Skip to content

New check: suggest dataclass when __init__ only assigns instance variables #8008

Open
@nickdrozd

Description

@nickdrozd

Current problem

It's very common to have __init__ methods that only assign instance variables:

class Thing:
    def __init__(self, this, that, the_third):
        self.this = this
        self.that = that
        self.the_third = the_third

Desired solution

It would be less verbose to declare such a class as a dataclass:

from dataclasses import dataclass

@dataclass
class Thing:
    this: int
    that: str
    the_third: str

This way, the instance variables are declared only once, rather than twice (field and argument). Additionally, the dataclass version requires type annotations, which are generally a good thing.

A new check could be added that detects __init__ methods that only assign instance variables and suggests using a dataclass instead. IMO this would be in keeping with existing Pylint checks that suggest using higher-level language features (for example, suggesting enumerate).

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs decision 🔒Needs a decision before implemention or rejectionNeeds specification 🔐Accepted as a potential improvement, and needs to specify edge cases, message names, etc.dataclasses

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions