[Python] Why can't dataclasses have mutable defaults in their class attributes declaration?

Discussão em 'Python' iniciado por Stack, Agosto 8, 2025.

  1. Stack

    Stack Membro Participativo

    This is similar to Passing default list argument to dataclasses, but it's not quite what I'm looking for.

    Here's the problem: when one tries to assign a mutable value to a class attribute, there's an error:

    from dataclasses import dataclass

    @dataclass
    class Foo:
    bar: list = []

    # ValueError: mutable default <class 'list'> for field a is not allowed: use default_factory


    I gathered from the error message that I'm supposed to use the following instead:

    from dataclasses import dataclass, field

    @dataclass
    class Foo:
    bar: list = field(default_factory=list)


    But why are mutable defaults not allowed? Is it to enforce avoidance of the mutable default argument problem?

    Continue reading...

Compartilhe esta Página