Practical Use Cases
Logging and Configuration Functions
def configure_logger(**kwargs):
config = {
'level': 'INFO',
'format': '%(asctime)s - %(message)s',
'filename': None
}
config.update(kwargs)
print(f"Logger Configuration: {config}")
## Flexible logger configuration
configure_logger(level='DEBUG')
configure_logger(filename='app.log', format='%(levelname)s: %(message)s')
API Wrapper Design
def make_api_request(endpoint, *args, **kwargs):
headers = kwargs.get('headers', {})
method = kwargs.get('method', 'GET')
params = kwargs.get('params', {})
print(f"Endpoint: {endpoint}")
print(f"Method: {method}")
print(f"Headers: {headers}")
print(f"Params: {params}")
## Flexible API request handling
make_api_request('/users',
method='POST',
headers={'Auth': 'token123'},
params={'active': True})
Decorator Implementation
def flexible_decorator(*decorator_args, **decorator_kwargs):
def decorator(func):
def wrapper(*args, **kwargs):
print("Decorator arguments:", decorator_args, decorator_kwargs)
return func(*args, **kwargs)
return wrapper
return decorator
@flexible_decorator(log=True, level='debug')
def example_function(x, y):
return x + y
example_function(3, 4)
Workflow Processing
graph TD
A[Input Data] --> B{Process with Flexible Arguments}
B --> C[Transform Data]
B --> D[Validate Data]
B --> E[Log Information]
Comparison of Argument Techniques
Technique |
Flexibility |
Use Case |
Complexity |
*args |
High |
Multiple inputs |
Low |
**kwargs |
Very High |
Configuration |
Medium |
Mixed |
Highest |
Complex workflows |
High |
Database Query Builder
def create_query(table, **conditions):
base_query = f"SELECT * FROM {table}"
where_clauses = [f"{k} = '{v}'" for k, v in conditions.items()]
if where_clauses:
query = f"{base_query} WHERE {' AND '.join(where_clauses)}"
else:
query = base_query
return query
## Dynamic query generation
print(create_query('users', active=True, role='admin'))
print(create_query('products', category='electronics', price_above=100))
Event Handling System
class EventManager:
def __init__(self):
self.listeners = {}
def register_listener(self, event_type, *callbacks):
if event_type not in self.listeners:
self.listeners[event_type] = []
self.listeners[event_type].extend(callbacks)
def trigger_event(self, event_type, **event_data):
if event_type in self.listeners:
for callback in self.listeners[event_type]:
callback(**event_data)
## Flexible event handling
manager = EventManager()
manager.register_listener('user_login',
lambda **data: print(f"Login: {data}"),
lambda **data: print(f"Logging: {data}"))
Best Practices
- Use variable arguments for maximum flexibility
- Document function signatures clearly
- Validate and sanitize inputs
- Consider performance implications
LabEx recommends practicing these techniques to build more adaptable Python applications.