hasattr
used to check if the object is callable PTC-W0035hasattr
used to check if the object is callable 322
323 # Allow callable classes to take a context
324 if (
325 hasattr(__obj, "__call__") # noqa: B004 326 and _PassArg.from_obj(__obj.__call__) is not None # type: ignore
327 ):
328 __obj = __obj.__call__ # type: ignore
It is unreliable to use hasattr(object, '__call__')
to check if an object is callabe as it can give wrong results if object
implements custom __getattr__
or its __call__
is itself not callabe. It is recommended to use the callable
built-in instead.
Here's an example:
In [1]: class FooBar:
...: def __init__(self):
...: self.foo = "Foo"
...: self.bar = "Bar"
...:
...: def __getattr__(self, key):
...: return key
...:
In [2]: instance = FooBar()
When hasattr
is used to check if instance
is callable, it return True
In [3]: hasattr(instance, '__call__')
Out[3]: True
But when checked using the callable
built-in, it returns False
In [4]: callable(instance)
Out[4]: False
When instance
is called, here's the traceback:
In [5]: instance()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-23-5dd8ea036ab8> in <module>
----> 1 instance()
TypeError: 'FooBar' object is not callable