- LPU MCA Semester 1
- CAB106
- Unit 4
CAB106 · Unit 4: Abstraction, modules and packages
Namespaces and scope of variables
11 practice questions
Key points
- LEGB: Local, Enclosing, Global, Built-in
- Assignment inside a function makes a local name
- global and nonlocal rebind outer variables
- Defaults are evaluated once at definition time
A namespace maps names to objects, and the scope is the region of code where a name is visible. Python searches in the LEGB order: Local (inside the current function), Enclosing (outer functions), Global (module level) and Built-in (names such as len and list).
An assignment inside a function creates a local name, so x = "l" does not change a global x. To rebind a module-level variable use global x; to rebind a variable of an enclosing function use nonlocal x. Using n += 1 on a global without declaring it fails with UnboundLocalError, because the assignment makes n local before it has a value. Closures keep their own enclosing variables, so each call of the factory gets a fresh counter.
Other points: a comprehension has its own scope, so its loop variable is not visible afterwards; assigning to a built-in name such as list shadows the built-in; locals() and globals() return the current namespaces; and a default argument is evaluated once, when the function is defined.
Exam trap: reading a global inside a function is fine, but assigning to it creates a local variable unless global is declared.
Try two questions
In which order does Python search for a name?
- Local, Global, Enclosing, Built-in
- Global, Local, Enclosing, Built-in
- Built-in, Global, Enclosing, Local
- Local, Enclosing, Global, Built-in
Show the answer
D. The LEGB rule: Local, Enclosing, Global, Built-in.
Why not A: Enclosing function scopes are searched before the module's global scope.
Why not B: The search starts with the local scope, not the global one.
Why not C: The search ends at the built-in scope, not at the start.