Skip to content

Subclasses of NamedTuple #3739

Closed
Closed
@progval

Description

@progval

Hi,

I often use a subclass to a namedtuple to add optional arguments (and/or methods) to a namedtuple.

For instance, this gives this kind of code:

     1	from typing import *
     2	
     3	_Foo = NamedTuple('_Foo', [
     4	    ('bar', str),
     5	    ('baz', str),
     6	    ])
     7	
     8	class Foo(_Foo):
     9	    def __new__(cls, bar, baz='z') -> 'Foo':
    10	        return _Foo.__new__(cls, bar, baz)
    11	
    12	def f() -> None:
    13	    print(repr(Foo('r')))
    14	
    15	f() # prints Foo(bar='r', baz='z')

which I think is completely valid Python.

However, Mypy raises the following errors:

foo.py:10: error: Too many arguments for "__new__" of "object"
foo.py:10: error: Argument 1 to "__new__" of "object" has incompatible type Type[Foo]; expected Type[object]
foo.py:13: error: Too few arguments for "Foo"

Is there something I am doing wrong?

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions