Skip to content

Suggestion: more precise inference when all elements are of same generic type #8392

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

Closed
Zac-HD opened this issue Feb 12, 2020 · 2 comments
Closed

Comments

@Zac-HD
Copy link
Contributor

Zac-HD commented Feb 12, 2020

Consider the following cases:

# A list of mixed cats and dogs is a list of animals.
class Animal: pass
class Cat(Animal): pass
class Dog(Animal): pass
pets = [Cat(), Dog()]  # note: Revealed type is 'builtins.list[Animal*]'

# A list of mixed ints and strings is a list of objects.
shallow = [1, "2"]  # note: Revealed type is 'builtins.list[builtins.object*]'

# A list of mixed lists-of-integers and lists-of-strings is also a list of objects!
nested = [[1], ["2"]]  # note: Revealed type is 'builtins.list[builtins.object*]'

Inferring the most precise type which is a parent of all the element types makes sense, but IMO the element type of nested should be inferred to be List[object] instead of object.


I'm using List here as a placeholder for any generic type - this is really more of an issue for things like Hypothesis strategies such as fixed_dictionaries(), with signature (Mapping[K, SearchStrategy[V]],) -> SearchStrategy[Mapping[K, V]].

This was reported downstream in HypothesisWorks/hypothesis#2349, because fixed_dictionaries({"num": integers(), "string": text()}) works but fails to type-check unless all values are strategies for the same type or the mapping is assigned to a type-annotated variable first.

Python 3.8 and Mypy 0.761, but it's not dependent on Python version.

@ilevkivskyi
Copy link
Member

We can probably special case list and dict literals somehow. I don't think there exists a deterministic algorithm that would infer such types consistently.

@AlexWaygood
Copy link
Member

Closing as a duplicate of #6968

@AlexWaygood AlexWaygood added the topic-join-v-union Using join vs. using unions label Apr 4, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants