-
Hello, I'm not sure if this is a bug since I am still not that familiar with Python's complicated typing system. However, I am seeing a strange (to me) behavior when trying to narrow tuple lengths and using variables inside of lambda functions.
Is it expected that these two reveal_type() calls don't match? For my purposes, I would like them to, so is there a way to tell Pyright that Here is a link to this example in the online version of Pyright. Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
This behavior is intended, so it's not a bug. When you define a lambda function, it captures the associated variable For more details, refer to the pyright documentation. A typical way to make this code type safe — and allow a type checker to verify its type safety, is to assign the narrowed value to another variable. Code sample in pyright playground from typing import reveal_type
def parse_float_tuple(str_input: str):
return tuple(float(k.strip()) for k in str_input[1:-1].split(","))
value = parse_float_tuple("(0,1,2)")
assert len(value) == 2
narrowed_value = value
reveal_type(narrowed_value) # tuple[float, float]
test = lambda a: reveal_type(narrowed_value) # tuple[float, ...] |
Beta Was this translation helpful? Give feedback.
-
Thanks again! I figured this was likely a quirk I didn't understand yet. |
Beta Was this translation helpful? Give feedback.
This behavior is intended, so it's not a bug.
When you define a lambda function, it captures the associated variable
value
. This variable can subsequently be modified in the outer context. For example, it could be reassigned a new value. By the time the lambda is executed, the value ofvalue
might be different from the value you checked with your assert. In general, it's unsafe for a type checker to assume that narrowed types will be retained for captured variables. There are certain cases where pyright can prove to itself that this is safe, but your code sample isn't one of them.For more details, refer to the pyright documentation.
A typical way to make this code type safe — and allow a…