[Python] Python frozen dataclass, allow changing of attribute via method

Discussão em 'Python' iniciado por Stack, Fevereiro 25, 2025.

  1. Stack

    Stack Membro Participativo

    Suppose I have a dataclass:

    @dataclass(frozen=True)
    class Foo:
    id: str
    name: str


    I want this to be immutable (hence the frozen=True), such that foo.id = bar and foo.name = baz fail. But, I want to be able to strip the id, like so:

    foo = Foo(id=10, name="spam")

    foo.strip_id()
    foo
    -> Foo(id=None, name="spam")


    I have tried a few things, overriding setattr, but nothing worked. Is there an elegant solution to this? (I know I could write a method that returns a new frozen instance that is identical except that that id has been stripped, but that seems a bit hacky, and it would require me to do foo = foo.strip_id(), since foo.strip_id() would not actually change foo)

    Edit:

    Although some commenters seem to disagree, I think there is a legitimate distinction between 'fully mutable, do what you want with it', and 'immutable, except in this particular, tightly controlled way'

    Continue reading...

Compartilhe esta Página