Skip to content

Inconsistent name mangling in TypedDict in function and class forms #129567

Closed
@sobolevn

Description

@sobolevn

Bug report

Let's say that you have a dict like {"__key": 1} and you want to type it.

You can write:

>>> import typing
>>> class A(typing.TypedDict):
...     __key: int

>>> A.__mutable_keys__
frozenset({'_A__key'})

and:

>>> B = typing.TypedDict("B", [("__key", int)])
>>> B.__mutable_keys__
frozenset({'__key'})

Note that A mangles __key as a regular name. While B does not.

I guess that it is expected, but!
Docs (https://docs.python.org/3/library/typing.html#typing.TypedDict) does not say anything about this behavior. We only mention that functional form should be used for invalid identifiers. But, __key is a valid indentifier.
We don't have explicit tests for this either.
And Typing Spec does not mention this as well: https://typing.readthedocs.io/en/latest/spec/typeddict.html

So, what we can do:

  • Do not mangle names in this case (hard and problematic: it can break existing stuff)
  • Document and test current behavior (my vote)

Please, share your thoughts on this. And I willing to send a PR with the fix.

Linked PRs

Metadata

Metadata

Assignees

Labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions