-
Hello! How would I go about creating a custom type hint for use with from typing import Iterable
from multimethod import multimethod
def is_coll(coll):
if isinstance(coll, (str, bytes, bytearray)):
return False
else:
try:
iter(coll)
except TypeError:
return isinstance(coll, Iterable)
else:
return True
class MetaColl(type):
def __instancecheck__(cls, other):
return is_coll(other)
def __subclasscheck__(cls, other):
return is_coll(other)
class Coll(metaclass=MetaColl):
pass
@multimethod
def test(a: str):
print(a)
@multimethod
def test(a: Coll):
for item in a:
print(item)
print(isinstance("Hello!", Coll)) # False
print(isinstance("Hello!".split(), Coll)) # True
test("Hello!") # False
test("Hello!".split()) # DispatchError: ('test: 0 methods found', (<class 'list'>,), set()) Thank you kindly for the help! |
Beta Was this translation helpful? Give feedback.
Answered by
coady
Mar 8, 2024
Replies: 1 comment 1 reply
-
>>> issubclass(list, Coll)
False
class Coll(abc.ABC):
@classmethod
def __subclasshook__(cls, subclass):
return issubclass(subclass, Iterable) and not issubclass(subclass, (str, bytes, bytearray))
>>> issubclass(list, Coll)
True
>>> issubclass(str, Coll)
False
|
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
coady
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Coll
doesn't implement the subclass check correctly.issubclass(str, Iterable)
. So ifstr
is being matched, it will take precedence overIterable
anyway.