liveBook · Manning

Callable

As explained in Python How-To

callable is a Python built-in function that returns whether an object can be invoked with the call operator.

Can an object be used with parentheses? Python’s built-in callable checks whether an object can be invoked with the call operator (). Functions and classes are callable; ordinary instances are not necessarily callable. section 10.5 section 10.5.4

Check a function

def doubler(x): return 2 * x assert callable(doubler) The assertion passes because doubler is a function and can be called as doubler(3). section 10.5

Callability does not mean “function.” Calling a class creates an instance, while calling a function performs its defined operation. For example, dict and range are classes, whereas callable and hash are functions. Either kind of object can be passed where a callable is expected, such as the key argument to sorted. section 10.5.1 section 10.5.3

Use a class as a sorting key

cards = [10, 1, 'J', 'A'] print(sorted(cards, key=str)) # [1, 10, 'A', 'J'] Converting each card to a string permits sorting but puts A before J. A class that converts face cards to numeric ranks can instead serve as the key: class PokerOrder(int): def __new__(cls, x): ranks = {'J': 11, 'Q': 12, 'K': 13, 'A': 14} return super().__new__(cls, ranks.get(x, x)) print(sorted(cards, key=PokerOrder)) # [1, 10, 'J', 'A'] section 10.5.3

A custom instance can also become callable by implementing __call__. This makes a class-based decorator possible: the class receives the decorated function, and its instance handles later calls. Unlike a function-based decorator, the decorated name then refers to an instance, which can hold additional attributes. section 10.5.4 section 10.5.5

import time

class TimeLogger:
   def __init__(self, func):
       def logger(*args, **kwargs):
           start = time.time()
           result = func(*args, **kwargs)
           print(f"Calling {func.__name__}: {time.time() - start:.5f}")
           return result
       self._logger = logger

   def __call__(self, *args, **kwargs):
       return self._logger(*args, **kwargs)

TimeLogger stores a logging function on the instance and forwards calls through __call__, making that instance usable as a decorator result. section 10.5.4

How Python How-To covers it

How deep it goes
Defines callable and works through sorting keys and __call__-based decorators, while deferring decorator best practices.
Examples
Tests a doubling function, sorts poker cards with a class key, and logs execution time with a class decorator.
What it assumes
Introduces callability from basic object behavior but assumes familiarity with decorators for their class-based variation.
What you can do after
Build it from scratch: create a callable sorting key or class-based decorator, and check an object with callable.
How it connects
Links callability to classes, functions, sorting keys, decorators, and __call__.

Also explained in

Compare how 5 books explain callable →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python How-To. The section links point to the parts of the book it draws on.