Handle null and undefined values safely by using appropriate fallback patterns, validating critical parameters early, and avoiding mutable default arguments.
Handle null and undefined values safely by using appropriate fallback patterns, validating critical parameters early, and avoiding mutable default arguments.
Key Practices:
cpu_count = os.cpu_count() or 4 meta = meta or {}
func_name = getattr(func, “name”, “Unknown”)
func_name = func.name # May raise AttributeError
2. **Validate critical parameters early** and fail fast:
```python
# Good: Early validation with clear error
def get_features(tenant_id: str):
if not tenant_id:
raise ValueError("tenant_id is required")
# ... rest of function
# Avoid: Allowing empty/None values to propagate
def get_features(tenant_id: str):
# ... function continues without validation
def create_blob_message(blob: bytes, meta: dict = None, save_as: str = “”): meta = meta or {}
conditions: list[SubCondition] = Field(default_factory=list)
def create_blob_message(blob: bytes, meta: dict = {}, save_as: str = “”):
4. **Use dict.get() with explicit defaults** for safe dictionary access:
```python
# Good: Explicit default value
for tool in agent_mode.get("tools", []):
# Less clear: Relying on or operator
for tool in agent_mode.get("tools") or []:
if keyword and isinstance(keyword, str): keyword_like_val = f”%{keyword[:30]}%”
keyword_like_val = f”%{keyword[:30]}%” # May fail if keyword is None ```
This approach prevents runtime errors, makes code more predictable, and clearly communicates intent about required vs optional values.
Enter the URL of a public GitHub repository