What is a Variable in Python?
A variable is a name that refers to an object in computer memory. In Python, variables do not have fixed types. The type belongs to the object that the variable refers to.
x = 42
x = "now a string"
Local Variables in Python
Defining Local Variables
A local variable is defined inside a function and is accessible only within that function. After the function completes its execution, the local variable is removed from memory.
def say_hello():
name = "Python" # local variable
print("Hello,", name)
say_hello()
# print(name) # Error: name is not defined
The variable name exists only within the say_hello function and is not accessible outside of it.
Advantages of Local Variables
Local variables provide data isolation and prevent unwanted changes to values from other parts of the program. They automatically free up memory after the function completes.
Global Variables in Python
What are Global Variables?
A global variable is declared outside of all functions and is accessible anywhere in the program file. These variables retain their values throughout the entire execution of the program.
language = "Python" # global variable
def show():
print("Language:", language)
show() # Language: Python
Problems with Modifying Global Variables
Attempting to modify a global variable inside a function can lead to an error:
counter = 0
def increment():
counter += 1 # UnboundLocalError!
Python interprets counter as a local variable due to the assignment operation, but it has not been defined locally.
The global Keyword
Using global to Modify Global Variables
The global keyword allows you to modify global variables inside functions:
count = 0
def increment():
global count
count += 1
increment()
print(count) # 1
Applying global in Mathematical Operations
total = 0
def add(x):
global total
total += x
add(10)
add(20)
print(total) # 30
When to Use global
The global keyword should be used sparingly, as it can complicate program debugging and make code less readable.
Scope: The LEGB Rule
Variable Lookup Principle
Python searches for variables according to the LEGB rule in the following order:
- L (Local) — inside the current function
- E (Enclosing) — in nested functions
- G (Global) — at the module level
- B (Built-in) — built-in Python names
Example of the LEGB Rule in Action
x = "global"
def outer():
x = "enclosing"
def inner():
x = "local"
print(x)
inner()
outer() # local
Python finds the variable x in the local scope and uses its value.
The nonlocal Keyword
Accessing Variables in Nested Functions
The nonlocal keyword is used to work with variables from an outer, but not global, scope:
def outer():
count = 0
def inner():
nonlocal count
count += 1
return count
return inner
f = outer()
print(f()) # 1
print(f()) # 2
Differences Between global and nonlocal
The global keyword works with module-level variables, while nonlocal works with variables from outer functions within the same scope.
Private Variables in Python
Naming Conventions
Python does not support true variable privacy but uses conventions:
_var— a private variable for internal use__var— a protected variable with name mangling__var__— a magic system variable
Example of Private Variables in Classes
class MyClass:
def __init__(self):
self.public = "accessible to all"
self._private = "for internal use"
self.__very_private = "with name mangling"
obj = MyClass()
print(obj.public) # accessible to all
print(obj._private) # 123 (accessible, but not recommended)
# print(obj.__very_private) # AttributeError
print(obj._MyClass__very_private) # works via mangled name
Name Mangling Mechanism
Python automatically changes the names of variables starting with two underscores by adding the class name to them. This makes accidental access to such variables more difficult.
Comparing Local and Global Variables
Main Differences
Local variables exist only within a function and are automatically deleted after it completes. Global variables are accessible throughout the entire module and are retained until the program terminates.
Performance and Security
Local variables offer better performance due to faster memory access. They also reduce the risk of side effects and naming conflicts.
Usage Recommendations
Prefer local variables for temporary calculations and intermediate results. Use global variables only for constants and configuration settings.
Proper Use of Global Variables
Suitable Use Cases
Global variables are appropriate in the following situations:
- Mathematical constants (
PI = 3.14159) - Application configuration settings
- Debugging flags (
DEBUG = True) - Data caching when no alternatives exist
Cases to Avoid
Do not use global variables for:
- Passing data between functions
- Storing mutable state
- Temporary calculations
- Counters and accumulators
Practical Examples and Solutions
Function Call Counter
Incorrect Approach with a Global Variable:
count = 0
def handler():
global count
count += 1
Correct Solution with a Closure:
def create_counter():
count = 0
def counter():
nonlocal count
count += 1
return count
return counter
my_counter = create_counter()
print(my_counter()) # 1
print(my_counter()) # 2
Application Configuration
Proper Use of Global Constants:
DATABASE_URL = "postgresql://localhost:5432/mydb"
MAX_CONNECTIONS = 100
TIMEOUT_SECONDS = 30
def connect_to_database():
# using global constants
connection = create_connection(DATABASE_URL, TIMEOUT_SECONDS)
return connection
Debugging Scope Issues
Common Errors
UnboundLocalError occurs when attempting to modify a variable that Python considers local but has not been defined within the function.
Diagnostic Methods
Use the built-in functions locals() and globals() to view available variables:
x = "global"
def test():
y = "local"
print("Local:", locals())
print("Global:", list(globals().keys()))
test()
Best Practices for Working with Variables
Main Recommendations
- Use local variables by default
- Declare global constants in uppercase
- Apply naming conventions for privacy
- Avoid modifying global state from functions
- Prefer passing parameters over global variables
Principles of Clean Code
Functions should receive data through parameters and return results, rather than relying on global state. This makes the code more predictable and testable.
Frequently Asked Questions
How to Properly Declare a Global Variable?
Declare the variable outside all functions at the module level. To modify it inside a function, use the global keyword.
What is the Difference Between global and nonlocal?
The global keyword works with module-level variables, while nonlocal works with variables from outer functions in nested constructs.
Are There Truly Private Variables?
Python does not have a true privacy mechanism. Privacy is implemented through naming conventions and a social contract between developers.
When is the Use of Global Variables Justified?
Global variables are appropriate for constants, configuration settings, and in cases where passing parameters significantly complicates the application architecture.
Conclusion
Understanding variable scope is critical for writing high-quality Python code. Local variables provide security and data isolation, while global variables require careful use.
Key principles for working with variables include preferring local variables, consciously using global constants, and adhering to privacy conventions. A correct understanding of the LEGB rule and the global and nonlocal keywords will help avoid common errors and create more reliable programs.
The Future of AI in Mathematics and Everyday Life: How Intelligent Agents Are Already Changing the Game
Experts warned about the risks of fake charity with AI
In Russia, universal AI-agent for robots and industrial processes was developed