Skip to content

[Py SDK] Add a safe access helper for nested optional fields #1126

Open

Description

@laurabelinfante

Summary

Python has no equivalent of TypeScript's foo?.bar?.baz, so traversing nested optional models means either chained if checks or a crash. A roughly 30 line wrapper class covers it.

Considered and rejected: glom and Box, both dict-focused rather than model-focused. Given how little code this takes, the preference is a small wrapper in our own SDK over a new dependency we have to keep current.

Open caveat: consumers may still need to pass the type of the final attribute to get useful type hinting. Worth settling how much type safety the helper can realistically offer before building it.

Also noted in discussion: this would fit a future Maintenance deliverable, so it may want to move out of the catch-all if that gets created.

Example

Sketch from discussion:

from typing import Any, Optional
from pydantic import BaseModel


class SafeAccess:
    """The '?.' simulator for Python."""

    def __init__(self, value: Any):
        self._value = value

    def __getattr__(self, name: str) -> "SafeAccess":
        # If the current level is None, keep returning a wrapper of None
        if self._value is None:
            return SafeAccess(None)
        # Attempt to get attribute, return wrapped None if missing
        return SafeAccess(getattr(self._value, name, None))

    def __call__(self, default: Any = None) -> Any:
        """Unwrap the value with an optional default."""
        return self._value if self._value is not None else default


class Config(BaseModel):
    theme_name: str


class Profile(BaseModel):
    config: Optional[Config] = None


class User(BaseModel):
    profile: Optional[Profile] = None


# Data with missing pieces
user_data = {"profile": None}
user = User.model_validate(user_data)

# Wrap and traverse: user?.profile?.config?.theme_name
# This would normally crash at .config because .profile is None
theme = SafeAccess(user).profile.config.theme_name("default_dark")

print(f"Final Value: {theme}")  # Output: default_dark

Acceptance criteria

  • Helper supports chained access through None and returns a caller-supplied default
  • The type-hinting behavior is documented, including whether callers must supply the expected type
  • Tests cover a full chain, a broken chain, and a missing attribute
  • Usage documented in the Python SDK README

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureNew capability. Belongs on a hold branch.py-sdkRelated to Python SDKpythonIssue or PR related to Python toolingsdkIssue or PR related to our SDKs

    Type

    Projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions