Skip to content

Trigger violation on mutable values and function calls for non-dataclass attribute defaults #4053

@adampauls

Description

@adampauls

This is a feature request. I see in this PR that there is some recent work in flagging mutable and function call defaults for dataclass attributes. Is there a plan to enable this check for non-dataclass attributes as well? Right now, no Python tooling I know of catches this bug:

import dataclasses

class NonDataClass:
    my_list: list[int] = dataclasses.field(default_factory=list)  # oops! type checks but is nonsense

    def add_item(self, item: int) -> None:
        self.my_list.append(item)

instance = NonDataClass()
instance.add_item(1)
assert instance.my_list == [1]

The problem is that dataclass.field lies about its type.

It would be great if we could check for mutable and function call defaults in class attributes because they are just problematic for non-dataclasses as they are for dataclasses. The only difference from the existing implementation would need to be that dataclasses.field should only be exempted when used inside a dataclass.

I can look into this if the work is not already planned since I think it's a simple change from what's already been done.

Thanks for the great tool!

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionAsking for support or clarification

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions