Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python's `with` statement target is unexpectedly None

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
like image 245
Prestel Nué Avatar asked Jan 29 '11 06:01

Prestel Nué


1 Answers

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.

like image 93
ephemient Avatar answered Sep 22 '22 09:09

ephemient