Python Professional — Hard
Explanation
The correct output is "enter 42 exit" because the context manager function "managed()" prints "enter" before yielding 42, then prints "exit" after the yield statement. The value 42 is printed when the context manager is used with the "with" statement.
Ready to go further?
Related questions
- What is the output of the following code? from contextlib import contextmanager @contextmanager def managed(): print('enter') try: yield 42 finally: print('exit') with managed() as v: print(v)
- What is the output of the following code? def decorator(cls): original_init = cls.__init__ def new_init(self, *args, **kwargs): original_init(self, *args, **kwargs) self.decorated = True cls.__init__ = new_init return cls @decorator class Foo: def __init__(self): self.value = 1 f = Foo() print(f.value, f.decorated)
- What is the purpose of `__new__` in Python?
- What is the purpose of Python's __init_subclass__ cls parameter's keyword arguments, and how are they passed?
- What is the output of the following code involving __missing__? class DefaultList(dict): def __missing__(self, key): self[key] = [] return self[key] d = DefaultList() d['a'].append(1) d['a'].append(2) d['b'].append(3) print(d)
- What is the purpose of `weakref.ref()` in Python?
