stubtest: check Final variables with literal values against runtime#20858
stubtest: check Final variables with literal values against runtime#20858Vikash-Kumar-23 wants to merge 5 commits intopython:masterfrom
Conversation
mypy/stubtest.py
Outdated
| yield Error(object_path, "is not present at runtime", stub, runtime) | ||
| return | ||
|
|
||
| if stub.final_value is not None and stub.final_value != runtime: |
There was a problem hiding this comment.
Maybe move this to an elif branch of the subtype check below? That way we don't get duplicate errors when the types are different.
mypy/stubtest.py
Outdated
| if stub.final_value is not None and stub.final_value != runtime: | ||
| yield Error( | ||
| object_path, | ||
| f"is inconsistent, stub value {stub.final_value!r} differs from runtime value {runtime!r}", |
There was a problem hiding this comment.
The runtime object could potentially have a very long repr, which we wouldn't want included in the error message. It's also already rendered in the output (with length truncation), so including in the message isn't necessary.
mypy/test/teststubtest.py
Outdated
| yield Case( | ||
| stub=""" | ||
| from typing import Final | ||
| x_final: Final = 2 |
There was a problem hiding this comment.
style nit: maybe use CAPS_CASE, like the other cases with Final variables?
Co-authored-by: Brian Schubert <brianm.schubert@gmail.com>
|
"Hi @brianschubert, thank you for the feedback! I have applied the suggested refinements to the PR: Logic Refactor: Moved the Final value check into an elif branch of the subtype check to prevent duplicate error reporting. Error Message: Cleaned up the error string by removing {runtime!r} value as suggested. Consistency: Updated the new test cases to use CAPS_CASE for constants to match the project's style. Verification: Verified the fix locally
|
for more information, see https://pre-commit.ci

Description
Currently, stubtest does not detect discrepancies when a stub uses Final = but the runtime has a different value. While it correctly handles Literal[...] mismatches, it was previously silent on Final assignments.
This PR extends the variable verification logic in stubtest to ensure assigned Final values in stubs are compared against the actual runtime value.
Changes
mypy/stubtest.py: Added logic in verify_var to compare stub.final_value with the runtime object if a concrete value is assigned in the stub.
mypy/test/teststubtest.py: Added regression test cases to test_var covering both matching and mismatched Final values.
Verification
Verified the fix using a minimal reproduction case:
Stub: FOO: Final = 2
Runtime: FOO = 1
Result: error: repro.FOO is inconsistent, stub value 2 differs from runtime value 1
Evidence:

Note on Environment:
Full stubtest suite was verified (63/63 passed) prior to recent upstream changes affecting the local environment.
Fixes #20857