I have a decorator that logs the name of the decorated function (among other things).
Is it safe to access the __name__
attribute of the decorated function? Or is there some callable type that doesn't have name that I have not run into yet?
In Python, a callable is a function-like object, meaning it's something that behaves like a function. Just like with a function, you can use parentheses to call a callable. Functions are callables in Python but classes are callables too!
Definition and Usage The callable() function returns True if the specified object is callable, otherwise it returns False.
A callable object is an object which can be used and behaves like a function but might not be a function. By using the __call__ method it is possible to define classes in a way that the instances will be callable objects. The __call__ method is called, if the instance is called "like a function", i.e. using brackets.
A callable object is something that can be called like a function, with the syntax object() or object(args) ; that is, a function pointer, or an object of a class type that overloads operator() . The overload of operator() in your class makes it callable.
Answering my own question with a summary of other answers and comments.
Not all callables have __name__
.
Instances of classes that define __call__
may not have a __name__
attribute.
Objects created with functools.partial
do not have a __name__
attribute.
A workaround is to use the three argument getattr
:
name = getattr(callable, '__name__', 'Unknown')
Or use repr(callable)
instead of 'Unknown'
, which would include more information about the callable:
name = getattr(callable, '__name__', repr(callable))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With