-
Notifications
You must be signed in to change notification settings - Fork 1.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Support TypeScript-style "evolving" types for []
-initialized values
#9281
Comments
This feature has been proposed previously for pyright. Although I like the feature in TypeScript, I'm very reluctant to add it in pyright for the following reasons.
function push_string(x: (number | string)[]) {
x.push('');
}
function test() {
const x = [];
x.push(1);
push_string(x);
// x's type is inferred to be "number[]", but the array contains strings!
return x;
} I'll give this a bit more thought, but I wanted to share my current thinking. |
After thinking about this further, I've come up with even more reasons against implementing this in pyright.
function test(cond: boolean) {
const x = [];
if (cond) {
x.push(1);
// The inferred type of x here is "number[]"
} else {
x.push("hello");
// The inferred type of x here is "string[]"
}
// The type of x here is "(number | string)[]"
return x;
}
The recommended approach is to use an explicit type annotation to specify the intended type of the list. xs: list[int] = []
xs.append(1) |
Thanks for considering the proposal @erictraut, and for the detailed response. Regarding point 4, perhaps I've just internalized how TypeScript handles these situations, but what is the "hole"? The type of The TS feature has many of the same issues that you described. In any case, thanks for the rationale, and for the fantastic tool! |
Is your feature request related to a problem? Please describe.
Here's some valid Python code that pyright is unhappy with in strict mode:
(pyright playground)
Describe the solution you’d like
Coming from the TypeScript world, I'd expect the type of
xs
to evolve as youappend
to it:(TypeScript playground)
This construct could be quite helpful for typing Python code without annotations.
It looks like pyright already does this for values initialized to
None
:So this is a feature request to add a similar behavior to values initialized to
[]
/ empty list.The text was updated successfully, but these errors were encountered: