Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell if a class has a method `__call__`?

A very simple class isn't a callable type:

>>> class myc:
...     pass
... 
>>> c=myc()
>>> callable(c)
False

How can I tell if a class has a method __call__? Why do the following two ways give opposite results?

>>> myc.__call__
<method-wrapper '__call__' of type object at 0x1104b18>     

>>> __call__ in myc.__dict__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '__call__' is not defined

Thanks.

like image 908
Tim Avatar asked Dec 20 '25 03:12

Tim


1 Answers

myc.__call__ is giving you the __call__ method used to call myc itself, not instances of myc. It's the method invoked when you do

new_myc_instance = myc()

not when you do

new_myc_instance()

__call__ in myc.__dict__ gives you a NameError because you forgot to put quotation marks around __call__, and if you'd remembered to put quotation marks, it would have given you False because myc.__call__ isn't found through myc.__dict__. It's found through type(myc).__dict__ (a.k.a. type.__dict__, because type(myc) is type).


To check if myc has a __call__ implementation for its instances, you could perform a manual MRO search, but collections.abc.Callable already implements that for you:

issubclass(myc, collections.abc.Callable)
like image 199
user2357112 supports Monica Avatar answered Dec 22 '25 19:12

user2357112 supports Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!