Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python introspection

Tags:

python

Is it possible to apply code from imported module to module which import it? For example, I have module Debug where defined some decorator for debugging, for example:

def debug_func(f):
    def wrapper(*func_args, **func_kwargs):
        print(f(*func_args, **func_kwargs))
    return wrapper

What's the idea: It's would be useful if I can just

import Debug 

and all functions from current module will wrapped with decorator. Is it possible?

like image 689
Dmitriy Avatar asked Oct 22 '13 14:10

Dmitriy


1 Answers

Within Debug.py:

import functools
from types import FunctionType

def wrap_functions(module_dict):
    for k, f in module_dict.items():
        if not isinstance(f, FunctionType):
            continue
        def get_wrapper(f):
            def wrapper(*func_args, **func_kwargs):
                print(f(*func_args, **func_kwargs))
            return functools.wraps(f)(wrapper)
        module_dict[k] = get_wrapper(f)

At the bottom of the module you are wishing to debug:

import Debug
Debug.wrap_functions(globals())

Thanks (+1) to all the commenters who provided suggestions.

like image 94
Jim Garrison Avatar answered Oct 03 '22 08:10

Jim Garrison