Common Pitfalls
1. Mutable Default Arguments Trap
def append_to_list(value, lst=[]):
lst.append(value)
return lst
## Unexpected behavior
print(append_to_list(1)) ## [1]
print(append_to_list(2)) ## [1, 2]
Correct Approach
def append_to_list(value, lst=None):
if lst is None:
lst = []
lst.append(value)
return lst
2. Default Argument Evaluation Time
graph TD
A[Default Argument] --> B[Evaluated Once]
B --> C[At Function Definition]
B --> D[Not at Function Call]
Potential Issues
import time
def log_timestamp(timestamp=time.time()):
print(f"Timestamp: {timestamp}")
## Multiple calls will show same timestamp
log_timestamp()
log_timestamp()
3. Overriding Complex Default Arguments
Problematic Pattern
def create_config(settings={"debug": False}):
settings['debug'] = True
return settings
## Unexpected mutation
config1 = create_config()
config2 = create_config()
print(config1, config2) ## Both will have debug=True
Safe Implementation
def create_config(settings=None):
if settings is None:
settings = {"debug": False}
settings = settings.copy()
settings['debug'] = True
return settings
4. Keyword Argument Ordering
Incorrect Usage
def register_user(username, email, active=True, role="user"):
return {
"username": username,
"email": email,
"active": active,
"role": role
}
## Potential confusion
user = register_user("john", "[email protected]", "admin") ## Incorrect
Correct Usage
user = register_user("john", "[email protected]", role="admin")
5. Type Hint Complications
Pitfall |
Example |
Solution |
Immutable Type Hints |
def func(x: list = []) |
Use `x: list |
Complex Default Types |
def func(config: dict = {}) |
Initialize inside function |
def memory_intensive_default(large_data=complex_computation()):
## Computation happens only once
pass
Best Practices with LabEx
- Always use
None
for mutable defaults
- Be explicit about argument types
- Use type hints carefully
- Avoid complex default argument computations
Advanced Warning Techniques
import warnings
def deprecated_function(param=None):
warnings.warn("This function is deprecated", DeprecationWarning)
## Function implementation
Error Handling Strategies
def robust_function(required_param, optional_param=None):
if required_param is None:
raise ValueError("Required parameter cannot be None")
optional_param = optional_param or []
return optional_param
Debugging and Introspection
def inspect_defaults(func):
import inspect
signature = inspect.signature(func)
for param_name, param in signature.parameters.items():
print(f"{param_name}: {param.default}")