Implementation:Openai Openai python Lazy Proxy
| Knowledge Sources | |
|---|---|
| Domains | SDK_Infrastructure |
| Last Updated | 2026-02-15 00:00 GMT |
Overview
Concrete tool for lazy object proxy pattern provided by the openai-python SDK.
Description
The _proxy module defines the LazyProxy[T] abstract base class, a generic proxy that pretends to be an instance of type T by forwarding attribute access, string representation, and other dunder methods to the lazily loaded underlying object. Subclasses must implement the abstract __load__() method, which is called on first access via __get_proxied__(). The proxy overrides __getattr__, __repr__, __str__, __dir__, and the __class__ property to transparently delegate to the proxied object. Special handling ensures that proxies which themselves return proxies (for chained attribute access like proxy.foo.bar) do not cause infinite recursion. The __as_proxied__() helper returns the proxy itself typed as T for static type checking convenience.
Usage
Use this base class when implementing deferred initialization patterns, such as the module-level client proxies in _module_client or the deprecation proxies in _old_api.
Code Reference
Source Location
- Repository: openai-python
- File: src/openai/_utils/_proxy.py
- Lines: 1-65
Signature
T = TypeVar("T")
class LazyProxy(Generic[T], ABC):
def __getattr__(self, attr: str) -> object: ...
def __repr__(self) -> str: ...
def __str__(self) -> str: ...
def __dir__(self) -> Iterable[str]: ...
@property
def __class__(self) -> type: ...
def __get_proxied__(self) -> T: ...
def __as_proxied__(self) -> T: ...
@abstractmethod
def __load__(self) -> T: ...
Import
from openai._utils._proxy import LazyProxy
# or via the convenience re-export:
from openai._utils import LazyProxy
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| (none for base class) | N/A | N/A | Subclasses define __load__() to return the target object |
| attr | str | Yes | Attribute name forwarded via __getattr__ |
Outputs
| Name | Type | Description |
|---|---|---|
| __load__() result | T | The lazily loaded target object |
| __as_proxied__() result | T | The proxy itself, cast to type T for type-checker convenience |
| __getattr__ result | object | Attribute value from the proxied object |
Usage Examples
Basic Usage
from openai._utils import LazyProxy
from typing_extensions import override
class ConfigProxy(LazyProxy[dict]):
@override
def __load__(self) -> dict:
# Expensive initialization deferred until first access
return {"model": "gpt-4o", "temperature": 0.7}
config = ConfigProxy().__as_proxied__()
# No loading happens yet
print(config["model"]) # Triggers __load__(), prints "gpt-4o"