Skip to content

Error on conditional initialization of Final class variables #10736

Description

@nelsyeung

Bug Report

Conditional initialization of a Final class variable is reported as a reassignment error on elif/else branches.

To Reproduce

tmp.py:

from typing import Final, Optional


class Foo:
    a: Final[Optional[int]]

    def __init__(self, v: int) -> None:
        if v == 0:
            self.a = None
        else:
            self.a = v  # error: Cannot assign to final attribute "a"  [misc]

Expected Behavior

No errors on the first correct assignment of a final variable regardless of branching.

Actual Behavior

$ mypy tmp.py
tmp.py:11: error: Cannot assign to final attribute "a"  [misc]
Found 1 error in 1 file (checked 1 source file)

Reported error: Cannot assign to final attribute "a" [misc] during the else clause, even though it's only the first assignment of the variable.

Your Environment

  • Mypy version used: 0.910

  • Mypy command-line flags: mypy tmp.py

  • Mypy configuration options from pyproject.toml (and other config files):

    [tool.mypy]
    show_error_codes = true
  • Python version used: 3.9.5

  • Operating system and version: macOS 11.4

Related

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-finalPEP 591

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions