Код: Выделить всё
def wrap_module_with_warnings(module):
for fn_name, fn in inspect.getmembers(module):
if (not (inspect.isfunction(fn) or inspect.ismethod(fn))
or fn_name.startswith('_')
or inspect.getmodule(fn) is not module):
continue
@functools.wraps(fn)
def wrapped_fn(*args, **kwargs):
warnings.warn(f"The function {fn_name} was called.")
return fn(*args, **kwargs)
setattr(module, fn_name, wrapped_fn)
Код: Выделить всё
/tmp/question/main.py:22: UserWarning: The function random was called.
warnings.warn(f"The function {fn_name} was called.")
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
File /tmp/question/main.py:31
29 print(f"Output before wrapping: {mod.f()}")
30 wrap_module_with_warnings(mod)
---> 31 print(f"Output after wrapping: {mod.f()}")
File /tmp/question/main.py:23, in wrap_module_with_warnings..wrapped_fn(*args, **kwargs)
20 @functools.wraps(fn)
21 def wrapped_fn(*args, **kwargs):
22 warnings.warn(f"The function {fn_name} was called.")
---> 23 return fn(*args, **kwargs)
TypeError: 'module' object is not callable
Код: Выделить всё
import mod
if __name__ == '__main__':
print(f"Output before wrapping: {mod.f()}")
wrap_module_with_warnings(mod)
print(f"Output after wrapping: {mod.f()}")
Код: Выделить всё
import random
def f() -> int:
return random.randint(0, 1000)
Код: Выделить всё
In [1]: type(mod.f)
Out[1]: function
Код: Выделить всё
setattr(module, fn_name, (fn, wrapped_fn))
Код: Выделить всё
In [1]: mod.f[0]
Out[1]: int>
In [2]: mod.f[1]
Out[2]: int>
In [3]: type(mod.f[0])
Out[3]: function
In [4]: type(mod.f[1])
Out[4]: function
In [5]: mod.f[0]()
Out[5]: 785
In [6]: mod.f[1]()
/tmp/AscendSpeed/q/main.py:22: UserWarning: The function random was called.
warnings.warn(f"The function {fn_name} was called.")
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[6], line 1
----> 1 mod.f[1]()
File /tmp/AscendSpeed/q/main.py:23, in wrap_module_with_warnings..wrapped_fn(*args, **kwargs)
20 @functools.wraps(fn)
21 def wrapped_fn(*args, **kwargs):
22 warnings.warn(f"The function {fn_name} was called.")
---> 23 return fn(*args, **kwargs)
TypeError: 'module' object is not callable
Подробнее здесь: https://stackoverflow.com/questions/786 ... -typeerror