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?

2
  • it's useful for files as it calls the close automatically on __exit__ Commented Apr 28, 2012 at 21:56
  • 2
    What would you expect with f(): print f() to accomplish? Commented Apr 28, 2012 at 22:00

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

2 Comments

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.
@ zoogleflatt Because it answer OP X problem mywiki.wooledge.org/XyProblem :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.