Skip to content

Commit

Permalink
fix(client): don't cause crashes when inspecting the module (#897)
Browse files Browse the repository at this point in the history
  • Loading branch information
stainless-bot committed Dec 1, 2023
1 parent 17ac677 commit 84c85bd
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 7 deletions.
26 changes: 22 additions & 4 deletions src/openai/_utils/_proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,25 +18,43 @@ class LazyProxy(Generic[T], ABC):
def __init__(self) -> None:
self.__proxied: T | None = None

# Note: we have to special case proxies that themselves return proxies
# to support using a proxy as a catch-all for any random access, e.g. `proxy.foo.bar.baz`

def __getattr__(self, attr: str) -> object:
return getattr(self.__get_proxied__(), attr)
proxied = self.__get_proxied__()
if isinstance(proxied, LazyProxy):
return proxied # pyright: ignore
return getattr(proxied, attr)

@override
def __repr__(self) -> str:
proxied = self.__get_proxied__()
if isinstance(proxied, LazyProxy):
return proxied.__class__.__name__
return repr(self.__get_proxied__())

@override
def __str__(self) -> str:
return str(self.__get_proxied__())
proxied = self.__get_proxied__()
if isinstance(proxied, LazyProxy):
return proxied.__class__.__name__
return str(proxied)

@override
def __dir__(self) -> Iterable[str]:
return self.__get_proxied__().__dir__()
proxied = self.__get_proxied__()
if isinstance(proxied, LazyProxy):
return []
return proxied.__dir__()

@property # type: ignore
@override
def __class__(self) -> type:
return self.__get_proxied__().__class__
proxied = self.__get_proxied__()
if issubclass(type(proxied), LazyProxy):
return type(proxied)
return proxied.__class__

def __get_proxied__(self) -> T:
if not self.should_cache:
Expand Down
12 changes: 9 additions & 3 deletions src/openai/lib/_old_api.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from __future__ import annotations

from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Any
from typing_extensions import override

from .._utils import LazyProxy
Expand All @@ -23,13 +23,19 @@ def __init__(self, *, symbol: str) -> None:
super().__init__(INSTRUCTIONS.format(symbol=symbol))


class APIRemovedInV1Proxy(LazyProxy[None]):
class APIRemovedInV1Proxy(LazyProxy[Any]):
def __init__(self, *, symbol: str) -> None:
super().__init__()
self._symbol = symbol

@override
def __load__(self) -> None:
def __load__(self) -> Any:
# return the proxy until it is eventually called so that
# we don't break people that are just checking the attributes
# of a module
return self

def __call__(self, *_args: Any, **_kwargs: Any) -> Any:
raise APIRemovedInV1(symbol=self._symbol)


Expand Down

0 comments on commit 84c85bd

Please sign in to comment.