python / python/mypy

Allow redefinition of class attribute as an instance attribute in a child class

Open
#10,721 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Feature

It is a common design pattern in Python to define a class attribute which functions as a default instance method and can be "overwritten" by instances. For example, in cmd.Cmd

class Cmd:
    prompt = '> '
    ...

If a user were to define a subclass thus

class MyCmd(cmd.Cmd):
    @property
    def prompt(self):
        if self.some_condition():
            return '$ '
        else:
            return '> '

    @prompt.setter
    def prompt(self, value: str) -> None:
        raise NotImplementedError
    ...

mypy would complains,

error: Signature of "prompt" incompatible with supertype "Cmd"

Pitch

Short of changing the superclass (which, in this case, would mean changing the standard library), is there a way that mypy could recognize the above example as a proper child of the parent class?

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

No files, tests, or implementation entry points are named. Start by reproducing the reported mypy error with the Cmd and MyCmd examples, then locate the superclass compatibility check involved. Done means mypy accepts the child property while preserving the intended type-checking behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
20/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.