Python Forum
How does open context manager work?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How does open context manager work?
#1
While answering a question in another thread I wrote this:
import contextlib
 
@contextlib.contextmanager
def CreateFile(FilePath):
    file = open(FilePath, 'w', encoding="utf-8")
    file.write("Court,Location,Citation Number,Case Description,File Date\n")
    yield file
    file.close()
I occasionally create context managers when writing code that requires "cleaning up", but I never did it for a file. To use the code above, I am forced to us a context manager:
with CreateFile(filename) as file:
    # do stuff with file
I cannot do this because CreateFile creates a context object, not a file:
file = CreateFile(filename)
So how does open() let me do this?
file_one = open(filelename_one)
with open(filename_two) as file_two:
    # do file_two stuff
The best I can do to mimic open() is this:
class CreateFile():
    def __init__(self, filename, mode="w", encoding="utf-8"):
        print(f"CreateFile({filename})")
        self.file = open(filename, mode, encoding=encoding)
        self.file.write("Court,Location,Citation Number,Case Description,File Date\n")

    def __enter__(self):
        print("enter")
        return self.file

    def __exit__(self, *_):
        print("exit")
        self.file.close()

    def __getattr__(self, attribute):
        print(f"__getattr__({attribute})")
        return getattr(self.file, attribute)

file = CreateFile("junk.txt")
file.write("This is a test\n")
print(file.tell())
file.close()

print("\n")
with CreateFile("junk2.txt") as file:
    file.write("This is a test\n")
Output:
CreateFile(junk.txt) __getattr__(write) __getattr__(tell) 75 __getattr__(close) CreateFile(junk2.txt) enter exit
Reply


Messages In This Thread
How does open context manager work? - by deanhystad - Nov-07-2022, 06:15 PM
RE: How does open context manager work? - by Yoriz - Nov-07-2022, 06:17 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How to not open the context menu if a mouse gesture is executed? MicheliBarcello 2 697 Aug-22-2023, 02:47 PM
Last Post: deanhystad
  Open a new window does not work Nietzsche 4 1,233 Jun-14-2023, 08:52 AM
Last Post: Nietzsche
  with open context inside of a recursive function billykid999 1 619 May-23-2023, 02:37 AM
Last Post: deanhystad
  Context-sensitive delimiter ZZTurn 9 1,621 May-16-2023, 07:31 AM
Last Post: Gribouillis
  Decimal context stevendaprano 1 1,085 Apr-11-2022, 09:44 PM
Last Post: deanhystad
  How to create an app manager _ShevaKadu 8 3,892 Nov-01-2020, 12:47 PM
Last Post: _ShevaKadu
  TextIOWrapper.tell() with Python 3.6.9 in context of 0D/0A fschaef 0 2,109 Mar-29-2020, 09:18 AM
Last Post: fschaef
  Is it OK to use a context manager to simplify attribute access? nholtz 0 2,081 Jun-11-2019, 01:19 AM
Last Post: nholtz
  Smtplib: What does context argument means? Pythenx 1 3,141 Mar-27-2019, 06:25 PM
Last Post: nilamo
  Dealing with multiple context managers heras 5 4,821 Nov-16-2018, 09:01 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

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