Reputation: 31109
I'm reading PEP 343 and trying to make some examples. But it's not really clear to me now. Especially because I have an error:
>>> def f():
... return 'f'
...
>>> with f(): # or as f
... print f() # or f
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: __exit__
Indeed, the function has no method __exit__
. So how do you use the with
statement?
Upvotes: 0
Views: 983
Reputation: 70021
If you want to use the with statement with a function you can use the contextlib.contextmanager decorator.
Example from the doc:
from contextlib import contextmanager
@contextmanager
def tag(name):
print "<%s>" % name
yield
print "</%s>" % name
>>> with tag("h1"):
... print "foo"
...
<h1>
foo
</h1>
Upvotes: 3