Best Practices
Minimizing Global Variable Usage
Preferred Alternatives
graph TD
A[Avoiding Global Variables] --> B[Function Parameters]
A --> C[Class Attributes]
A --> D[Dependency Injection]
A --> E[Configuration Objects]
Encapsulation Techniques
1. Using Classes for State Management
class ConfigManager:
def __init__(self):
self._settings = {
'debug': False,
'max_connections': 100
}
def get_setting(self, key):
return self._settings.get(key)
def update_setting(self, key, value):
self._settings[key] = value
## Controlled state management
config = ConfigManager()
config.update_setting('debug', True)
Scope Management Strategies
Strategy |
Description |
Recommendation |
Local Variables |
Prefer local scope |
Highest Priority |
Function Parameters |
Pass data explicitly |
Recommended |
Class Attributes |
Manage object-specific state |
Preferred |
Global Variables |
Minimal usage |
Last Resort |
Immutable Configuration Approach
from typing import Final
## Using type hints and constants
class AppConfig:
DEBUG: Final[bool] = False
MAX_RETRIES: Final[int] = 3
API_ENDPOINT: Final[str] = 'https://api.example.com'
## Immutable, type-safe configuration
print(AppConfig.DEBUG) ## False
Dependency Injection Pattern
class DatabaseConnection:
def __init__(self, connection_string):
self._connection = self._establish_connection(connection_string)
def _establish_connection(self, connection_string):
## Connection logic
pass
class UserService:
def __init__(self, db_connection):
self._db = db_connection
def get_user(self, user_id):
## Use injected database connection
pass
LabEx Recommended Practices
- Minimize global state
- Use type hints
- Implement immutable configurations
- Leverage dependency injection
- Write testable code
Advanced Scoping Techniques
Context Managers
class TemporaryContext:
def __init__(self, initial_state):
self._original_state = initial_state
self._current_state = initial_state
def __enter__(self):
return self._current_state
def __exit__(self, exc_type, exc_value, traceback):
self._current_state = self._original_state
## Controlled state management
with TemporaryContext({'mode': 'test'}) as context:
context['mode'] = 'production'
graph TD
A[Code Quality] --> B[Readability]
A --> C[Performance]
A --> D[Maintainability]
Final Recommendations
- Avoid global variables when possible
- Use explicit parameter passing
- Implement clear, focused functions
- Leverage object-oriented design
- Write self-documenting code
By following these best practices, you'll create more robust, maintainable, and scalable Python applications.