Skip to content

TypedDict fields cannot be defined with variables #8186

Closed

Description

@bsamseth

Bug or opening a feature request?

A bug.

Minimal example

Using the alternative definition syntax for TypedDict (which should be equivalent according to PEP 589), the field names cannot be stored in variables (expected). But, I would expect Final or Literal typed variables to be accepted. See the following example:

from typing import TypedDict, Final, Literal

A = TypedDict("A", {"x": int})  # No issues, as expected.
d: A = {"x": 1}

x: Final = "x"
B = TypedDict("B", {x: int})  # Unexpected error 1.
dd: B = {"x": 1}  # Unexpected error 2.

x_literal: Literal["x"] = "x"
C = TypedDict("C", {x_literal: int})  # Unexpected error 3.
ddd: C = {"x": 1}  # Unexpected error 4.

What is the actual behaviour/output?

$ mypy repro.py
repro.py:8: error: Invalid TypedDict() field name
repro.py:9: error: Extra key 'x' for TypedDict "TypedDict"
repro.py:12: error: Invalid TypedDict() field name
repro.py:13: error: Extra key 'x' for TypedDict "TypedDict"
Found 4 errors in 1 file (checked 1 source file)

What is the behaviour/output you expect?

No errors, or at least one of the two options succeeding (Final or Literal).

The type annotations are equivalent, as far as I can tell.

>>> x: Final[str] = "x"
>>> A = TypedDict("A", {"x": int})
>>> A.__annotations__
{'x': <class 'int'>}
>>> B = TypedDict("B", {x: int})
>>> B.__annotations__
{'x': <class 'int'>}

What are the versions of mypy and Python you are using?

$  python --version
Python 3.8.0
$ mypy --version
mypy 0.761

Same behaviour on master (ce186f4).

Use case

We have defined constants for the field names of dictionaries read from JSON files. I would like to make TypedDict's for these various dictionaries so that mypy can better check our code (instead of marking all dicts with Dict[str, Any].

I would like to define the fields using these predefined constants.

# a.py
FIELD_A: Final = "field_a"
FIELD_B: Final = "field_b"

# b.py
MyDict = TypedDict("MyDict", {FIELD_A: int, FIELD_B: bool})

Activity

  1. ilevkivskyi commented on Dec 20, 2019

    @ilevkivskyi
    Member

    This is essentially a duplicate of #4128

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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