Replies: 1 comment 2 replies
-
Pyright is working as designed here, so I don't consider this a bug. In general, a type checker cannot determine the number of times that an iterable will return a value. In this very specific example, it is possible to determine this statically, but making this specific case work would be difficult and costly from a type analysis performance standpoint. Pyright's "unbound variable" detection logic is based on a code flow graph, which is necessarily built prior to any type analysis — long before it can analyze the type of the iterable in the I think there's a way I could make this work, but it would add complexity and overhead that would be justified only if this were sufficiently important to enough pyright users. Since you're the first person (as far as I remember) to request this support, I don't think it's justified at this time. We can leave this discussion topic open to see if it gets additional upvotes (in the form of thumbs-up reactions). If the signal is sufficiently strong, I might consider adding the feature. In general, I recommend against using loop iteration variables outside of a loop. Most modern programming languages forbid this — and for good reason. Python's lax variable scoping rules don't prevent this, but that doesn't mean that it's a good programming practice. |
Beta Was this translation helpful? Give feedback.
-
Lest is misclassify my issue, I figured I start a discussion first. Consider this minimal snippet representing more complicated code:
When I put on my type checker hat, I determine that the tuple literal ensures at least one loop iteration and hence
I
is initialized. I also determine that the loop variable iterates over atuple[int,...]
and hence its type is compatible with the function's return type. Yay!However, pyright claims the
I
is "possibly unbound." I don't think I'm missing something (especially after reducing the real code to the above snippet). That's disappointing because any alternative that might satisfy the type checker, i.e., an explicit declaration before the loop as suggested in similar cases before, adds a line and then I have to deal withNone
as well, which all seems a bit excessive.So, bug or feature request? 😇
Beta Was this translation helpful? Give feedback.
All reactions