Skip to content

Add support for PEP 681: dataclass_transform #7437

Open
@mjhaye

Description

@mjhaye

Bug description

When building my own dataclass decorator based on the stdlib dataclass, the type of the fields initialized via a field call is inferred incorrectly. This triggers errors every time the field is accessed (and thus this cannot be silenced locally).

# pylint: disable=missing-docstring,unnecessary-lambda,too-few-public-methods
from dataclasses import dataclass, field

def mydataclass(cls):
    cls.myfun = lambda self: print(self)
    return dataclass(cls)

@mydataclass
class TestDC:
    a_dict: dict[int, int] = field(default_factory=dict)

dc = TestDC()
dc.a_dict[0] = 0

I did some research in the issues here and at astroid and it appears to be related to the difficulty to determine if an object, TestDC in this case, is a dataclass. It seems to me, as a laymen, that in brains_dataclasses.py it is more or less hard-coded if something is a dataclass (stdlib, pydantic, and marshmallow_dataclass are supported).

A suggestion: Stdlib provides the is_dataclass() function that checks for a __dataclass_fields__ attribute. Maybe this could be a "generic" way of checking if a class is a dataclass. It would work for stdlib, pydantic and marshmallow_dataclass, but also on all homebrew dataclass adoptations that are derived from that.

Configuration

No response

Command used

pylint dataclass_pylint.py

Pylint output

************* Module dataclass_pylint
dataclass_pylint.py:13:0: E1137: 'dc.a_dict' does not support item assignment (unsupported-assignment-operation)

Expected behavior

No error.

Pylint version

pylint 2.15.2
astroid 2.12.9
Python 3.10.7 (tags/v3.10.7:6cc6b13, Sep  5 2022, 14:08:36) [MSC v.1933 64 bit (AMD64)]

OS / Environment

W10

Additional dependencies

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    AstroidRelated to astroidHelp wanted 🙏Outside help would be appreciated, good for new contributorsNeeds astroid updateNeeds an astroid update (probably a release too) before being mergabledataclasses

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions