Skip to content

Final not honored when applied post-hoc #20144

Open

Description

@avylove

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

Activity

  1. sterliakov commented on Oct 30, 2025

    @sterliakov
    Collaborator

    I think SERIES_STD: Final = SERIES_STD should trigger a diagnostic [no-redef], this is no better than

    x = 0
    x: int = 1

    This must have something to do with us stripping Final early after setting the flag.

  2. avylove commented on Oct 30, 2025

    @avylove
    Author

    I think SERIES_STD: Final = SERIES_STD should trigger a diagnostic [no-redef]

    This is what I initially expected to happen. I don't love it, but it is what is specified in PEP 591

    The two main rules for defining a final name are:

    • There can be at most one final declaration per module or class for a given attribute. There can’t be separate class-level and instance-level constants with the same name.

    • There must be exactly one assignment to a final name

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

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