Skip to content

Bug: list('abc') not inferred to be of type List[str] #7766

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
AbhijeetKrishnan opened this issue Oct 21, 2019 · 3 comments
Closed

Bug: list('abc') not inferred to be of type List[str] #7766

AbhijeetKrishnan opened this issue Oct 21, 2019 · 3 comments

Comments

@AbhijeetKrishnan
Copy link

list('abc') should be inferred to be of type List[str]. However, we still get errors if used as the argument to a function.

MRE

import collections
named_tuple = collections.namedtuple('Test', list('abc'))

Command used

mypy code.py

Version

mypy 0.720
Python 3.7.4

Actual output

error: List or tuple literal expected as the second argument to namedtuple().

Expected behaviour

I would expect it to succeed without error.

Reference: pandas-dev/pandas#29114 (comment)

@msullivan
Copy link
Collaborator

list('abc') does get inferred as being of type List[str]. The issue here is that it is not a list "literal" -- that is, something like ["a", "b", "c"]. mypy needs it to be a literal so that it can easily read off and determine the names of the fields.

It would probably be possible to handle this particular case, but it doesn't seem common enough to be worth doing.

@ilevkivskyi
Copy link
Member

FYI, there is an idiomatic way of doing this, that is also supported by mypy:

from collections import namedtuple

C = namedtuple('C', 'a b c')
c = C(1, 2, 3)
c.a  # OK
c.x  # Error

@AbhijeetKrishnan
Copy link
Author

Thank you! mypy's behaviour is confusing me though. The error when the second argument is list('abc') is error: List or tuple literal expected as the second argument to namedtuple(). 'a b c' is neither a list nor a tuple (I believe it is a str). Why does mypy not complain in the latter case?

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

3 participants