callable() function in Python

Programming PYTHON BUILT-IN FUNCTIONS SERIES Image

    Introduction

    The callable() method returns True if the object passed to it appears to be callable, else it returns False. Callable means something that can be called.

    The syntax of callable() method is:

    callable(object)

    The callable() method takes a single parameter object and can return one of the two possible values:

    • True if the object appears to be callable
    • False if the object doesn't appear to be callable

    Note: In some cases, callable() returns True, but the call to the object can still fail. However, if the callable() method returns False, the call to the object will definitely fail.


    Example 1

    def my_func():
        print("I am a function, I can be called!")
    
    
    func = my_func
    print(callable(func))
    
    my_var = 20
    print(callable(my_var))
    

    Output:

    True
    False

    In the first case, an object func of the my_func function is created and passed to the callable() method which appears to be callable. Hence it returns True. However, in the second case, an object my_var is passed which is definitely not callable. Hence, it returns False.
     

    Example 2

    The callable() method checks if the argument is either of the following:

    1. an instance of class with a __call__ method
    2. of a type that indicates callability such as method or function
    class TestClass1:
        def __call__(self):
            print("Test Class 1 called")
    
    obj1 = TestClass1()
    print(callable(obj1))
    obj1()

    Output:

    True
    Test Class 1 called

    In the above example, the TestClass1 has __call__ method implemented, and hence appears to be callable, and is callable.

    class TestClass2:
        def my_method(self):
            print("Test Class 2 called")
    
    obj2 = TestClass2()
    print(callable(obj2))
    obj2()

    Output:

    False
    Traceback (most recent call last):
      File "D:\Quarantine\Test\Blog-Codes\Built-Ins\callable\ex2.py", line 17, in <module>
        obj2()
    TypeError: 'TestClass2' object is not callable

    However, in the above example, the TestClass2 appears to be callable, but the instance of the class is not callable, and hence an error is thrown.
     

    Conclusion

     

    In this part, we learned about the Python callable() function with the help of examples.

    If you liked this post, you can consider subscribing to my newsletter.


    If you read this far, support the author to show them you care.

    0 Comments

    To add a comment, please Signup or Login

    OR