Question

How to explicitly list allowed keyword arguments in python for IDE support?

I'm using argparse.ArgumentParser in python and giving users the option to add their own functions to my script. For that, I'm giving them a function that generates data that gets used in argparse's add_argument() function. I noticed that add_argument's signature is add_argument(self, *args, **kwargs) but when looking at the documentation in vscode I can see all the different arguments it can get (action, nargs, const, default, etc.).

example screenshot

How does python do it? As far as I know when you give the user **kwargs it is shown as **kwargs and that's it.

I looked all over this site and the internet in general but I can't find the syntax used for it.

 3  72  3
1 Jan 1970

Solution

 1

VSCode's language server is pulling from the stub file in the typeshed, where the current definition is:

def add_argument(
    self,
    *name_or_flags: str,
    action: _ActionStr | type[Action] = ...,
    nargs: int | _NArgsStr | _SUPPRESS_T | None = None,
    const: Any = ...,
    default: Any = ...,
    type: _ActionType = ...,
    choices: Iterable[_T] | None = ...,
    required: bool = ...,
    help: str | None = ...,
    metavar: str | tuple[str, ...] | None = ...,
    dest: str | None = ...,
    version: str = ...,
    **kwargs: Any,
) -> Action: ...

Sidenote: It looks like you're using Pylance, which is adding some detail to the types. For example with _T@add_argument it's saying that _T is scoped to add_argument. I'm using Jedi which shows different details.

Reference

Editing Python in Visual Studio Code § Autocomplete and IntelliSense

Pylance is the default language server for Python in VS Code, and is installed alongside the Python extension to provide IntelliSense features.

Pylance is based on Microsoft's Pyright static type checking tool, leveraging type stubs (.pyi files) and lazy type inferencing to provide a highly-performant development experience.

See also

2024-06-30
wjandrea