Python - Name Scope

Card Puncher Data Processing


Language - Scope of an identifier (Variable, Package, Lexical) in Python

A scope defines the visibility of a name within a block.

  • If a local variable is defined in a block, its scope includes that block.
  • If the definition occurs in a function block, the scope extends to any blocks contained within the defining one, unless a contained block introduces a different binding for the name.



If the global statement occurs within a block, all uses of the name specified in the statement refer to the binding of that name in the top-level namespace. Names are resolved in the top-level namespace by searching the global namespace, i.e. the namespace of the module containing the code block, and the builtins namespace, the namespace of the module builtins. The global namespace is searched first. If the name is not found there, the builtins namespace is searched. The global statement must precede all uses of the name.

The global statement has the same scope as a name binding operation in the same block. If the nearest enclosing scope for a free variable contains a global statement, the free variable is treated as a global.

Global statement

Non local

The nonlocal statement causes corresponding names to refer to previously bound variables in the nearest enclosing function scope. SyntaxError is raised at compile time if the given name does not exist in any enclosing function scope.

Non local statement

Documentation / Reference

Discover More
Card Puncher Data Processing
Python - Comprehension (Iteration)

Comprehension are a way to loop over elements of: a , , , tuple, , or . Comprehensions permit to build collections out of other collections. Comprehensions allow one to express computations...
Card Puncher Data Processing
Python - Generator

Generator expressions are implemented using a function scope. Generators are a special class of functions that simplify the task of writing iterators. ...
Card Puncher Data Processing
Python - Name

in Python Names (refer to|are pointer for) objects. Names are introduced by name binding operations such as during the def process. targets that are identifiers if occurring in an assignment,...

Share this page:
Follow us:
Task Runner