Python's 'with' statement versus 'with .. as'

后端 未结 3 900
陌清茗
陌清茗 2020-12-28 18:53

Having just pulled my hair off because of a difference, I\'d like to know what the difference really is in Python 2.5.

I had two blocks of code (dbao.

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-28 19:13

    It may be a little confusing at first glance, but

    with babby() as b:
        ...
    

    is not equivalent to

    b = babby()
    with b:
        ...
    

    To see why, here's how the context manager would be implemented:

    class babby(object):
        def __enter__(self):
            return 'frigth'
    
        def __exit__(self, type, value, tb):
            pass
    

    In the first case, the name b will be bound to whatever is returned from the __enter__ method of the context manager. This is often the context manager itself (for example for file objects), but it doesn't have to be; in this case it's the string 'frigth', and in your case it's the database cursor.

    In the second case, b is the context manager object itself.

提交回复
热议问题