-
-
Save foxmask/1b8f19d2a4c458d02a979a50db3aae4f to your computer and use it in GitHub Desktop.
Use contextmanager to create a decorator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Read docs here: https://docs.python.org/3/library/contextlib.html | |
>>> from contextlib import contextmanager | |
>>> | |
>>> | |
>>> @contextmanager | |
... def deco_and_cm(): | |
... print('Hello') | |
... yield | |
... print('Goodbye') | |
... | |
>>> | |
>>> with deco_and_cm(): | |
... print('Nice to meet you!') | |
... | |
Hello | |
Nice to meet you! | |
Goodbye | |
>>> | |
>>> @deco_and_cm() | |
... def fun(name): | |
... print('Nice to meet you, %s!' % name) | |
... | |
>>> | |
>>> fun('Tomek') | |
Hello | |
Nice to meet you, Tomek! | |
Goodbye | |
>>> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment