Skip to content

Instantly share code, notes, and snippets.

@foxmask
Forked from oinopion/deco.py
Created December 2, 2016 08:08
Show Gist options
  • Save foxmask/1b8f19d2a4c458d02a979a50db3aae4f to your computer and use it in GitHub Desktop.
Save foxmask/1b8f19d2a4c458d02a979a50db3aae4f 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