liveBook · Manning

Callable

As explained in Python Workout, Second Edition

A callable is a Python object that can be invoked using call syntax with parentheses.

A callable is a Python object that can be invoked with parentheses. Functions and classes are callables, so a menu can map user-entered keywords to actions and invoke the selected value. section 9.6 section 10.8

Use callables to separate input selection from the operation that follows:

  • Accept any number of keyword arguments whose values are callables. section 9.6
  • Invoke the callable associated with matching user input and return its result. section 9.6
  • Reject unknown input with an error message, then ask again. section 9.6
from menu import menu

def func_a():
    return "A"

def func_b():
    return "B"

return_value = menu(a=func_a, b=func_b)
print(f'Result is {return_value}')

This executable example maps a and b to separate functions, then prints the selected callable's returned value. section 9.6

How Python Workout, Second Edition covers it

How deep it goes
Defines callability, applies it to menu dispatch, and traces class invocation through __new__ and __init__.
Examples
Uses menu callbacks named func_a and func_b, plus Foo(10) as a class invocation.
What you can do after
Apply it by building a menu that invokes keyword-selected callables and returns their results.
How it connects
Connects callable to functions, classes, modules, __new__, __init__, and object creation.

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 Workout, Second Edition. The section links point to the parts of the book it draws on.