Python inspect.getmembers does not return the actual function when used with decorators

I have three python functions:

def decorator_function(func) def wrapper(..) return func(*args, **kwargs) return wrapper def plain_func(...) @decorator_func def wrapped_func(....) 

inside module A.

Now I want to get all the functions inside this module A, for which I:

 for fname, func in inspect.getmembers(A, inspect.isfunction): # My code 

The problem is that the value of func is not what I want.

This will be decorator_function, plain_func and wrapper (instead of wrapped_func).

How can I make sure wrapped_func is returning instead of a shell?

+4
source share
2 answers

If you want to keep the name of the original function visible from the outside, I think you can do it with

 @functools.wraps 

as a decorator for your decorator

here is an example from standard documents

 >>> from functools import wraps >>> def my_decorator(f): ... @wraps(f) ... def wrapper(*args, **kwds): ... print('Calling decorated function') ... return f(*args, **kwds) ... return wrapper ... >>> @my_decorator ... def example(): ... """Docstring""" ... print('Called example function') ... >>> example() Calling decorated function Called example function >>> example.__name__ 'example' >>> example.__doc__ 'Docstring' 
+5
source

You can access the pre-decorated function:

 wrapped_func.func_closure[0].cell_contents() 

For instance,

 def decorator_function(func): def wrapper(*args, **kwargs): print('Bar') return func(*args, **kwargs) return wrapper @decorator_function def wrapped_func(): print('Foo') wrapped_func.func_closure[0].cell_contents() 

prints

 Foo # Note, `Bar` was not also printed 

But really, if you know you want to access a pre-decorated function, then it would be much easier to define

 def wrapped_func(): print('Foo') deco_wrapped_func = decorator_function(wrapped_func) 

So wrapped_func will be a pre-decorated function, and deco_wrapped_func will be a decorated version.

+6
source

Source: https://habr.com/ru/post/1395712/


All Articles