python's `with` statement target is unexpectedly None

被刻印的时光 ゝ 提交于 2019-12-18 19:05:47

问题


seems like I do not understand something with---the python with statement.

Consider this class:

class test(object):
    def __enter__(self): pass
    def __exit__(self, *ignored): pass

now, when using it with with, like in

with test() as michael:
    print repr(michael)

I would expect some output like <test instance at memore blah>. But I get None.

Something wrong here? Any suggestions would help.

(I am using Python 2.6.6.)

EDIT:

Thanks to ephement for pointing me to the documentation. The __enter__ method should read

    def __enter__(self): return self

回答1:


From the with documentation:

If a target was included in the with statement, the return value from __enter__() is assigned to it.

If you def __enter__(self): return self, then your expected output is produced.




回答2:


From the docs:

object.__enter__(self)

Enter the runtime context related to this object. The with statement will bind this method’s return value to the target(s) specified in the as clause of the statement, if any.




回答3:


I get the same thing for repr(michael)

Try this instead:

m.__repr__()

I'm not entirely sure, but I think it has something to do with the fact that you haven't defined the repr method in your test class



来源:https://stackoverflow.com/questions/4835611/pythons-with-statement-target-is-unexpectedly-none

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