Sometimes we call classes functions in Python. Why? And what's a "callable"?
Table of contents
Class or function?
There's a group activity I often do when training new Python developers: the class or function game.
In the class or function game, we take something that we "call" (using parentheses: ()
) and we guess whether it's a class or a function.
For example:
- We can call
zip
with a couple iterables and we get another iterable back, so iszip
a class or a function? - When we call
len
, are we calling a class or a function? - What about
int
: when we writeint('4')
are we calling a class or a function?
Python's zip
, len
, and int
are all often guessed to be functions, but only one of these is really a function:
>>> zip<class 'zip'>>>> len<built-in function len>>>> int<class 'int'>
>>> zip<class 'zip'>>>> len<built-in function len>>>> int<class 'int'>
While len
is a function, zip
and int
are classes.
The reversed
, enumerate
, range
, and filter
"functions" also aren't really functions:
>>> reversed<class 'reversed'>>>> enumerate<class 'enumerate'>>>> range<class 'range'>>>> filter<class 'filter'>
>>> reversed<class 'reversed'>>>> enumerate<class 'enumerate'>>>> range<class 'range'>>>> filter<class 'filter'>
After the class or function game, we often talk discuss:
- The term "callable" (and how classes are callables)
- The fact that in Python we often don't care whether something is a class or a function
What's a callable?
A callable is anything you …