google / pytype

A static type analyzer for Python code
https://google.github.io/pytype
Other
4.78k stars 281 forks source link

Fix type guards propagating invisibile bindings #1782

Closed copybara-service[bot] closed 1 month ago

copybara-service[bot] commented 2 months ago

Fix type guards propagating invisibile bindings

The test case test_only_use_visible_bindings added in this change fails with the following error before the fix:

dummy_input_file:7:9: error: in <module>: Name 'value' is not defined [name-error]

  Variable value has been used after it has been deleted (line 4).

  print(value)
        ~~~~~

This happens because the "Deleted" binding, which is not visible anymore after the value = 2 assignment, is made visible again by the type guard.

The fix: rather than operating on all bindings and making them visible, we now only operate on visible bindings.

While testing my changes I broke existing code in 2 different ways and added new test cases for these. The tests test_dont_hide_previous_bindings and test_type_guard_matches_input_type pass before this change and still pass after it.