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

Unpack iterable class to its declared type for __iter__ #14496

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

flaeppe
Copy link

@flaeppe flaeppe commented Jan 21, 2023

I've started an attempt to fix #14470. There's probably more stuff to be done here, as I've basically copy-pasted as much as I could of the behaviour of checker.TypeChecker.iterable_item_type.

mypy/mypy/checker.py

Lines 6347 to 6363 in cc1bcc9

def iterable_item_type(self, instance: Instance) -> Type:
iterable = map_instance_to_supertype(instance, self.lookup_typeinfo("typing.Iterable"))
item_type = iterable.args[0]
if not isinstance(get_proper_type(item_type), AnyType):
# This relies on 'map_instance_to_supertype' returning 'Iterable[Any]'
# in case there is no explicit base class.
return item_type
# Try also structural typing.
iter_type = get_proper_type(find_member("__iter__", instance, instance, is_operator=True))
if iter_type and isinstance(iter_type, CallableType):
ret_type = get_proper_type(iter_type.ret_type)
if isinstance(ret_type, Instance):
iterator = map_instance_to_supertype(
ret_type, self.lookup_typeinfo("typing.Iterator")
)
item_type = iterator.args[0]
return item_type

As that happened to resolve the issue I found. I'm not at all sure this is even a valid approach, I just wanted to check in on the idea before going any further. Any kind of feedback here would be much appreciated.

Fixes #14470

@github-actions
Copy link
Contributor

According to mypy_primer, this change has no effect on the checked open source code. 🤖🎉

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

Successfully merging this pull request may close these issues.

Custom __iter__ method yields false positive when used with star args (*)
1 participant