liveBook · Manning

Built-in namespace

As explained in Python Workout: 50 ten-minute exercises

The built-ins namespace is Python's namespace containing names available as a final fallback during ordinary name resolution, including built-in functions and types.

When Python evaluates a name such as int, range, or sum, it searches available namespaces. The built-in namespace is the final fallback: inside a function, Python searches local, enclosing, global, then built-in names; outside a function, it searches globals before built-ins. Once Python finds the name, it stops. section 6.5

Shadowing a built-in

sum = 0 for i in range(5): sum += i print(sum) print(sum([10, 20, 30])) The final call fails because the global integer named sum is found before the built-in sum function. Avoid redefining built-in names; tools such as pylint can flag these collisions. section 6.5

Keep these distinctions in mind:

  • Built-ins are not ordinary global variables, but Python makes their names available through the final lookup level. section 6.5
  • Common types and functions such as lists, dicts, and int are built into the language and require no import. section 8.0
  • The standard library is broader than the built-ins: modules such as os must be loaded with import before use. section 8.0
sum = 0
for i in range(5):
   sum += i
print(sum)

print(sum([10, 20, 30]))

TypeError: 'int' object is not callable

Trace a built-in name collision from assignment through failed function invocation. section 6.5

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains lookup order and shadowing with a failure example, but stops short of namespace implementation internals.
Examples
Uses int, range, sum, a shadowing error, pylint, lists, dicts, and os imports.
What it assumes
Assumes familiarity with variables and functions while teaching namespace lookup and built-in availability through examples.
What you can do after
Diagnose/debug with it by recognizing built-in shadowing and distinguishing built-ins from modules requiring import.
How it connects
Connects built-in lookup with LEGB, global scope, local scope, namespaces, and the standard library.

Also explained in

Compare how 3 books explain built-in namespace →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.