You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I think this might be an impossible issue to fix because Python iterators (and all other standard collections) can hold elements of multiple types. Feel free to close without much consideration.
If I have a class that extends generic and has a method that takes an iterator, I cannot type check that the iterator has all elements of the desired type. This arises in the use case of creating a typed list which supports extend.
fromtypingimportTypeVar, Generic, IteratorfrompytypesimporttypecheckedT=TypeVar('T')
classTypList(Generic[T], list):
@typecheckeddefappend(self, obj: T) ->None:
super().append(obj)
@typecheckeddefextend(self, iterable: Iterator[T]) ->None:
super().extend(iterable)
@typecheckeddefinsert(self, index: int, obj: T) ->None:
super().insert(index, obj)
classIntList(TypList[int]):
...
il=IntList()
il.append(1) # No error, as expectedil.append("a") # InputTypeError as expectedil.extend(iter([1, 2, 3])) # No error, as expectedil.extend(iter(["a", "b", "c"])) # No error, somewhat unexpectedprint(il) # [1, 1, 2, 3, 'a', 'b', 'c'] <-- Ideally would only hold ints
In this case, a perfectly reasonable workaround is the check the contents of iterable manually, not using the decorator.
The text was updated successfully, but these errors were encountered:
I am implementing a fix that wraps iterables and iterators into little typecheckers.
For cases where this is too invasive, one can opt out via pytypes.check_iterables = False.
I think this might be an impossible issue to fix because Python iterators (and all other standard collections) can hold elements of multiple types. Feel free to close without much consideration.
If I have a class that extends generic and has a method that takes an iterator, I cannot type check that the iterator has all elements of the desired type. This arises in the use case of creating a typed list which supports
extend
.In this case, a perfectly reasonable workaround is the check the contents of
iterable
manually, not using the decorator.The text was updated successfully, but these errors were encountered: