microsoft / pyright

Static Type Checker for Python
Other
13.48k stars 1.48k forks source link

Better support for accessing __args__ in runtime #9495

Open PythonCoderAS opened 3 days ago

PythonCoderAS commented 3 days ago

Type: Feature Request

For a lot of the Python typing functions, we can determine the type of args from the arguments. For example, if you have a Union (or the union by | ing types), __args__ is a tuple[type[...]].

Example:

MY_TYPE = str | int | bool
print(MY_TYPE.__args__) # (str, int, bool)
type_args: tuple[str, int, bool] = MY_TYPE.__args__

The type checker could reasonably guess the types in that instance without me having to explicitly annotate it. Another example using literals:

from typing import Literal

MY_LITERAL = Literal[1, 2, 3, 4, 5]
print(MY_LITERAL.__args__) # (1, 2, 3, 4, 5)
literal_args: tuple[Literal[1], Literal[2], Literal[3], Literal[4], Literal[5]] = MY_LITERAL.__args__

Some similar inference could be done here. The current annotation of tuple[Any, ...] is correct but it would be nicer if interacting with __args__ in the runtime (such as pulling values out of a Literal).

Extension version: 2024.11.3 VS Code version: Code 1.95.3 (f1a4fb101478ce6ec82fe9627c43efbf9e98c813, 2024-11-13T14:50:04.152Z) OS version: Darwin x64 24.0.0 Modes:

erictraut commented 3 days ago

Could someone from the pylance team please transfer this to the pyright project?

erictraut commented 3 days ago

The __args__ parameter for UnionType objects is defined here in the typeshed stubs. In general, pyright does not override the types provided in typeshed. Doing so usually leads to maintenance and correctness issues.

In general, static type checkers do not concern themselves with the runtime representation of type forms (objects that result from the runtime evaluation of type expressions). This is the domain of runtime type checkers.

For these reasons, I'm going to reject this enhancement request.