问题
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