python / python/mypy

Final not honored when applied post-hoc

Open
#20,144 2 comments 0 reactions 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

The behavior of Final is a bit inconsistent. It can be applied post-hoc, but then it won't be honored.

To Reproduce

import platform
import sys

from typing import Final

SERIES_STD = ' ▌█' if platform.system() == 'Windows' else ' ▏▎▍▌▋▊▉█'
if sys.__stdout__ and sys.__stdout__.encoding:
    try:
        SERIES_STD.encode(sys.__stdout__.encoding)
    except UnicodeEncodeError:
        SERIES_STD = ' |'

SERIES_STD: Final = SERIES_STD
SERIES_STD = '| '

Expected Behavior

I expect an assignment error for the final line to raise an error.

error: Cannot assign to final name "SERIES_STD"  [misc]

Some people might argue applying Final post-hoc itself should raise an error, but I'm not one of them.

Actual Behavior

Success: no issues found in 1 source file

Your Environment

  • Mypy version used: 1.18.2
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): No Config
  • Python version used: 3.13.9

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 supplied reproducer with mypy 1.18.2 and trace how post-hoc Final annotations are handled. Identify the relevant type-checking path, add coverage for this example, and confirm that the reassignment reports "Cannot assign to final name" while other Final behavior remains unchanged.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
52/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.