Verified Commit 20bf1e42 authored by Renato Alves's avatar Renato Alves 🌱

Show attribute error when using with on regular functions

parent 7fabd62b
......@@ -1354,9 +1354,28 @@ write to it and Python takes care of closing it for us.
#### with and generators
If we wanted to define our own functions that can work with the `with` keyword we can easily combine
the `contextmanager` from `contextlib` and a generator to create a
context managed function.
The `with` keyword is somewhat picky. Not all functions are compatible with it.
If you try to use it with a regular function you will likely see the following exception.
~~~
def myfunction():
return ["Yes", "No"]
with myfunction() as out:
print(out)
~~~
{: .language-python}
~~~
AttributeError: __enter__
~~~
{: .output}
To define our own functions that can work with the `with` keyword
we need to create a *context manager*.
Luckily, the `contextlib` library included in Python contains a `contextmanager` function
that does exactly this.
`contextmanager` is a function that takes as input a *generator* and turns it into
a context manager.
~~~
from contextlib import contextmanager
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment