Why inspect.isclass says iter() a class?
tjreedy at udel.edu
Thu Apr 11 14:04:56 EDT 2019
On 4/10/2019 3:17 PM, Arup Rakshit wrote:
> From docs https://docs.python.org/3/library/itertools.html#itertools.chain I see that itertools.chain is defined as a function.
Because that is what the itertools functions are. (The chain entry does
not use 'function', but the beginning of the doc does.) In mathematics,
a 'function' is defined either as a set of input-output pairs with
unique first members or as something that returns a value (output) when
called with or applied to arguments (inputs). Programmers usually use
'function' in the latter sense when not using the word narrowly to refer
to a specific concrete implementation of 'function'.
Calling a class returns an instance. When a class is called, it is
being used as a function. CPython's exposed-by-default builtin classes
are included in the 'Built-in Functions' chapter of the Library
Reference. At one time, things like these were not implemented as 'classes
The Python manuals generally define the Python language, not the CPython
implementation. The itertools iterator-producing functions do not have
to be implemented as classes, so it would be wrong to define then as
such and impose that as a requirement on all Python implementation.
> But then why inspect.isclass(chain) is saying it as class.
Because, for speed, the CPython itertools module implements the
itertools functions as classes written in C. In other words, this is a
CPython implementation detail, not a language requirement, and one that
users can and should usually ignore. One should not normally write code
that depends on inspect.isclass(chain) returning True.
Another implementation could implement the itertools functions as the
'roughly equivalent' generator functions given in the manual.
inspect.isclass(chain) would then be False. But if one did so, that
fact that the returned iterators were specifically generators with send
and throw methods would a different implementation detail that users
would be expected to ignore.
I presume that Raymond originally wrote each itertool function as a
generator function, to get the behavior right and write tests, and than
rewrote them as C classes. One cannot write a generator function in C.
I don't know if any of the functions were ever exposed publicly as
generator functions, but they could have been.
Terry Jan Reedy
More information about the Python-list