I am running micropython on my ESP32_S2 Saola board and I am trying determine the name of a function passed as a parameter to another function (to be used as a callback).
Produces error: AttributeError: 'function' object has no attribute '__name__'
How do I retrieve the name of the function passed? If I do a 'print(func)' it prints the name of the function to console, so it is known somewhere.
As can be seen way below in full example I am trying to add a new method to a class using a @add_method decorator and it works.....except the I had to hardcode the function name 'foo'.
Code: Select all
setattr(cls, 'foo', wrapper)
Code: Select all
setattr(cls, func.__name__, wrapper)
Code: Select all
def add_method(cls):
def decorator(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
return func(*args, **kwargs)
# print(func)
# print(sys.modules[func.__globals__['__name__']])
setattr(cls, 'foo', wrapper) # Hardcoded function name 'foo'...Not ideal
# setattr(cls, func.__name__, wrapper)
# Note we are not binding func, but wrapper which accepts self but does exactly the same as func
return func # returning func means func can still be used normally
return decorator
class A:
pass
# No trickery. Class A has no methods nor variables.
a = A()
try:
a.foo()
except AttributeError as ae:
print(f'Exception caught: {ae}') # 'A' object has no attribute 'foo'
# Decorator can be written to take normal functions and make them methods
@add_method(A)
def foo():
print('hello world!')
a.foo()