Skip to content

Commit

Permalink
Add python < 3.10 compatibility
Browse files Browse the repository at this point in the history
  • Loading branch information
tarsil committed Oct 10, 2023
1 parent ef424da commit 60e7dcc
Showing 1 changed file with 18 additions and 6 deletions.
24 changes: 18 additions & 6 deletions polyforce/decorator.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,17 +48,29 @@ def check_types(*args: Any, **kwargs: Any) -> Any:
if isinstance(type_hint, _SpecialForm) or type_hint == Any:
continue

actual_type = get_origin(type_hint)
if isinstance(actual_type, typing._SpecialForm):
actual_type = get_args(value)
_type = actual_type or type_hint

if not isinstance(value, _type):
actual_type = get_actual_type(type_hint=type_hint, value=value)
if not isinstance(value, actual_type):
raise TypeError(
f"Expected type '{type_hint}' for attribute '{name}'"
f" but received type '{type(value)}') instead."
)

def get_actual_type(type_hint: Any, value: Any) -> Any:
"""
Checks for all the version of python.
"""
if hasattr(type_hint, "__origin__"):
actual_type = type_hint.__origin__
else:
actual_type = get_origin(type_hint)

# For versions prior to python 3.10
if isinstance(actual_type, typing._SpecialForm):
actual_type = (
get_args(value) if not hasattr(type_hint, "__origin__") else type_hint.__args__
)
return actual_type or type_hint

def decorate(func: Any) -> Any:
@wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> Any:
Expand Down

0 comments on commit 60e7dcc

Please sign in to comment.