In programming, a callable is something that can be called. In this post, we want to discuss Python callable() Explained.
In Python, a callable is anything that can be called, using parentheses and maybe with some arguments. Functions, Generators, and Classes are inherently callable in Python. The callable() method takes an object and returns a boolean.
- True – if the object is callable
- False – if the object is not callable
The callable() method checks if the object is either of the two –
- An instance of a class with a __call__ method
- Is of a type that has a which indicates callability such as in functions, classes, etc., or has a non-null tp_call (c struct) member.
Since functions are callable in Python.
1 2 3 4 5 | def my_function(): print("Hi, I'm a function") callable(my_function) |
Output
1 2 3 | True |
This indicates that every time we create a function, Python creates a callable object for it. You can also verify the presence of __call__ attribute.
1 2 3 | my_function.__call__ |
Output
1 2 3 | <method-wrapper '__call__' of function object at 0x7f08706d5840> |
Similarly for a Class,
1 2 3 4 5 6 7 | class MyClass(): def my_method(self): print("Hi, I am a class method") callable(MyClass) |
Output
1 2 3 | True |
However, if you create an object and run the callable() method over that then you will observe that class objects are not inherently callable in Python.
1 2 3 4 | my_obj = MyClass() callable(my_obj) |
Output
1 2 3 | False |
If you try to call the object with parenthesis you will get an error message saying the object is not callable.
1 2 3 | my_obj() |
Output
1 2 3 | TypeError: 'MyClass' object is not callable |
However, we can create classes having the __call__ method which makes instances of the class callable.
Making Class objects callable in Python
1 2 3 4 5 6 7 8 9 10 11 | class MyClass(): def __call__(self): print("I am callable now") def my_method(self): print("Hi, I am a class method") my_obj = MyClass() callable(my_obj) |
Output
1 2 3 | True |
Now if you call the object the __call__Â method will run.
1 2 3 | my_obj() |
Output
1 2 3 | I am callable now |
Python callable() Explained
The article was published on December 21, 2020 @ 3:30 PM
Leave a Comment