Python Global Keyword

1. Basic Use of Global Variable

count = 10

def display():
    print(count)

display()  # Output: 10

Global variables are declared outside functions and are readable within functions by default.


2. Modifying Global Variable Without global (Error Case)

value = 5

def update():
    value = value + 1  # UnboundLocalError

Assigning to a variable inside a function makes it local unless explicitly declared global.


3. Using global to Modify Global Variable

counter = 0

def increment():
    global counter
    counter += 1

increment()
print(counter)  # Output: 1

The global keyword allows direct modification of a global variable.


4. Global Variable Across Multiple Functions

A global variable can be shared and updated across multiple functions.


5. Global Keyword Inside Nested Functions

global always refers to the module-level scope, even when used inside nested functions.


6. Difference Between global and nonlocal

  • global → Refers to module-level variable

  • nonlocal → Refers to nearest enclosing function scope


7. Tracking State Using Global Variable

Used for maintaining application-wide counters or shared state.


8. Global Variable with Conditional Logic

Global variables often manage configuration state.


9. Avoiding Global Abuse (Best Practice Warning)

Mutable objects can be modified without global, reducing global keyword dependency.


10. Best Practice: Encapsulation Instead of Global

Encapsulation is preferred over global variables in production systems for maintainability and testability.


Last updated