Reputation: 63162
For a DB class with the following init method:
class DB:
def __init__(self, dbprops):
self.dbprops = dbprops
self.conn = self.get_connection(self.dbprops)
debug("self.conn is %s" %self.conn)
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
if not self.conn is None:
self.close()
And for a client method invoking it as follows:
with DB(self.dbprops) as db:
if not db:
raise Exception("Db is None inside with")
return db.get_cmdline_sql()
The output shows the debug message - thus the init method was successfully called:
File "./classifier_wf.py", line 28, in get_cmdline_mysql
raise Exception("Db is None inside with")
Exception: Db is None inside with
Update: fixed the enter method to return a DB object . But need help on how to invoke it:
def __enter__(self, dbprops):
return DB(dbprops)
Invoking it with a single parameter does not work apparently:
with DB(dbprops) as db:
TypeError: __enter__() takes exactly 2 arguments (1 given)
Now I do not follow because the "self" is supposed to be filled in automatically..
Upvotes: 6
Views: 3490
Reputation: 799062
The context manager protocol is handled by the __enter__()
and __exit__()
methods; the former must return the value to assign.
Upvotes: 11