Scopes
1. Variable Scopes (Local vs. Global)
Section titled “1. Variable Scopes (Local vs. Global)”- 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 02. The global Keyword
Section titled “2. The global Keyword”- 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
globalkeyword.
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 20013. Name Resolution: The LEGB Rule
Section titled “3. Name Resolution: The LEGB Rule”- 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):
- Local: Inside the current function.
- Enclosing: Inside any enclosing (nested) parent functions.
- Global: At the top level of the module/script.
- Built-in: Pre-defined Python names (like
print,len,int).
4. Anonymous Functions (Lambda)
Section titled “4. Anonymous Functions (Lambda)”- 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 definitiondef standard_sum(a, b): return a + b
# Lambda equivalentlambda_sum = lambda a, b: a + bprint(lambda_sum(10, 20)) # Outputs 305. 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 calledlocals()inside yourif True:block, it simply returned the global dictionary, showing your'a': 20and'b': 20variables 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.