liveBook · Manning

Scope

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

Scope is the region of a program in which a name or variable is accessible and has a particular binding.

Scope determines where a name can be accessed and how long its binding exists. In Python, functions and modules create namespaces that organize variable names and prevent unrelated code from sharing every value. section 2.3.4

A module-level variable is available throughout its module and generally lasts as long as the imported module. A function-level variable is available only while that function runs. Code inside a function can access suitable names from its containing module scope. section 2.3.4

The same name can resolve differently depending on where it is created:

  • Module scope: define prefix outside functions, making it accessible across the module and to code that imports the module. section 2.3.4
  • Function scope: define prefix inside add(), so that local value takes precedence when the function runs. section 2.3.3
  • Nested access: let my_message() use the module-level prefix while keeping new_message local to the function. section 2.3.4

The same name at two levels

With prefix = "added" at module level, add(12, 12) returns "added: 12 12". If add() assigns prefix = "inside add function", its local value is used instead. The inner binding changes the function’s result without changing the module-level binding. section 2.3.3

Figure 2.4 How the scopes nest inside one another and where in a scope a variable is visible

Use the scope diagram to see how module and function scopes nest and where a variable is visible. section 2.3.4

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

How deep it goes
Explains module and function scope through progressive examples, stopping short of broader name-resolution internals.
Examples
Uses prefix, add(), print_prefix(), my_message(), imported modules, and a nested-scope diagram.
What it assumes
Assumes basic Python variables, functions, modules, and assignment while defining scope through concrete examples.
What you can do after
Diagnose variable behavior by inspecting names within the current scope at debugger breakpoints.
How it connects
Connects variables with namespaces, modules, functions, name resolution, lifetime, and debugging.

Also explained in

Compare how 21 books explain scope →

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.