liveBook · Manning

Shadowing

As explained in The Well-Grounded Python Developer: How the pros use Python and Flask

Shadowing is the concealment of an existing name binding by another binding with the same name in a nearer or overriding namespace.

Shadowing occurs when a nearer definition reuses a name and hides an existing binding. In Python, this can make familiar built-ins or earlier functions inaccessible. section 2.3.1 section 2.3.2

Common cases include:

  • Defining your own open() hides Python’s built-in open(), even though the replacement may be valid for the immediate program. section 2.3.1
  • Defining add() twice in one file causes the second definition to replace the first, regardless of their different behaviors. section 2.3.2
  • Placing one implementation in a module preserves both names: local add() and utility.add() refer to separate namespace entries. section 2.3.2

Keep implementations in separate namespaces

A local add() can perform mathematical addition while utility.add() performs string concatenation. Importing utility gives each implementation an explicit qualified name; importing it as utils creates the alias utils.add(). section 2.3.2

import utility 
 
def add(a, b):
    return a + b
 
print(add(12, 12))
print(utility.add(12, 12))

Compare an unqualified local function with utility.add() to see how a module namespace prevents the definitions from shadowing one another. section 2.3.2

How The Well-Grounded Python Developer: How the pros use Python and Flask covers it

How deep it goes
Explains replacement and namespace separation through built-in and module examples, but does not catalog broader name-resolution rules.
Examples
Uses open(), duplicate add() functions, utility.add(), aliased imports, and qualified module calls.
What it assumes
Assumes familiarity with Python functions and basic files while introducing namespaces through built-ins and imported modules.
What you can do after
Diagnose/debug with it by spotting hidden built-ins or overwritten functions and separating conflicting definitions into module namespaces.
How it connects
Connects shadowing with namespaces, scope, built-ins, modules, imports, and aliases.

Also explained in

Compare how 4 books explain shadowing →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Python Developer: How the pros use Python and Flask. The section links point to the parts of the book it draws on.