Why can a Final dictionary not be used as a literal in TypedDict?

Viewed 297

I am trying to accomplish the below (see mypy playground):

from typing import TypedDict, Final

account_schema: Final = {"name": str, "email": str}

Account = TypedDict("Account", account_schema)
AccountPatch = TypedDict("AccountPatch", account_schema, total=False)

Idea is that I can have my schema specified in one place, with a version requiring all fields (Account, when inserting in database) and a version making all fields optional (AccountPatch, when updating a database).

From PEP 586:

The Final qualifier serves as a shorthand for declaring that a variable is effectively Literal.

But mypy errors with:

error: TypedDict() expects a dictionary literal as the second argument

Why does TypedDict not allow a Final dictionary as its second argument?

For my core problem, is there anyway I can use the same schema for two TypedDicts (one with totality, one with no totality) without having to duplicate the schema?

1 Answers

As pointed out in the comments, it is not possible. See the issue raised on mypy's github: TypedDict keys reuse?. The error is raised here.

The only way to define your two TypeDict is by repeating the code

from typing import TypedDict

Account = TypedDict("Account", {"name": str, "email": str})
AccountPatch = TypedDict("AccountPatch", {"name": str, "email": str}, total=False)
Related