Skip to content

bug: A dataclass field with init=False should not be a parameter #233

@has2k1

Description

@has2k1

Here are failing tests.

from griffe.tests import temporary_visited_module

code = """
from dataclasses import dataclass, field

@dataclass
class PointA:
    x: float
    y: float
    z: float = field(init=False)

@dataclass(init=False)
class PointB:
    x: float
    y: float

@dataclass(init=False)
class PointC:
    x: float
    y: float = field(init=True)  # init=True has no effect
"""

with temporary_visited_module(code) as module:
    paramsA = module["PointA"].parameters
    paramsB = module["PointB"].parameters
    paramsC = module["PointC"].parameters

    assert "z" not in paramsA
    assert "x" not in paramsB and "y" not in paramsB
    assert "x" not in paramsC and "y" not in paramsC

Then there are the perhaps more complicated cases to deal with statically where the field class is wrapped inside another function e.g.

def no_init(default: T) -> T:
    """
    Set default value of a dataclass field that will not be __init__ed
    """
    return field(init=False, default=default)

@dataclass
class Point:
    x: float
    y: float = no_init(0)  # y is not a parameter

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions