I’m usually coding in python on Visual Studio Code, and using tkinter.
When I start typing a function’s options, it sometimes suggests me their values,
like here
I do not know at all where it comes from :
- Is it because of
tkinter
? - Is it Visual Studio Code ?
- Is it Pylance ? (I don’t know what it is, but read ‘Pylance’ in similar autocompletions)
I also noticed that when I wanted to create a class
inheriting from an existing class with an existing function :
from tkinter import *
class MyClass (Label):
def pack_conf
I clicked on tab
and this appeared :
# These imports were almost all automatically added :
from collections.abc import Mapping
from tkinter import *
from tkinter import _Anchor, _ScreenUnits
from typing import Any
from typing_extensions import Literal
class MyClass (Label):
def pack_configure(self,
cnf: Mapping[str, Any] | None = ...,
*,
after: Misc = ..., anchor: _Anchor = ...,
before: Misc = ..., expand: int = ...,
fill: Literal['none', 'x', 'y', 'both'] = ..., # Interesting
side: Literal['left', 'right', 'top', 'bottom'] = ..., # Interesting
ipadx: _ScreenUnits = ..., ipady: _ScreenUnits = ...,
padx: _ScreenUnits | tuple[_ScreenUnits, _ScreenUnits] = ...,
pady: _ScreenUnits | tuple[_ScreenUnits, _ScreenUnits] = ...,
in_: Misc = ...,
**kw: Any
) -> None:
return super().pack_configure(cnf, after=after, anchor=anchor, before=before, expand=expand, fill=fill, side=side, ipadx=ipadx, ipady=ipady, padx=padx, pady=pady, in_=in_, **kw)
I would like to enable this autocompletion for my functions. Is Literal
the cause of autocompletion ? If so, is this a proper way to do this ?
2
Answers
I finally found the answer to my question.
My question was not to complete a function's name but the value of arguments (see again here).
I tried
Literal
, and it worked :See the result here.
yes it’s Pylance for python files. In general VS code can use a "Language Server" to analyze your code and provide warnings, autocompletion etc.
Pylance should already automatically be providing autocompletion for you code. For example if you write:
then
ctrl
+space
I get:notice though it says foo can be any type, this isn’t as nice as it could be, as it won’t be able to autocomplete things related to foo without knowing it’s type.
For example if you typed:
then you could autocomplete strip because it knows the type of my_thing, but if you tried the same thing for foo it doesn’t provide any help:
So to get pylance to provide useful suggestions you have to let it know the types of your variables. In this case it’s like so:
So you probably just need to start typing the variables that you’d like autocomplete to work on.