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

Category:

Harness the Potential of AI Tools with ChatGPT. Our blog offers comprehensive insights into the world of AI technology, showcasing the latest advancements and practical applications facilitated by ChatGPT’s intelligent capabilities.

PYTHON PROGRAMMING

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])
3

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)
True
>>> callable(print)
True
>>> def foo(): ...
>>> callable(foo)
True

The below objects are not callables:

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

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…

Discover the vast possibilities of AI tools by visiting our website at
https://chatgptoai.com/ to delve deeper into this transformative technology.

Reviews

There are no reviews yet.

Be the first to review “Python Callables: The Basics and the Secrets | by Marcin Kozak | Oct, 2023”

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

Back to top button