Skip to content

Instantly share code, notes, and snippets.

@Averroes
Created April 10, 2015 16:59
Show Gist options
  • Select an option

  • Save Averroes/78c98dcf81a1b27607ef to your computer and use it in GitHub Desktop.

Select an option

Save Averroes/78c98dcf81a1b27607ef to your computer and use it in GitHub Desktop.
monkeypatching modules on import
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