hasattr
used to check if the object is callable PTC-W0035hasattr
used to check if the object is callable51 else:
52 converter = None
53
54 if hasattr(converter, "__call__"):55 return converter(value)
56
57 return value
hasattr
used to check if the object is callable153
154def wrong_callable():
155 number = ImaginaryNumber()
156 if hasattr(number, "__call__"):157 return number()
158
159
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