Changeset View
Changeset View
Standalone View
Standalone View
swh/model/model.py
Show First 20 Lines • Show All 85 Lines • ▼ Show 20 Lines | |||||
def _check_type(type_, value): | def _check_type(type_, value): | ||||
if type_ is object or type_ is Any: | if type_ is object or type_ is Any: | ||||
return True | return True | ||||
origin = getattr(type_, "__origin__", None) | origin = getattr(type_, "__origin__", None) | ||||
# Non-generic type, check it directly | # Non-generic type, check it directly | ||||
if origin is None: | if origin is None: | ||||
return type(value) == type_ | # This is functionally equivalent to using just this: | ||||
# return isinstance(value, type) | |||||
# but using type equality before isinstance allows very quick checks | |||||
# when the exact class is used (which is the overwhelming majority of cases) | |||||
# while still allowing subclasses to be used. | |||||
return type(value) == type_ or isinstance(value, type_) | |||||
# Check the type of the value itself | # Check the type of the value itself | ||||
if origin is not Union and type(value) != origin: | # | ||||
# For the same reason as above, this condition is functionally equivalent to: | |||||
# if origin is not Union and not isinstance(value, origin): | |||||
if origin is not Union and type(value) != origin and not isinstance(value, origin): | |||||
return False | return False | ||||
# Then, if it's a container, check its items. | # Then, if it's a container, check its items. | ||||
if origin is tuple: | if origin is tuple: | ||||
args = type_.__args__ | args = type_.__args__ | ||||
if len(args) == 2 and args[1] is Ellipsis: | if len(args) == 2 and args[1] is Ellipsis: | ||||
# Infinite tuple | # Infinite tuple | ||||
return all(_check_type(args[0], item) for item in value) | return all(_check_type(args[0], item) for item in value) | ||||
▲ Show 20 Lines • Show All 1,185 Lines • Show Last 20 Lines |