22
votes

The following code returns false

import inspect
print(inspect.isbuiltin(map))

But the map function is listed under "built-in" functions.

Why is it so?

1
I does seem odd that inspect.isbuiltin(__builtins__.map) would be False. - jonrsharpe

1 Answers

33
votes

The inspect.isbuiltin will only

Return true if the object is a built-in function or method.

The map builtin is a class, not a function or method:

>>> map
<class 'map'>

In fact, most "built-in functions" that return iterators are implemented as classes; calling them returns optimised instances instead of re-using some generic iterator class.

>>> zip  # zip iterator "function" is also a class
<class 'zip'>
>>> map(str, (1, 2, 34))  # map builds instances of map
<map object at 0x103fa34f0>

In addition, keep in mind that the term "built-in" has two meanings in Python:

  • A compiled object, i.e. built into the interpreter.
  • A member of the builtins module, available in every module.

While most builtins are compiled for speed, this is no necessity.

If you want to check whether a name is part of builtins, do so via the module:

>>> import builtins
>>> hasattr(builtins, "map")
True
>>> hasattr(builtins, "sum")
True
>>> hasattr(builtins, "reduce")
False