With statement in python is returning None object even though __init__ method works

巧了我就是萌 提交于 2019-12-02 00:09:12

问题


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..


回答1:


The context manager protocol is handled by the __enter__() and __exit__() methods; the former must return the value to assign.



来源:https://stackoverflow.com/questions/16659231/with-statement-in-python-is-returning-none-object-even-though-init-method-wo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!