ZetCode

Python callable function

last modified November 29, 2026 Python 3.15

In this article we show what the callable builtin tests, and where that test is useful.

The function answers one question: does the type of the object provide a __call__ slot? If it does, the object can be followed by parentheses. It says nothing about how many arguments the call needs or whether the call will succeed.

Reading attributes and types at runtime is the subject of Python introspection. The protocol behind a callable instance is described in Python __call__ method, and filtering with a predicate function in Python predicate.

What the test looks at

callable looks at the type, never at the instance dictionary. Adding a __call__ attribute to a single object does not make that object callable.

type_level.py
class Falcon:
    pass


bird = Falcon()
bird.__call__ = lambda: 'not really'

print(callable(Falcon))
print(callable(bird))
print(hasattr(bird, '__call__'))

try:
    bird()
except TypeError as e:
    print('TypeError:', e)

The attribute exists on the instance, so hasattr reports True, but the call fails because Python looks for __call__ on the type. This is the mistake behind the advice to check hasattr(obj, '__call__'): the two tests are not equivalent.

The class itself is callable because its metaclass, type, provides __call__. That is how Falcon() creates an instance.

$ python type_level.py
True
False
True
TypeError: 'Falcon' object is not callable

Functions, classes, and values

Most objects that represent behaviour are callable, and most objects that represent data are not.

kinds.py
def greet(name):
    return f'Hello there, {name}'


values = [greet, len, int, str.upper, [].append, 'falcon', 42, None, [1, 2]]

for value in values:
    print(f'{type(value).__name__:26} {callable(value)}')

Functions, builtins, classes, method descriptors such as str.upper, and bound methods such as [].append are callable. Strings, numbers, None, and lists are not.

A list is not callable even though it contains callables; the test applies to the object itself. To test the elements, pass each element to callable in a loop or with all.

$ python kinds.py
function                   True
builtin_function_or_method True
type                       True
method_descriptor          True
builtin_function_or_method True
str                        False
int                        False
NoneType                   False
list                       False

Bound methods and method objects

Accessing a method through an instance binds it to that instance, and the bound method is callable. A static method and a class method behave differently, and the raw objects stored in the class dictionary are a separate case.

methods.py
class Falcon:
    def method(self):
        return 'instance method'

    @staticmethod
    def stat():
        return 'static method'

    @classmethod
    def kind(cls):
        return cls.__name__


bird = Falcon()

print(callable(Falcon.method))
print(callable(bird.method))
print(callable(Falcon.stat))
print(callable(Falcon.kind))

raw = vars(Falcon)
print(callable(raw['stat']))
print(callable(raw['kind']))

The static method object is callable on its own since Python 3.10, so vars(Falcon)['stat'] passes the test. A classmethod object is still not callable: it is a descriptor that has to be bound to a class first, and Falcon.kind is the bound method that results.

This distinction matters when a decorator stores the raw descriptor somewhere. Reading it through the class gives a callable, while reading it from vars may not.

$ python methods.py
True
True
True
True
True
False

Partial objects and other wrappers

The functools module builds callable objects that wrap a function together with some arguments.

partials.py
import functools


def report(name, count, unit='items'):
    return f'{name}: {count} {unit}'


half = functools.partial(report, count=3)
square = functools.partial(pow, 2)

print(callable(half), half('falcon'))
print(callable(square), square(10))
print(callable(functools.partial))

for value in [half, square, report, functools]:
    print(f'{type(value).__name__:18} {callable(value)}')

A partial object is callable because its type defines __call__; the wrapped function is called with the stored arguments in front of the new ones. Keyword arguments can be pre-filled too.

The module functools is not callable, even though it contains callables. The last loop shows that the test is about the object, not about what the object holds.

$ python partials.py
True falcon: 3 items
True 1024
True
partial            True
partial            True
function           True
module             False

Objects with __call__

A class that defines __call__ produces instances that pass the test and can be used wherever a function is expected.

callable_instance.py
class Tally:
    def __init__(self):
        self.seen = []

    def __call__(self, item):
        self.seen.append(item)
        return len(self.seen)


tally = Tally()
print(callable(tally))
print(tally('falcon'))
print(tally('heron'))
print(tally.seen)

print(callable(Tally()))
print(callable(Tally))

The instance keeps state between calls, which a plain function cannot do without a global or a closure. This is the usual reason to write a callable class.

Both the instance and the class are callable, but for different reasons: the instance uses its own __call__, while the class uses the metaclass. The protocol itself is covered in Python __call__ method.

$ python callable_instance.py
True
1
2
['falcon', 'heron']
True
True

A true result does not promise a successful call

The test only checks that the call machinery exists. Argument counts, argument types, and the body of the callable are not inspected.

not_a_guarantee.py
print(callable(len))
print(callable(int))

try:
    len()
except TypeError as e:
    print('TypeError:', e)

try:
    int('falcon')
except ValueError as e:
    print('ValueError:', e)

try:
    int('falcon', 8, 2)
except TypeError as e:
    print('TypeError:', e)

Both builtins are callable, yet the first call omits a required argument and the second passes a string that is not a number. The exceptions come from the call, not from the test.

Code that uses callable as a guard still needs try around the actual call, or a signature check such as inspect.signature when the argument count is unknown.

$ python not_a_guarantee.py
True
True
TypeError: len() takes exactly one argument (0 given)
ValueError: invalid literal for int() with base 10: 'falcon'
TypeError: int expected at most 2 arguments, got 3

Validation and dispatch

The usual use of the function is to reject a table entry before it is called. The check moves the failure to the moment the table is built, where the error message can name the bad key.

dispatch.py
def falcon_speed():
    return 390


def heron_speed():
    return 80


handlers = {
    'falcon': falcon_speed,
    'heron': heron_speed,
    'eagle': 'fast',
}


def validate(table):
    bad = [name for name, handler in table.items() if not callable(handler)]
    if bad:
        raise ValueError(f'not callable: {", ".join(bad)}')


try:
    validate(handlers)
except ValueError as e:
    print('ValueError:', e)

del handlers['eagle']
validate(handlers)

for name in ['heron', 'falcon']:
    print(name, handlers[name]())

The list comprehension collects every bad entry instead of stopping at the first one, so a single run reports the whole table. This is the same filtering idea as Python predicate, with callable as the predicate.

The second call succeeds and the loop dispatches by name. A dictionary of callables with a validated key set is the smallest form of a command table, and it keeps string keys out of long if chains.

$ python dispatch.py
ValueError: not callable: eagle
heron 80
falcon 390

Source

Python callable() documentation

Python __call__ method

Python functools.partial

In this article we have tested functions, classes, bound methods, static and class method objects, partial objects, and callable instances, and we have seen that a true result says nothing about the arguments. For the attribute lookup that the test performs, see Python __call__ method; for the wider set of runtime checks, see Python introspection.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.