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

Better support for defaultdict(lambda) #1205

Closed
mihneagiurgea opened this issue Feb 4, 2016 · 3 comments
Closed

Better support for defaultdict(lambda) #1205

mihneagiurgea opened this issue Feb 4, 2016 · 3 comments
Labels
false-positive mypy gave an error on correct code feature priority-2-low

Comments

@mihneagiurgea
Copy link

On this code:

from collections import defaultdict

from typing import Any, Dict, Tuple, Union

class Point(object):
    def __init__(self, x, y):
        # type: (int, int) -> None
        self.x = x
        self.y = y

x = defaultdict(lambda: Point(0, 0))

mypy complains with:

sandbox.py:12: error: Need type annotation for variable
@JukkaL
Copy link
Collaborator

JukkaL commented Feb 4, 2016

There isn't enough context to infer the defaultdict key type in your example, as nobody assigns anything to the dictionary.

However, mypy could do a better job in cases like this:

...
x = defaultdict(lambda: Point(0, 0))  # enough context to infer type defaultdict[int, Point]
x[1] = Point(2, 3)

@JukkaL JukkaL added the feature label Feb 4, 2016
@JukkaL
Copy link
Collaborator

JukkaL commented Feb 4, 2016

This is a little harder but could also be nice (though probably not high priority):

x = defaultdict(list)  # inferred type should be defaultdict[int, List[str]]
x[0].append('x')

@ddfisher ddfisher added this to the Future milestone Mar 1, 2016
@gvanrossum gvanrossum removed this from the Future milestone Mar 29, 2017
@JukkaL JukkaL added the false-positive mypy gave an error on correct code label May 18, 2018
@AlexWaygood
Copy link
Member

It seems like mypy's type inference has improved a great deal. Here's the output on mypy 0.941:

from collections import defaultdict
from typing import Any, Dict, Tuple, Union

class Point(object):
    def __init__(self, x, y):
        # type: (int, int) -> None
        self.x = x
        self.y = y

x = defaultdict(lambda: Point(0, 0))
x[1] = Point(2, 3)
reveal_type(x)  # Revealed type is "collections.defaultdict[builtins.int, __main__.Point]"

y = defaultdict(list)
y[0].append('x')
reveal_type(y)  # Revealed type is "collections.defaultdict[builtins.int, builtins.list[builtins.str]]"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
false-positive mypy gave an error on correct code feature priority-2-low
Projects
None yet
Development

No branches or pull requests

5 participants