-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Add support for collections.namedtuple #460
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
Comments
It's not implemented yet. |
I now noticed that some work-arounds are mentioned in the "Common issues" section of the "Creating stubs for Python modules" wiki page. |
The most primitive support would allow basic type checking with implicit X = namedtuple('X', ['a', 'b'])
x = X(1, 'x') # Ok
x.c # Type error
x.a + [1] # No error, since a has implicit type Any We also need to support class X(namedtuple('X', ['a', 'b'])):
... The above features would allow running mypy on code that uses named tuples and perform rudimentary type checking. The next step (potentially as a separate issue) would be to allow specifying item types. Here is a potential syntax: X = namedtuple('X', ['a', 'b']) # type: (int, str) Coming up with a syntax for the base class case is more difficult. Suggestions are welcome, or we can require the code to be rewritten like this: X = namedtuple('X', ['a', 'b']) # type: (int, str)
class X(X):
... |
I'm working on this. |
I just pushed an experimental, partial implementation of This is supported: from collections import namedtuple
X = namedtuple('X', ['a', 'b'])
x = X(1, 'x') # Ok
x = X(1, c='x') # Error
x.c # Error
x.a + [1] # No error, since a has implicit type Any
class Y(X):
"""you can use a namedtuple class as a base class""" Also, you can define the types of named tuple items using from typing import NamedTuple
X = NamedTuple('X', [('a', int), ('b', str)])
x = X(1, 'x') # Ok
x = X(1, 2) # Error A bunch of stuff is still broken or unsupported, but this should be good enough for (most) library stubs that need |
This is now implemented. It's not quite perfect yet, but it should be usable and I'll file issues for the remaining limitations (or just fix them). Now you can also use named tuples in the base class list: from typing import NamedTuple
class Foo(NamedTuple('Bar', [('item1', int), ('item2', str)])): # OK!
... |
I don't see NamedTuple defined in the https://github.com/JukkaL/typing project yet. mypy's own typing.py seems to have diverged (e.g. it has Callable, mypy still has Function, but mypy has NamedTuple). |
Mypy disallows usage of _replace() method from namedtuple (and likewise for NamedTuple). from collections import namedtuple ==> "Person" has no attribute "_replace" |
Yeah, the |
namedtupletest.py:
Test:
The text was updated successfully, but these errors were encountered: