Created
May 18, 2016 22:24
-
-
Save buckbaskin/8b0d7239b7427ce0fae738ba329d51bd to your computer and use it in GitHub Desktop.
A simple decorator function that applies itself to all elements in a module. The example is modifying the math module to print a string for every function call.
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
def module_wrapper(module): | |
def print_wrap(subfunc): | |
def internal_func(*args, **kwargs): | |
print("I'm going to run this function") | |
return subfunc(*args, **kwargs) | |
return internal_func | |
for func_name in dir(module): | |
setattr(module, func_name, print_wrap(getattr(module, func_name))) | |
if __name__ == '__main__': | |
print('demo:') | |
import math | |
module_wrapper(math) | |
# both of these will print "I'm going to run this function" | |
math.cos(0) | |
math.sin(90) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment