Skip to content

DefaultDict Typing is Overly Strict #7159

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
blink1073 opened this issue Feb 7, 2022 · 3 comments
Closed

DefaultDict Typing is Overly Strict #7159

blink1073 opened this issue Feb 7, 2022 · 3 comments

Comments

@blink1073
Copy link

The docs for defaultdict say:

The first argument provides the initial value for the default_factory attribute; it defaults to None. All remaining arguments are treated the same as if they were passed to the dict constructor, including keyword arguments.

However, the second argument is currently treated as a generic type that influences the type of the first argument.

The following should be valid:

>>> dict([('foo', 'bar')])
{'foo': 'bar'}
>>> dct = collections.defaultdict(dict, [('foo', 'bar')])
>>> dct
defaultdict(<class 'dict'>, {'foo': 'bar'})
>>> dct['g']
{}
>>> dct
defaultdict(<class 'dict'>, {'foo': 'bar', 'g': {}})

However, we get the error error: Argument 1 to "defaultdict" has incompatible type "Type[Dict[Any, Any]]"; expected "Optional[Callable[[], str]]".

@AlexWaygood
Copy link
Member

AlexWaygood commented Feb 7, 2022

It works fine as long as you give it an explicit annotation:

from collections import defaultdict
from typing import Any

dct: defaultdict[str, str | dict[Any, Any]] = defaultdict(dict, [('foo', 'bar')])

<=3.8 compatible version, if you're not using from __future__ import annotations:

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

dct: DefaultDict[str, Union[str, Dict[Any, Any]]] = defaultdict(dict, [('foo', 'bar')])

@blink1073
Copy link
Author

Makes sense, thanks @AlexWaygood!

@AlexWaygood
Copy link
Member

Makes sense, thanks @AlexWaygood!

No worries, happy typing!

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