Skip to content

TypedDict handles unicode names and keys inconsistently in Python 2 #6123

Closed
@Michael0x2a

Description

@Michael0x2a

I noticed an minor inconsistency in the way mypy handles the following program in Python 2:

from __future__ import unicode_literals
from mypy_extensions import TypedDict

MyDict = TypedDict('MyDict', {'foo': int})

Mypy type-checks this problem without errors. However, if you actually try running this program at runtime, you get the following exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\site-packages\mypy_extensions.py", line 40, in _typeddict_new
    '__total__': total})
  File "C:\Python27\lib\site-packages\mypy_extensions.py", line 52, in __new__
    tp_dict = super(_TypedDictMeta, cls).__new__(cls, name, (dict,), ns)
TypeError: type() argument 1 must be string, not unicode

You have to do MyDict = TypedDict(b'MyDict', {'foo': int}) to get this program to both typecheck and run.

I'm not sure whether the correct thing to do is modify mypy to report an error or to relax the runtime implementation.

On one hand, type(name, bases, dict) legitimately won't accept unicode names in Python 2 so perhaps we should add a check to mypy. On the other, we don't get the same kind of runtime error when creating NamedTuples, so perhaps it's better to try and convert the unicode name to str inside TypedDict for consistency.

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions