0

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?

mouad
  • 67,571
  • 18
  • 114
  • 106
I159
  • 29,741
  • 31
  • 97
  • 132

1 Answers1

3

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>
mouad
  • 67,571
  • 18
  • 114
  • 106
  • The question was "How do you use the with statement?" not "Is there a library to use a with statement with functions?". I don't know why this answer was accepted. – Jpaji Rajnish Mar 04 '15 at 10:46
  • @ zoogleflatt Because it answer OP X problem http://mywiki.wooledge.org/XyProblem :) – mouad Mar 04 '15 at 13:59