An example for Decorator
Monkey Patching
by Viet Hung Nguyen
hvn@pymi.vn
or hvnsweeting every elsewhere
There is no ideal world...
In the ideal world...
- Your code always run
- Library functions have all options you need (e.g: retry)
- API allows unlimited requests
In the real world
- Your code sometimes fail
- Library functions DO NOT have all options you need (e.g: retry)
- API allows unlimited requests only with UNLIMITED $$$
A library of real world
import random
class LimitError(Exception):
pass
def query_user_data(name):
choice = random.randrange(1, 7)
if choice == 1:
raise LimitError
else:
return 'User data of {}: {}'.format(name, choice)
def query_team_data():
choice = random.randrange(1, 7)
if choice == 1:
raise LimitError
else:
return 'User data'An user program in real world
import lib
def main():
for username in ['hvn', 'htl', 'tuda', 'hoangp']:
response = lib.query_user_data(username)
print(response)
main()How to handle those errors?
Try/except
How to handle those errors?
If we use function in multiple place => multiple try/except...
try/except every where
Show off time for Decorator

What is a decorator?
A function returning another function, usually applied as a function transformation using the @wrapper syntax.
https://docs.python.org/3/glossary.html#term-decorator
What is a decorator?
Input function ----|DECORATOR| ----> new function
outfunc = decorator(infunc)
Decorator is a good solution
- 1 logic for all functions
newfunc = decorator(oldfunc)
newfunc()
Replace all oldfunc -> newfunc?
Text
Replace a function
lib.function = decorator(lib.function)
No other change.
Monkey patching
Text
Real world library
AWS retry
https://github.com/linuxdynasty/awsretry/blob/master/awsretry/__init__.py#L65
Monkey patching in gevent:
http://www.gevent.org/intro.html#monkey-patching
Text
Lessons
- When one needs to transform (add ability to functions), use decorator
- Monkey patching is cool
Text
Q&A
Thank you!
One example for decorator and monkey patching
By hvnsweeting
One example for decorator and monkey patching
Implement retry for functions that do not support it.
- 172