Search code examples
pythonvisual-studio-codepylance

How does autocompletion work on Visual Studio Code (Python, tkinter)?


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 I 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 found here the values proposed by autocompletion (['left', 'right', 'top', 'button']) (see lines commented #Interesting).

I would like to enable this autocompletion for my functions. Is Literal the cause of autocompletion? If so, is this a proper way to use it in my functions?


Solution

  • 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 :

    from typing_extensions import Literal #Important, Literal doesn't exist otherwise
    
    class Person:
        def __init__(self, **attributes):
            self.attributes = attributes
    
        def get(self, attribute: Literal['first_name', 'last_name', 'age']):
            return self.attributes.get(attribute)
        
    john_smith = Person(first_name='John', last_name='Smith', age=34)
    print( john_smith.get('age') )
    

    See the result here.