Python Callables: The Basics and the Secrets | by Marcin Kozak | Oct, 2023


Learn how powerful Python callables can be.

Marcin Kozak
Towards Data Science
Python has many callables.
In Python, there are many callables to choose from. Photo by Pavan Trikutam on Unsplash

In programming languages, callable objects are typically associated with functions, and for good reason. Functions are perhaps the best examples of callable objects, but they are not the only ones. In Python, there are many other callable types, which can be incredibly useful and powerful. You can also create your own callable objects. This article is about both.

A callable is an object that can be called using a pair of parentheses, like for example below, where we use the built-in function sum():

>>> sum([1, 1, 1])

A call to a callable, depending on its definition, can be

  • without any arguments, as in no_args_callable()
  • or a series of positional and/or keyword arguments, as in args_callable(arg1, arg2), args_callable(arg1, arg2=value2) or args_callable(arg1=value1, arg2=value2)

Above, I described a callable as a noun. The word callable, however, is also used as an adjective, meaning being a callable. Therefore, a callable is the same as a callable object.

Python has a built-in function , callable(), that checks if an object is callable, or — in other words — if it’s a callable. Consider the following examples of actual callables:

>>> callable(lambda x: x + 1)
>>> callable(print)
>>> def foo(): ...
>>> callable(foo)

The below objects are not callables:

>>> callable(None)
>>> callable(10)
>>> callable("hello")

The positive examples above were about functions, which are what most people associate with callables. However, in fact, every Python class is callable. If you know the basics of object-oriented programming in Python, you know that to create an instance of a class, you do the following:¹

>>> class Empty: ...

This looks exactly like a call, and it is — and that is why Python classes are callables.

This code shows that the Empty class is callable, but the truth is, every single Python class is callable. However, in Python…

Source link

This post originally appeared on TechToday.

Leave a Reply

Your email address will not be published. Required fields are marked *