Trouble with a context manager class made with dunders - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Trouble with a context manager class made with dunders (/thread-7877.html) |
Trouble with a context manager class made with dunders - Regulus - Jan-28-2018 I am running Python 3.6.3 in Spyder 3.2 and getting at with ManagedFile('hello.txt') as f: class ManagedFile: def _init_(self, name): self.name = name def _enter_(self): self.file = open(self.name, 'w') return self.file def _exit_(self, exc_type, exc_val, exc_tb): if self.file: self.file.close() with ManagedFile('hello.txt') as f: f.write('hello there!') f.write('bye')Obviously ManagedFile isn't a function that excepts parameters. But according to the author, _enter_ is supposed to work with the withstatement to enter its content. The last three lines are supposed to create a new file and write to it. The class is supposed to function as a "context manager," which is a new term to me. Is there something wrong you see in the code? RE: Trouble with a context manager class made with dunders - Gribouillis - Jan-28-2018 (Jan-28-2018, 02:40 PM)Regulus Wrote: Is there something wrong you see in the code?Yes there should be double underscores on each side for __init__, __enter__, exit__ .
|