Skip to content

Consider making RUF009 work with custom dataclasses #4171

@NeilGirdhar

Description

@NeilGirdhar

Ruff produces useful errors for dataclasses. Recently, PEP 681 added the ability to define custom dataclasses. However, Ruff doesn't treat these as dataclasses and produces no errors:

from dataclasses import field
import dataclasses as dc
from collections.abc import Callable
from typing import Any, TypeVar

from typing_extensions import dataclass_transform

_T = TypeVar('_T')

def model_field(*,
                default: None | Any = ...,
                resolver: None | Callable[[], Any] = None,
                init: bool = True
                ) -> Any:
    return field(default=default, init=init)

@dataclass_transform(
    kw_only_default=True,
    field_specifiers=(model_field,))
def create_model(*,
                 init: bool = True,
                 ) -> Callable[[type[_T]], type[_T]]:
    return dc.dataclass(init=init)


def f(x: int) -> int:
    return x + 1


@create_model(init=False)
class CustomerModel:
    a: int = model_field(resolver=lambda: 0)  # Should be fine: model_field is a field specifier
    b: int = f(1)  # Should give RUF009


c = CustomerModel()

Metadata

Metadata

Assignees

No one assigned

    Labels

    acceptedReady for implementationruleImplementing or modifying a lint rule

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions