python / python/mypy

Warn if instance atribute is defined outside of __init__

Open
#10,552 3 comments 4 reactions 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

Feature

(Optionally?) generate error if the instance attribute is defined outside of __init__

Pitch

Mypy does not generate any errors for the code below:

class Tst:
    def __init__(self) -> None:
        ...

    def create_field(self) -> None:
        self.abc = 1  # Please, generate error here

    def print_field(self) -> None:
        print(self.abc)  # And, optionally here...


def main() -> None:
    tst = Tst()
    tst.print_field()


if __name__ == '__main__':
    main()

which fails with run time error, caused by the absence of the abc attribute definition in the __init__ method.

Additionaly:

PyCharm and pylint generate error in the line 6.

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

The issue names no implementation files, tests, or entry points. Start with the supplied Python example and review how mypy currently handles instance attributes; done means agreeing on a diagnostic for assignments outside init and whether reads such as print_field are included, then covering the requested behavior with tests.

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
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.