Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Custom file class
#10
You don't need a base class to create a context manager, you just need to implement the enter/exit interface.

>>> class TimeHistory:
...   def __init__(self, filename):
...     self.filename = filename
...     self.fobj = None
...   def __enter__(self):
...     self.fobj = open(self.filename, "r")
...     return self
...   def __exit__(self, *args):
...     if self.fobj:
...         self.fobj.close()
...     self.fobj = None
...
>>> with TimeHistory('test.txt') as file:
...   print(file)
...
<__main__.TimeHistory object at 0x000001AA1BB40AF0>
Reply


Messages In This Thread
Custom file class - by deanhystad - Jan-26-2021, 08:36 PM
RE: Custom file class - by Larz60+ - Jan-26-2021, 10:14 PM
RE: Custom file class - by deanhystad - Jan-27-2021, 12:57 PM
RE: Custom file class - by Larz60+ - Jan-27-2021, 08:09 PM
RE: Custom file class - by deanhystad - Jan-27-2021, 09:07 PM
RE: Custom file class - by Larz60+ - Jan-27-2021, 09:37 PM
RE: Custom file class - by deanhystad - Jan-27-2021, 09:46 PM
RE: Custom file class - by Larz60+ - Jan-27-2021, 09:47 PM
RE: Custom file class - by deanhystad - Jan-27-2021, 11:05 PM
RE: Custom file class - by nilamo - Jan-28-2021, 06:10 PM
RE: Custom file class - by deanhystad - Jan-31-2021, 08:43 PM
RE: Custom file class - by nilamo - Feb-01-2021, 05:09 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
Question How to move a class to a custom module? python300 4 1,593 Mar-08-2022, 09:19 PM
Last Post: python300
  How to serialize custom class objects in JSON? Exsul1 4 3,530 Sep-23-2019, 08:27 AM
Last Post: wavic
  Duplicate output when calling a custom function from the same file? road2knowledge 2 2,414 May-10-2019, 07:58 AM
Last Post: road2knowledge
  Class File ankur2207 1 2,822 Sep-07-2017, 02:22 PM
Last Post: ichabod801
  PlaintextCorpusReader connectives custom file raky 1 3,045 Jun-16-2017, 08:26 PM
Last Post: raky

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020