Repository navigation
Conversation
|
Conflicts trivially with #3798 -- will rebase if needed. |
873c2a8 to
b991c36
Compare
|
This breaks a test in mypy (https://github.com/python/mypy/blob/09676c94ca885929322e0d5191df04d472d4df10/test-data/unit/pythoneval.test#L210), which breaks our CI. I agree that we should make this form return |
|
Thanks @JelleZijlstra, I sent python/mypy#8474. Even if this PR is rejected due to ergonomics, I still think the mypy one should be merged, to keep the option open. |
… not Any
`dict.fromkeys()` has two forms:
1. `dict.fromkeys([1,2], "foo")` -> `{1: 'foo', 2: 'foo'}`
2. `dict.fromkeys([1,2])` -> `{1: None, 2: None}`
Previously, the second form gave the type `dict[int, None]`. Presumably
this is done to accommodate the common case where the values are filled
in later.
I think type safety should trump the minor inconvenience of needing to
use the longer form, so change it to None instead.
|
I think by using |
b991c36 to
bd658bd
Compare
|
@srittau I personally prefer the strict option, but There is definitely an ergonomics argument to be made. Let's say we intend the value type to be d: Dict[int, Optional[int]] = dict.fromkeys([1,2,3], None)BTW, considering PEP 585 which will hopefully be implemented, I was wondering if there's actually a reason why the from typing import Generic, TypeVar, Iterable, Optional, overload
_K = TypeVar("_K")
_V = TypeVar("_V")
class Dict(Generic[_K, _V]):
@overload
@classmethod
def fromdict(cls, keys: Iterable[_K]) -> Dict[_K, None]: ...
@overload
@classmethod
def fromdict(cls, keys: Iterable[_K], value: _V) -> Dict[_K, _V]: ...
d1 = Dict.fromdict([1,2,3])
reveal_type(d1) # Revealed type is 'x.Dict[builtins.int*, None]'
d2 = Dict.fromdict([1,2,3], None)
reveal_type(d2) # Revealed type is 'x.Dict[builtins.int*, None]'
d3 = Dict[int, Optional[int]].fromdict([1,2,3], None)
reveal_type(d3) # Revealed type is 'x.Dict[builtins.int*, Union[builtins.int, None]]'Seems to work, and makes the form demonstrated in |
|
What we are really missing is a way to explicitly state the type of a type variable like other languages allow us to do: x = dict.fromkeys[str]([1, 2, 3]) # dict[int, Optional[str]]But that's getting off-topic now. I am fine with any solution for this PR. |
|
Closed per python/mypy#8474 (comment). |
dict.fromkeys()has two forms:dict.fromkeys([1,2], "foo")->{1: 'foo', 2: 'foo'}dict.fromkeys([1,2])->{1: None, 2: None}Previously, the second form gave the type
dict[int, None]. Presumablythis is done to accommodate the common case where the values are filled
in later.
I think type safety should trump the minor inconvenience of needing to
use the longer form, so change it to None instead.