python / python/mypy

Error on conditional initialization of Final class variables

Open
#10,736 5 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-final
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the reported mypy tmp.py example with the Final attribute and conditional branches. Trace how the type checker handles the first assignment across the if and else paths; done means the command reports no reassignment error for this example and the behavior is covered by a regression test.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.