-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
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
dict() overload insufficient #10013
Comments
Currently typing does not support multi-type lists. See python/typing#592. Unfortunately, there is no way for us to fix/work around this in typeshed. |
It's strange to see it closed. According to docs
It's OK if typing tools don't catch all the cases that are not possible to describe with current typing system. But explicitly disallowing valid cases is certainly a bug. The problem is not only with multi-type list, and even not lists only. The following case is valid too, but is not acceptable according to current annotations: dict([iter([1, 2]), iter([2, 3])]) |
Do you actually have a use case for As the comment says, we can't just accept an iterable of iterables, because then type checkers would not complain about |
Yes, the trouble here is that it's hard to write the types so that they accept everything the runtime accepts, while still rejecting a reasonable set of common mistakes. |
Not exactly, it was just a simplest example of valid code with false positive complaint due to bug in typeshed. Here is real life example with SQLAlchemy: result: CursorResult[tuple[str, some_type]] = await connection.execute(
select(some_table.c.string_field, some_table.c.some_type_field)
)
dict(result.all()) Here
Because for typing false negative is unfortunate, but ok, while false positive is a certain bug.
But it MUST NOT complaint about >>> dict(['ab', 'cd'])
{'a': 'b', 'c': 'd'} Do you mean we can potentially use strings of different length? But typing is not expected to cover all possible runtime errors. So |
In my case, I was parsing HTTP Headers into dict header_raw = b'''\
Host: example.com\r
User-Agent: curl/8.0.1\r
Accept: */*'''
result = dict(line.split(b': ') for line in header_raw.split(b'\r\n'))
print(result) When using str rather than bytes, it can be inferred. Not fixing this is not a big issue for me. I understand there are limitations. |
I added a similar overload with
I like "practicality beats purity": it just isn't practical for type checkers to be happy with that. It's more likely a mistake than not, and IMO it's exactly the kind of mistake that people expect type checkers to point out. |
This typing works with
dict([['a', '1'], ['b', '2']])
, but notdict([['a', 1], ['b', 2]])
Or
This works with
dict([('a', 1), ('b', 2)])
, but notdict([['a', 1], ['b', 2]])
The text was updated successfully, but these errors were encountered: