Skip to content

Commit 244ed1f

Browse files
authored
use knowledge about generic types to improve their getters and checkers (#5245)
1 parent 765c8cb commit 244ed1f

File tree

1 file changed

+14
-5
lines changed

1 file changed

+14
-5
lines changed

reflex/utils/types.py

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,10 @@ def __bool__(self) -> bool:
120120

121121

122122
@lru_cache
123+
def _get_origin_cached(tp: Any):
124+
return get_origin_og(tp)
125+
126+
123127
def get_origin(tp: Any):
124128
"""Get the origin of a class.
125129
@@ -129,7 +133,11 @@ def get_origin(tp: Any):
129133
Returns:
130134
The origin of the class.
131135
"""
132-
return get_origin_og(tp)
136+
return (
137+
origin
138+
if (origin := getattr(tp, "__origin__", None)) is not None
139+
else _get_origin_cached(tp)
140+
)
133141

134142

135143
@lru_cache
@@ -190,7 +198,6 @@ def is_none(cls: GenericType) -> bool:
190198
return cls is type(None) or cls is None
191199

192200

193-
@lru_cache
194201
def is_union(cls: GenericType) -> bool:
195202
"""Check if a class is a Union.
196203
@@ -200,10 +207,12 @@ def is_union(cls: GenericType) -> bool:
200207
Returns:
201208
Whether the class is a Union.
202209
"""
203-
return get_origin(cls) in UnionTypes
210+
origin = getattr(cls, "__origin__", None)
211+
if origin is Union:
212+
return True
213+
return origin is None and isinstance(cls, types.UnionType)
204214

205215

206-
@lru_cache
207216
def is_literal(cls: GenericType) -> bool:
208217
"""Check if a class is a Literal.
209218
@@ -213,7 +222,7 @@ def is_literal(cls: GenericType) -> bool:
213222
Returns:
214223
Whether the class is a literal.
215224
"""
216-
return get_origin(cls) is Literal
225+
return getattr(cls, "__origin__", None) is Literal
217226

218227

219228
def has_args(cls: type) -> bool:

0 commit comments

Comments
 (0)