python / python/mypy

Allow setting a final instance attribute in `__set_name__`?

Open
#15,772 5 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

feature
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Currently, Mypy reports the following problems:

from typing import Any, Final, Type

class D:
    name: Final[str]  # error: Final name must be initialized with a value  [misc]

    def __set_name__(self, owner: Type[Any], name: str) -> None:
        self.name = name  # error: Cannot assign to final attribute "name"  [misc]

I know PEP 591 does not mention __set_name__, but I think it could be helpful if Mypy would handle it like __init__ regarding the one-time initialisation of instance attributes.

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 reproducing the Python example from the issue and compare it with Mypy’s existing handling of Final instance attributes in init. Investigate where Final assignment rules and set_name behavior are analyzed. Done means the proposed one-time initialization behavior is implemented with regression coverage and the example no longer reports either error.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.