Skip to content

Errors when using defaultdict #995

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
rowillia opened this issue Nov 24, 2015 · 5 comments
Closed

Errors when using defaultdict #995

rowillia opened this issue Nov 24, 2015 · 5 comments
Labels
bug mypy got something wrong

Comments

@rowillia
Copy link
Contributor

defaultdict's documentation suggests passing list as an argument to defaultdict - https://docs.python.org/2/library/collections.html#defaultdict-examples

mypy complains when I do this however

from collections import defaultdict

foo = defaultdict(list)
bar = defaultdict(dict)

Results in:

default_dict_example.py, line 3: Argument 1 to "defaultdict" has incompatible type List[_T]; expected Callable[[], List[_T]]
default_dict_example.py, line 3: Need type annotation for variable
default_dict_example.py, line 4: Argument 1 to "defaultdict" has incompatible type Dict[_KT, _VT]; expected Callable[[], Dict[_KT, _VT]]
default_dict_example.py, line 4: Need type annotation for variable
@gvanrossum
Copy link
Member

This seems a symptom of a general problem where classes don't seen to be considered compatible with callables. I've found a few other instances of this too.

@rowillia
Copy link
Contributor Author

Changing this to defaultdict(lambda: dict()) can be used as a work around, but then items coming out of the defaultdict aren't being type checked -

bar = defaultdict(lambda: dict())
bar.foobar() # works
bar['0'].foobar() # also works

@rowillia
Copy link
Contributor Author

Hmm, weird. In a standalone file I get an error about bar needing a type (which is equally strange). In the real example it's ignoring it's type.

@gvanrossum
Copy link
Member

Hm, this works for me:

from typing import MutableMapping, Any, Dict
bar = defaultdict(dict)  # type: MutableMapping[Any, Dict]

@JukkaL JukkaL added bug mypy got something wrong priority labels Nov 25, 2015
@JukkaL
Copy link
Collaborator

JukkaL commented Nov 25, 2015

Ah this is a dupe of #815.

@JukkaL JukkaL closed this as completed Nov 25, 2015
hauntsaninja added a commit to hauntsaninja/mypy that referenced this issue Jun 20, 2023
Linking python#995

I could fix this 3.12 regression, I guess, but what's the point
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

3 participants