Created
April 10, 2015 16:59
-
-
Save Averroes/78c98dcf81a1b27607ef to your computer and use it in GitHub Desktop.
monkeypatching modules on import
This file contains hidden or 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
| from postimport import when_imported | |
| from functools import wraps | |
| def logged(func): | |
| @wraps(func) | |
| def wrapper(*args, **kwargs): | |
| print('Calling', func.__name__, args, kwargs) | |
| return func(*args, **kwargs) | |
| return wrapper | |
| # Example | |
| @when_imported('math') | |
| def add_logging(mod): | |
| mod.cos = logged(mod.cos) | |
| mod.sin = logged(mod.sin) | |
| if __name__ == '__main__': | |
| import math | |
| print(math.cos(2)) | |
| print(math.sin(2)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment