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

mypy requires type annotations for empty lists even if they're never added #1164

Closed
timabbott opened this issue Jan 27, 2016 · 6 comments
Closed
Labels
false-positive mypy gave an error on correct code feature priority-1-normal

Comments

@timabbott
Copy link

timabbott commented Jan 27, 2016

Reproducer:

foo: bool
if foo:
    x = []
else:
    x = ["liststr"]

print(x)

Error: foo.py:12: error: Need type annotation for variable

It seems like this is a case where mypy can be 100% confident that a type annotation is pointless, and so it should probably not throw an error.

@JukkaL JukkaL added the feature label Jan 28, 2016
@JukkaL
Copy link
Collaborator

JukkaL commented Jan 28, 2016

Yeah, mypy should infer the type of x. This was actually on my to-do list when I recently improved type inference, but I didn't implement this because I hadn't seen examples in the wild. Now I have :-)

@ddfisher ddfisher added this to the 0.3.3 milestone Mar 1, 2016
@saxbophone
Copy link

+1 for this, have found the same is true for empty dicts.

I think it would also be quite helpful if there was an option to make type-checking of variables optional, but this would be a separate issue I think. If such an issue does not already exist, I may create one to explore this idea.

@yoon28
Copy link

yoon28 commented Feb 14, 2019

Why should we declare the type of container? Python container, such as list, set and dict, can have various types of data. We can store 'str' and 'int' to one list at the same time. Why mypy need that?

@JukkaL
Copy link
Collaborator

JukkaL commented Feb 14, 2019

Mypy needs to know the item types so that it can check that any operations on the items are valid. It also uses the types to check that you don't accidentally add values with invalid types. If you don't care about the types, you can use List[Any], for example, to allow arbitrary items.

@robertocarta
Copy link

@JukkaL is there a setting to make List[Any] the default list type?

@JukkaL
Copy link
Collaborator

JukkaL commented Jul 3, 2020

@robertocarta You can try --allow-untyped-globals.

The original example no longer generates an error, so I'm closing this issue. If there are other cases which don't work as expected, feel free to open a new issue.

@JukkaL JukkaL closed this as completed Jul 3, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
false-positive mypy gave an error on correct code feature priority-1-normal
Projects
None yet
Development

No branches or pull requests

7 participants