Skip to content

Instantly share code, notes, and snippets.

@buckbaskin
Created May 18, 2016 22:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save buckbaskin/8b0d7239b7427ce0fae738ba329d51bd to your computer and use it in GitHub Desktop.
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.
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