python 'with' statement, should I use contextlib.closing?

后端 未结 2 1995
失恋的感觉
失恋的感觉 2021-02-05 06:00
from contextlib import closing

def init_db():
    with closing(connect_db()) as db:
        with app.open_resource(\'schema.sql\') as f:
            db.cursor().execute         


        
2条回答
  •  一整个雨季
    2021-02-05 06:28

    The only thing done by the with statement is to call __enter__ method before entering its block and __exit__ method before exiting it. If those methods are not defined the with statement won't work as you may expect. I don't know what is the return type of connect_db, but I guess that it could be many different things from different third-party libraries. So, your code without closing will probably work in many (all?) cases, but you never know what can be returned by connect_db.

提交回复
热议问题