Skip to content

Instantly share code, notes, and snippets.

@oinopion
Last active December 2, 2016 08:08
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save oinopion/becac820c60bdf9e93ba49fdce4cf797 to your computer and use it in GitHub Desktop.
Save oinopion/becac820c60bdf9e93ba49fdce4cf797 to your computer and use it in GitHub Desktop.
Use contextmanager to create a decorator
# 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