Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

92
Views
Why does inspect() think map isn't built in?

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?

10 months ago · Santiago Trujillo
1 answers
Answer question

0

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
10 months ago · Santiago Trujillo Report
Answer question
Find remote jobs