Skip to content

NamedTuple.__init__(**kwargs) doesn't type check #6823

Closed
@csingley

Description

@csingley
  • Are you reporting a bug, or opening a feature request?
    • Bug
  • Please insert below the code you are checking with mypy,
from typing import NamedTuple, Optional
from collections import OrderedDict

class Datum(NamedTuple):
    id: Optional[str] = None
    value: Optional[int] = None

# This passes type checking
# datum = Datum(value=1, id="foo")

# This fails to type check
attrs = {"id": "foo", "value": 1}

# This passes type checking
# attrs = OrderedDict([("id", "bar"), ("value", 1)])

datum = Datum(**attrs)
  • What is the actual behavior/output?
test.py:19: error: Argument 1 to "Datum" has incompatible type "**Dict[str, object]"; expected "Optional[str]"
test.py:19: error: Argument 1 to "Datum" has incompatible type "**Dict[str, object]"; expected "Optional[int]"
  • What is the behavior/output you expect?
    • mypy should treat dict unpacking the same as keyword assignment for NamedTuple.__init__()
  • What are the versions of mypy and Python you are using?
    • Python 3.7.3
    • mypy 0.701
  • Do you see the same issue after installing mypy from Git master?
    • yes
  • What are the mypy flags you are using? (For example --strict-optional)
    • none

I didn't see this issue reported; sorry if I overlooked. Using **OrderedDict is a workaround. as shown in the code sample above.

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