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

generator in dict: No overloads for "__init__" ... #6015

Closed
ewerybody opened this issue Sep 9, 2021 · 3 comments · Fixed by #6050
Closed

generator in dict: No overloads for "__init__" ... #6015

ewerybody opened this issue Sep 9, 2021 · 3 comments · Fixed by #6050

Comments

@ewerybody
Copy link
Contributor

Hello! With Pylance I get a typing error highlighted for the following code:

line = 'NAME|a=2345|b=SDFdss sdfsdf|ignored|c=another'
parts = line.strip().split('|')
attrs = dict(p.split('=', 1) for p in parts if '=' in p) # < HERE
No overloads for "__init__" match the provided arguments
  Argument types: (Generator[list[str], None, ...

I got the code working like that for aaaages!! But I see: a list can have different lengths and the ways I am making sure
it is like len == 2 is not obvious to the type checker, right?

I figured adding this into the builtins.pyi under class dict... makes the error go away:

    @overload
    def __init__(self, iterable: Iterable[Iterable[str]]) -> None: ...

But is there another way to make this more type safe?
Cheers:
ëRiC

@Akuli
Copy link
Collaborator

Akuli commented Sep 9, 2021

There is no way to say "a list with exactly 2 elements", but we could add another __init__ overload for lists in general. It would mean that mypy won't complain if you do dict([[1, 2], [3, 4, 5]]), but that's fine. We generally prefer false negatives (type checker doesn't complain about wrong code) over false positives (type checker complains about correct code).

@srittau
Copy link
Collaborator

srittau commented Sep 9, 2021

See also python/typing#592 and python/typing#786 for suggestions to add fixed-length sequences. I agree that we should probably add another overload, although I would suggest to allow sequences in general, not only lists.

@Akuli
Copy link
Collaborator

Akuli commented Sep 9, 2021

Sequences in general would mean that arbitrary-length tuples are allowed too.

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

Successfully merging a pull request may close this issue.

3 participants