function - Calling context managers in python -



function - Calling context managers in python -

i trying find way explain why creating specialized context manager calling 1 works expected. not complaining!, great does. not sure if work until tested , hence sense loosing something.

just clarify considere next example:

>>> contextlib import contextmanager >>> @contextmanager ... def f(val): ... print(val) ... yield ... print(val+1) ... >>> >>> f(1): ... print(3) ... 1 3 2

and specialize it:

>>> def f42(): ... homecoming f(42) ... >>> f42(): ... print(3) ... 42 3 43

i guess confusing me why yield f bubbles through f42? why not need write f42 context manager explicitly.

there no difference between using f(42) in with statement , using in function returning it. with requires expression produces context manager.

you this:

cm = f(42) cm: print(3)

all python execute look in with <expression> statement , treats result of look context manager. how look produced context manager of no consequence.

in other words, f not context manager here, return value of phone call f().

python function yield contextmanager

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -