Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

typechecked methods of generics do not check typed iterators. #57

Closed
erp12 opened this issue Nov 28, 2018 · 1 comment
Closed

typechecked methods of generics do not check typed iterators. #57

erp12 opened this issue Nov 28, 2018 · 1 comment

Comments

@erp12
Copy link

erp12 commented Nov 28, 2018

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.

from typing import TypeVar, Generic, Iterator
from pytypes import typechecked

T = TypeVar('T')

class TypList(Generic[T], list):

    @typechecked
    def append(self, obj: T) -> None:
        super().append(obj)

    @typechecked
    def extend(self, iterable: Iterator[T]) -> None:
        super().extend(iterable)

    @typechecked
    def insert(self, index: int, obj: T) -> None:
        super().insert(index, obj)

class IntList(TypList[int]):
    ...

il = IntList() 

il.append(1) # No error, as expected
il.append("a") # InputTypeError as expected

il.extend(iter([1, 2, 3])) # No error, as expected
il.extend(iter(["a", "b", "c"])) # No error, somewhat unexpected

print(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.

@Stewori
Copy link
Owner

Stewori commented Oct 9, 2019

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.

@Stewori Stewori closed this as completed in 54a9876 Oct 9, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants