Python Forum
Trouble with a context manager class made with dunders
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Trouble with a context manager class made with dunders
#1
I am running Python 3.6.3 in Spyder 3.2 and getting
Error:
TypeError: object() takes no parameters
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
with
statement 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?
Reply
#2
(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__.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Context-sensitive delimiter ZZTurn 9 1,394 May-16-2023, 07:31 AM
Last Post: Gribouillis
  How does open context manager work? deanhystad 7 1,266 Nov-08-2022, 02:45 PM
Last Post: deanhystad
  Decimal context stevendaprano 1 1,013 Apr-11-2022, 09:44 PM
Last Post: deanhystad
  How to create an app manager _ShevaKadu 8 3,722 Nov-01-2020, 12:47 PM
Last Post: _ShevaKadu
  TextIOWrapper.tell() with Python 3.6.9 in context of 0D/0A fschaef 0 2,040 Mar-29-2020, 09:18 AM
Last Post: fschaef
  a contact book - a class made to store data apollo 2 1,912 Jun-12-2019, 04:33 PM
Last Post: apollo
  Is it OK to use a context manager to simplify attribute access? nholtz 0 2,022 Jun-11-2019, 01:19 AM
Last Post: nholtz
  Smtplib: What does context argument means? Pythenx 1 3,051 Mar-27-2019, 06:25 PM
Last Post: nilamo
  Dealing with multiple context managers heras 5 4,604 Nov-16-2018, 09:01 AM
Last Post: DeaD_EyE
  Context Manager (with) wyattbiker 3 3,726 Jul-23-2018, 03:19 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

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