From 20bae26b3421f2bbf0fe8c62a2855e16f6358a5b Mon Sep 17 00:00:00 2001 From: Erez Shinan Date: Fri, 13 Sep 2024 18:32:54 +0300 Subject: [PATCH] Bugfix in dispatch: Now properly handles Any (this bug was caused by a previous fix to match mypy behavior) --- runtype/dispatch.py | 5 ++++- runtype/typesystem.py | 4 +++- runtype/validation.py | 6 ++++-- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/runtype/dispatch.py b/runtype/dispatch.py index d3f44b8..27581ce 100644 --- a/runtype/dispatch.py +++ b/runtype/dispatch.py @@ -188,12 +188,15 @@ def define_function(self, f): def choose_most_specific_function(self, args, *funcs): issubclass = self.typesystem.issubclass + any_type = self.typesystem.any_type class IsSubclass: def __init__(self, k): self.i, self.t = k def __lt__(self, other): + if self.t is any_type: + return False return issubclass(self.t, other.t) most_specific_per_param = [] @@ -208,7 +211,7 @@ def __lt__(self, other): if ms_t == t: # Add more indexes with the same type ms_set.add(i) - elif issubclass(t, ms_t) or not issubclass(ms_t, t): + elif (issubclass(t, ms_t) and t is not any_type) or not issubclass(ms_t, t): # Possibly ambiguous. We might throw an error below # TODO secondary candidates should still obscure less specific candidates # by only considering the top match, we are ignoring them diff --git a/runtype/typesystem.py b/runtype/typesystem.py index 977166a..363c7d1 100644 --- a/runtype/typesystem.py +++ b/runtype/typesystem.py @@ -1,4 +1,4 @@ - +from typing import Any class TypeSystem: def isinstance(self, obj, t: type) -> bool: @@ -14,6 +14,7 @@ def get_type(self, obj) -> type: raise NotImplementedError() default_type: type = NotImplemented + any_type: type = NotImplemented @@ -22,3 +23,4 @@ class PythonBasic(TypeSystem): issubclass = issubclass get_type = type default_type = object + any_type = Any diff --git a/runtype/validation.py b/runtype/validation.py index 9d68599..06f7189 100644 --- a/runtype/validation.py +++ b/runtype/validation.py @@ -5,7 +5,8 @@ from .common import CHECK_TYPES from .utils import get_func_signatures -from .pytypes import TypeMismatchError, type_caster, All +from .pytypes import TypeMismatchError, type_caster +from . import pytypes from .typesystem import TypeSystem def ensure_isa(obj, t, sampler=None): @@ -69,7 +70,8 @@ class PythonTyping(TypeSystem): issubclass = staticmethod(issubclass) to_canonical_type = type_caster.to_canon get_type = type - default_type = All + default_type = pytypes.All + any_type = pytypes.Any def validate_func(f):