I have the following code:
import unittest
from contextlib import contextmanager
def outer(with_context=False):
def inner():
# Some code here
if with_context:
with unittest.TestCase().assertRaises(KeyError):
yield
else:
print("No context")
# Some more code here
if with_context:
return contextmanager(inner)
else:
return inner
no_context_func = outer()
no_context_func() # "No context" does not get printed
my_dict = {"valid_key": 123}
context_func = outer(with_context=True)
with context_func():
my_dict["valid_key"] # Works fine
Why is "No context" not printed to the console? In fact, it seems that the function call to no_context_func
is skipped completely, as I can not set a break point at the print("No context")
line. Removing the content of the if with_context:
branch prints "No context" but why does the yield influence the program execution although it is not in a branch that gets executed?
Edit:
I have added comments to the code example showing that there is more code before and after the if/else in the inner function. I eventually want to use outer
as a decorator that I can parameterize and that I can use to decorate regular functions and context managers, like assertRaises
. My question is whether there is a way of using the same decorator for both cases or if I will have to use separate decorators, one for regular functions and one for context managers. That unfortunately means that I have to duplicate the content of the inner function.