Thanks to visit codestin.com
Credit goes to github.com

Skip to content

TypedDict fields cannot be defined with variables #8186

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
bsamseth opened this issue Dec 20, 2019 · 1 comment
Closed

TypedDict fields cannot be defined with variables #8186

bsamseth opened this issue Dec 20, 2019 · 1 comment

Comments

@bsamseth
Copy link

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})
@ilevkivskyi
Copy link
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
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants