Is it possible to “hint” dictionary keys?

时光毁灭记忆、已成空白 提交于 2021-01-28 11:47:43

问题


In PyCharm Code completion > "Basic Completion" > "Invoke Basic Completion" > "Dictionaries" I see that, if you hard-code a dictionary to some values, you can use code completion when writing code about that dictionary.

But obviously, in many cases, you will work with a dict and you have some idea in advance what the structure of that dict will be, and you don't want to hard-code the dict into your code. For example, maybe you're parsing some YAML or JSON that has an expected structure.

It would be really nice if you could "hint" the structure in Python, so you could easily and rapidly code all the places you use that dictionary. Is that possible?


回答1:


As far as I'm aware, there's no agreed way to type-hint the specific key names and associated values of a Python dictionary until TypedDict is introduced in Python 3.8.




回答2:


There is no "official" support for typed (hinted) dictionaries in Python yet. However, the mypy_extensions package does expose TypedDict which supports the following syntax for defining typed dictionaries which can be validated by MyPy.

DictT = TypedDict(
    'DictT ',
    {
         'field': str, 
         'int_field': int,
    }
)

https://www.python.org/dev/peps/pep-0589/#alternative-syntax

You could then integrate MyPy into PyCharm but according to their bug tracker there is no direct support for type hinting TypedDicts https://youtrack.jetbrains.com/issue/PY-36008 .



来源:https://stackoverflow.com/questions/56198483/is-it-possible-to-hint-dictionary-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!