Skip to content

Scopes

  • Global Variables: Initialized outside of any function. They reside in the global memory space and are accessible from anywhere in the file.
  • Local Variables: Initialized strictly inside a function. They exist only temporarily while the function executes and are destroyed when it returns.
  • The Logic: You cannot access a local variable from the outside, but a function can read a global variable from the inside.

Example:

total = 0 # Global scope
def calculate_sum(arg1, arg2):
total = arg1 + arg2 # Local scope (shadows the global)
print("Inside function:", total) # Outputs 30
return total
calculate_sum(10, 20)
print("Outside function:", total) # Outputs 0
  • The Problem: By default, Python assumes that if you assign a value to a variable inside a function, you want to create a new local variable.
  • The Solution: If you need to physically modify an existing global variable from inside a function, you must explicitly declare it using the global keyword.

Example:

money = 2000
def add_money():
global money # Overrides local assignment creation
money = money + 1 # Modifies the global variable directly
print(money)
add_money() # Outputs 2001
  • The Concept: When you call a variable, Python must figure out which value you mean. It searches through scopes in a strict, unchangeable hierarchy.
  • The Hierarchy (LEGB):
    1. Local: Inside the current function.
    2. Enclosing: Inside any enclosing (nested) parent functions.
    3. Global: At the top level of the module/script.
    4. Built-in: Pre-defined Python names (like print, len, int).
  • The Concept: A shorthand way to write small, unnamed functions.
  • Constraints: Can take unlimited arguments, but is strictly limited to one single expression. It implicitly returns the result of that expression.
  • Syntax: lambda [arguments]: expression

Example:

# Standard function definition
def standard_sum(a, b):
return a + b
# Lambda equivalent
lambda_sum = lambda a, b: a + b
print(lambda_sum(10, 20)) # Outputs 30

5. Namespace Introspection (globals() and locals())

Section titled “5. Namespace Introspection (globals() and locals())”
  • Methods:
    • globals(): Returns a dictionary of all variables currently existing in the global namespace.
    • locals(): Returns a dictionary of all variables currently existing in the exact local scope where the function is called.
  • Logical Insight (Based on your terminal output): In Python, loops (for, while) and condition blocks (if) do not create a new local scope. Only functions and classes create scopes. Therefore, when you called locals() inside your if True: block, it simply returned the global dictionary, showing your 'a': 20 and 'b': 20 variables alongside system modules.

Example:

a = 10 # Global variable
def test_scope():
qwert = 1 # Local variable
print(locals())
test_scope()
# Output: {'qwert': 1}
print(globals().keys())
# Output includes 'a', 'test_scope', and built-in module names.