Skip to content

Resolve module-level Final to the literal value of its initializer - #22428

Closed
trim21 wants to merge 4 commits into
python:masterfrom
trim21:final-module-literal
Closed

trim21 wants to merge 4 commits into
python:masterfrom
trim21:final-module-literal

Conversation

@trim21

@trim21 trim21 commented Nov 10, 2026

Copy link
Copy Markdown

Fixes #22427.

A module-level Final cannot be rebound, so the value of its initializer is the value of every read of the variable. mypy already inferred the literal when the annotation was omitted; with an explicit annotation the declared type won, so the value was lost as soon as the variable was read from another module, where there is no code flow information to narrow it.

# flags.py
IS_WIN: Final[bool] = sys.platform == "win32"

# main.py
from flags import IS_WIN

reveal_type(IS_WIN)  # was "bool", now "Literal[False]?"

Behavior

The value is recorded in Instance.last_known_value when a module-level Final declaration is checked — the same mechanism a bare Final = 1 already used:

declaration resolved type
IS_WIN: Final[bool] = sys.platform == "win32" Literal[False]?
NUM: Final[int] = 1 Literal[1]?
NAME: Final[str] = "hi" Literal['hi']?
COLOR: Final[Color] = Color.RED Literal[Color.RED]?
MAYBE_WIN: bool = sys.platform == "win32" bool
NO_INFO: Final[Base] = Sentinel() Base
ITEMS: Final[list[int]] = [] list[int]
ClassWithFinal.class_final: Final[int] = 1 int

Only literal values (int/str/bool/enum member) are exposed. Widening any other inferred type would leak a subclass into everything inferred from such a read, which is why a Final annotated with a supertype keeps it. Class-body, instance and function-local Finals keep the declared type, since a constructor can still assign them.

A Final[bool] initialized from a static platform or version check is folded with infer_condition_value(), restricted to ALWAYS_TRUE/ALWAYS_FALSE: TYPE_CHECKING and friends are true for mypy but false at runtime, so those stay bool.

Branches guarded by such a variable are still analyzed — if FLAG: with FLAG: Final = False is not pruned. That is #14604 and is not addressed here.

Notable consequences

  • ==/!= start propagating the constant, because narrow_type_by_identity_equality coerces the target through coerce_to_literal(): x: Literal["hi", "bye"]; if x == NAME: now narrows to Literal['hi'].
  • Format string checks now see the value of a module-level Final, so '{:c}'.format(FINAL_STR) is an error when the value is not a single character.

Tests

  • New cases in check-final.test: module-level literals, cross-module reads, non-literal initializers, non-module scopes, statically known bool initializers.
  • testLiteralFinalDirectInstanceTypesSupersedeInferredLiteral and testLiteralFineGrainedChainedViaFinal updated: their "declared type wins" expectations no longer hold for module-level variables.
  • Full testcheck.py and testfinegrained.py pass (9117 passed), mypy_self_check.ini clean, black and ruff clean.

@github-actions

This comment has been minimized.

@trim21

trim21 commented Nov 10, 2026 •

Copy link
Copy Markdown
Author

The mypy_primer diff is expected: the new cwltool errors are real errors in cwltool that this change unmasks, not a regression from the implementation.

The downstream code is cwltool/mutation.py:

_generation: Final[str] = "http://commonwl.org/cwltool#generation"


def set_generation(self, obj: CWLFileType) -> None:
    """Register a File for mutation tracking."""
    loc = obj["location"]
    current = self.generations.get(loc, _MutationState(0, [], ""))
    obj[_generation] = current.generation  # type: ignore[literal-required]


def unset_generation(self, obj: CWLFileType) -> None:
    """Remove the mutation tracking metadata from a File."""
    obj.pop(_generation, None)  # type: ignore[misc]

CWLFileType is a TypedDict from cwl_utils.types (generated by schema-salad) that does not declare http://commonwl.org/cwltool#generation.

Before this PR the type of _generation was plain str, so the key was not a literal and the only diagnostic mypy could emit was literal-required ("TypedDict key must be a string literal"), which the two existing type: ignore comments silenced — the key itself was never checked. With the literal exposed, the check actually runs: typeddict-unknown-key for the assignment, typeddict-item for .pop, and both ignores become unused. A minimal repro reproduces the primer output exactly:

from typing import Final, TypedDict

_generation: Final[str] = "http://commonwl.org/cwltool#generation"


class CWLFileType(TypedDict):
    location: str


def set_generation(obj: CWLFileType) -> None:
    obj[_generation] = 1  # type: ignore[literal-required]


def unset_generation(obj: CWLFileType) -> None:
    obj.pop(_generation, None)  # type: ignore[misc]
$ mypy --warn-unused-ignores t.py
t.py:12: error: Unused "type: ignore" comment  [unused-ignore]
t.py:12: error: TypedDict "CWLFileType" has no key "http://commonwl.org/cwltool#generation"  [typeddict-unknown-key]
t.py:12: note: Error code "typeddict-unknown-key" not covered by "type: ignore[literal-required]" comment
t.py:15: error: Unused "type: ignore" comment  [unused-ignore]
t.py:15: error: TypedDict "CWLFileType" has no key "http://commonwl.org/cwltool#generation"  [typeddict-item]
t.py:15: note: Error code "typeddict-item" not covered by "type: ignore[misc]" comment

So these are expected new errors: the code writes and pops a key that its TypedDict never declares, and mypy could not see it while the key expression was not a literal. No implementation change is planned; cwltool would need to declare the extension key (or cast) and update the ignores. The pywin32 entry is only the dev version string.

@github-actions

Copy link
Copy Markdown
Contributor

Diff from mypy_primer, showing the effect of this PR on open source code:

cwltool (https://github.com/common-workflow-language/cwltool)
+ cwltool/mutation.py:92: error: Unused "type: ignore" comment  [unused-ignore]
+ cwltool/mutation.py: note: In member "set_generation" of class "MutationManager":
+ cwltool/mutation.py:92:13: error: TypedDict "CWLFileType" has no key "http://commonwl.org/cwltool#generation"  [typeddict-unknown-key]
+ cwltool/mutation.py:92:13: note: Error code "typeddict-unknown-key" not covered by "type: ignore[literal-required]" comment
+ cwltool/mutation.py: note: At top level:
+ cwltool/mutation.py:96: error: Unused "type: ignore" comment  [unused-ignore]
+ cwltool/mutation.py: note: In member "unset_generation" of class "MutationManager":
+ cwltool/mutation.py:96:17: error: TypedDict "CWLFileType" has no key "http://commonwl.org/cwltool#generation"  [typeddict-item]
+ cwltool/mutation.py:96:17: note: Error code "typeddict-item" not covered by "type: ignore[misc]" comment

pywin32 (https://github.com/mhammond/pywin32)
  ./pythonwin/pywin/test/_dbgscript.py: error: INTERNAL ERROR -- Please try using mypy master on GitHub:
- version: 2.5.0+dev.b83696ea8099ef3772a5a2bc2c49f2b05340c37a
+ version: 2.5.0+dev.35851a1ca3746ed15c55224f00ee7d3462be1237

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature request: Resolve module-level Final to the literal value of its initializer

1 participant