Assuming I’m properly typing my python code, is there a way or extension to get vscode to only offer autocomplete options that are appropriate for that parameter?
For example:
from enum import IntEnum
class MyEnum(IntEnum):
OneThing = 1
Another = 2
EvenMore = 3
def my_function(parameter : MyEnum):
print(parameter)
Now when I start writing my code, I type…
my_function(
And it completes the ()
and offers info on the type that needs to go there.
I’d LIKE for me to be able to start typing One
and have it have MyEnum.OneThing in its suggestions
If I create a variable at the top scope like…
MyEnum_OneThing = MyEnum.OneThing
I can then type
my_function(One
and it will autocomplete the )
and suggest MyEnum_OneThing
Is there a way to get it to suggest MyEnum.OneThing
? We have some objects with hundreds of enumerated values and we’d like autocomplete/intellisense to be a little more helpful.
(Or, I suppose, an alternate solution would be a way to automate the MyEnum_<thing>=MyEnum.<thing> so that the enum with 100s of items ends up at the top level scope so intellisense picks it up.
Ensure your function has type hints and detailed docstrings:
from enum import IntEnum
class MyEnum(IntEnum):
OneThing = 1
Another = 2
EvenMore = 3
def my_function(parameter: MyEnum):
"""
Function that does something with MyEnum.
:param parameter: Enum of type MyEnum
"""
print(parameter)
Then create a custom snippet in VS Code:
- Go to File > Preferences > User Snippets.
- Select python.json (or create a new global snippet file).
- Add the snippet:
{
"MyEnum Snippet": {
"prefix": "MyEnum.",
"body": [
"MyEnum.${1|OneThing,Another,EvenMore|}"
],
"description": "Autocomplete for MyEnum members"
}
}
Finally, you could Write a script to create variables for enum
members:
from enum import IntEnum
class MyEnum(IntEnum):
OneThing = 1
Another = 2
EvenMore = 3
globals().update({f"MyEnum_{member.name}": member for member in MyEnum})
def my_function(parameter: MyEnum):
print(parameter)
In this way, you will have top-level variables for each enum
member, which will be picked up by IntelliSense.