问题
I am using Python 3.6 with PyCharm and it's kind of frustrating that there's no support for code completion for special cases of dictionary objects (with fixed key schema).
Say for example I create and try to access a simple dictionary object like this:
inventory = {'name': 'hammer', 'price': 2.3}
inventory['']
When I position my cursor inside the quotes ' ' and hit Ctrl + Space
i get code completion and the IDE correctly suggests all the possible keys in the dictionary object. That's great!
But if i try to build it as a utility function that returns this same dict object, say with values that the user provide but with the same dict keys - then I don't get code completion anymore!
def get_inventory(name: str, price: float):
return {'name': name, 'price': price}
inventory = get_inventory('hammer', 2.3)
inventory[''] # <- Pycharm can't offer any suggestions!
Any workaround or solution for this? I searched already for similar solutions but I didn't find anything that works. I know I can just convert it into a class Inventory
and access the properties that way but I don't want to do it for a couple of reasons:
- I need the object to be easily JSON convertable since i might pass it from / to JSON a lot and
dict
objects are the easiest for this purpose - storing it as a class wouldn't make much sense since i just need it as a data container anyway, with minimal properties stored within it
Any help or solution for how I can get my IDE to assist in code completion by recognizing the possible keys in such a dict
object would be greatly appreciated!
回答1:
PyCharm has no idea what a dict
contains because its keys and values are denoted at runtime. So you have to somehow hint PyCharm about the keys of dict
beforehand. Prodict does exactly this to hint PyCharm, so you get the code completion.
class Inventory(Prodict):
name: str
price: float
def get_inventory(name: str, price: float):
return Inventory(name=name, price=price)
inventory = get_inventory('hammer', 2.3)
print(inventory.name)
print(inventory.price)
In the above code, both name
and price
attributes are auto-completed.
Since Prodict is derived directly from dict
, so you can use it as a regular dict
.
This is the screenshot from the Prodict repo that illustrates code completion:
PS: I am the author of the Prodict.
来源:https://stackoverflow.com/questions/52318992/how-to-enable-code-completion-for-a-dictionary-from-method-in-python