Home > Back-end >  Check if class instances are callable without instantiating
Check if class instances are callable without instantiating

Time:03-23

How to check if the instances of a given class are callable. This is easy to do if you instantiate the class and then use callable(). But my question is how to check this without instantiating. Take for example the Calendar class:

>>> import calendar
>>> callable(calendar.Calendar())
False

I want to do the same but without instantiating, i.e. implement some function callable_class_instances() such that:

>>> import calendar
>>> callable_class_instances(calendar.Calendar)
False
>>> 
>>> class MyFunc:
...     def __init__(self):
...         print('Should not run on callable_class_instances call.')
...     def __call__(self):
...         print('MyFunc instance called.')
>>> callable_class_instances(MyFunc)
True

Is there any simple way to do this which does not look like a hack?

CodePudding user response:

From the docs:

Note that classes are callable (calling a class returns a new instance); instances are callable if their class has a __call__() method.

The problem with my previous attempt (hasattr) was that all classes have a __call__ method so that we can initialise them. This should work most of the time:

>>> import types

>>> import calendar
>>> isinstance(calendar.Calendar.__call__, types.FunctionType)
False

Note that this will not work for non-Python __call__ implementations.

  • Related