Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do all callables have __name__?

Tags:

python

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?

like image 344
alejandro Avatar asked Nov 06 '15 22:11

alejandro


People also ask

What are Callables?

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!

What is callable () type in Python?

Definition and Usage The callable() function returns True if the specified object is callable, otherwise it returns False.

What makes a function callable?

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.

What is a callable object in C++?

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.


1 Answers

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))
like image 70
alejandro Avatar answered Oct 12 '22 17:10

alejandro