liveBook · Manning

Built-in namespace

As explained in Python Workout, Second Edition

builtins is Python's namespace and module containing names automatically available to Python code.

The built-in namespace supplies common names such as int and sum when Python resolves an identifier. Lookup follows LEGB: local, enclosing, global, then built-ins; Python stops at the first match. section 7.5

Avoid common lookup failures:

  • Do not redefine built-in names such as sum; a global variable shadows the built-in and can make sum(...) fail with TypeError. section 7.5
  • Remember that indentation alone does not create a new scope; function definitions create local scope. section 7.5
  • Use pylint or ruff to detect accidental collisions with built-in names. section 7.5
sum = 0
for i in range(5):
    sum += i
print(sum)

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

TypeError: 'int' object is not callable

Compare a shadowing assignment with a call to the original built-in sum. section 7.5

How Python Workout, Second Edition covers it

How deep it goes
Explains lookup order and shadowing consequences, including the resulting TypeError from calling a shadowed name.
Examples
Uses int('s'), a shadowed sum variable, sum([...]), and pylint or ruff diagnostics.
What it assumes
Assumes familiarity with variables and functions while teaching the LEGB lookup order explicitly.
What you can do after
Diagnose name-resolution errors by checking globals before built-ins and identifying collisions such as sum.
How it connects
Connects local, enclosing, and global scopes with name shadowing and static-analysis tools.

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, Second Edition. The section links point to the parts of the book it draws on.