A callable is an object that you can call.
When you define a function in Python:
>>> def greet(name): ... print("Hi", name) ...
You'll get a function object:
>>> greet <function greet at 0x7f61693c5940>
You can call a function object by putting parentheses (
()) after it:
>>> greet("Trey") Hi Trey
So, functions are callables, meaning they're objects that you're able to call.
Functions are not the only callables in Python.
>>> colors = ["green", "purple", "white", "pink"] >>> enumerate(colors) <enumerate object at 0x7f816c0ad400>
We can loop over that
enumerate object in order to see what's in it (related: looping with indexes):
>>> list(enumerate(colors)) [(0, 'green'), (1, 'purple'), (2, 'white'), (3, 'pink')]
Looping is the one thing we can do with an
The reason we get back an
enumerate object when we call the
enumerate function, is that
enumerate isn't actually a function: it's a class!
>>> enumerate <class 'enumerate'>
enumerate a function because we often use the word "function" in a fuzzy way in Python.
In Python we think in terms of duck typing. So if something is a function-like object (meaning it acts like a function) we may simply call it "a function".
enumerate function acts like a function (you call it using parenthesis) which means it's basically a function.
But more properly,
enumerate is a callable, meaning it's an object that can be called.
In Python, functions can be called and classes can be called.
Functions and classes are both callables, but you can actually invent your own callables too.
We have a class here called
class Person: def __init__(self, name): self.name = name def __call__(self): print("My name is", self.name)
When we call the
>>> trey <__main__.Person object at 0x7fbf9f3331c0>
We'll get back an instance of that class (a
>>> trey = Person("Trey")
We can also call that
Person object by putting parentheses after it:
>>> trey() My name is Trey
This works because we've implemented a
__call__ method on the
__call__ method to a class makes its class instances callable.
A callable is a function-like object, meaning it's something that behaves like a function. You can put parentheses after a reference to a callable to call it.
Functions are callables and classes are callables. They're not the only callables, but they're the primary two types of callables that you'll see in Python.
Hello friendly web visitor! 👋
This page is part of Python Morsels, an online Python skill-building service.
The best way to learn is by doing. In the case of Python that means writing Python code. If you'd like to improve your Python skills every week, try out Python Morsels by entering your email below to create an account.
Python Morsels topics pages are free and the first month's worth of exercises is free as well. You don't need to enter payment details to sign up.
You can find explanations of many other Python topics by signing up below.