Python Callable()

Python Callable refers to objects that are able to be called. We know to not use a word in its own definition, so let’s dive deeper.

A callable is either a class with a __call__ method, or else a function. When you call a function or class, you are telling python to execute this piece of code.

You’ll most commonly be able to tell which items are callables because of the () at the end of their name. Ex: pd.DataFrame.max(). In this case, .max() is the callable since it is a function being called on the Pandas Dataframe.

Fun fact: Callable is also a python keyword. callable(your_item) will return True if your_item is able to be called

Let’s take a look at a python callable code sample


Python Callable

DataIndependent - Callable

A callable is a function or class that is able to be called. When you call a function or class, you are telling python to execute a piece of code.

Let's take a look at a few callable examples

In [10]:
import numpy as np

x = np.linspace(start=0, stop=10, num=15)
x
Out[10]:
array([ 0.        ,  0.71428571,  1.42857143,  2.14285714,  2.85714286,
        3.57142857,  4.28571429,  5.        ,  5.71428571,  6.42857143,
        7.14285714,  7.85714286,  8.57142857,  9.28571429, 10.        ])
In [15]:
# If you call a function, but don't put on the "()", you will just get the function returned to you
x.max
Out[15]:
<function ndarray.max>
In [16]:
# But calling the function (which is a callable) with the () at the end, you'll run the function
In [17]:
x.max()
Out[17]:
10.0

Now let's play around with items that are not callables and see what python does

First, lets call .ndim, which will return the number of dimensions to us in numpy

In [20]:
x.ndim
Out[20]:
1

Now let's try 'calling' it

In [21]:
x.ndim()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-21-ee63ff362b3a> in <module>
----> 1 x.ndim()

TypeError: 'int' object is not callable

Oh no! An error. Whenever I see this error, I basically know that I tried 'calling' something that was not able to be called. This is most commonly an oversite on my part.

I need to go back and look at all of my function calls and make sure I know what they are doing.

In [ ]:
 

Link to code above

Check out more Python Vocabulary on our Glossary Page