[Python] How to use python descriptors with default_factory in dataclass

Discussão em 'Python' iniciado por Stack, Abril 6, 2025.

  1. Stack

    Stack Membro Participativo

    How can I make descriptors work with dataclass and default_factory? In the following example:

    from dataclasses import dataclass, field
    import numpy as np

    class A():
    a = np.arange(2)

    class Verbose_attribute(A):
    def __get__(self, obj, type=None) -> object:
    print("accessing the attribute to get the value")
    return self.a[-1]
    def __set__(self, obj, value) -> None:
    print("accessing the attribute to set the value")
    self.a[-1]=value

    #a = np.arange(2)

    @dataclass
    class Foo():
    attribute1: Verbose_attribute = Verbose_attribute()
    #attribute1: Verbose_attribute = field(default_factory=lambda: Verbose_attribute())

    my_foo_object = Foo()
    print(my_foo_object.attribute1)
    my_foo_object.attribute1 = 3
    print(my_foo_object.attribute1)


    the first print works properly, displaying the default value 1. If one comments the first version of attribute1 in Foo(), and uncomments the second, the first print gives object instead of the attribute value.

    Using default_factory is important for me, since in the real case I am creating a descriptor for a class that inherits from MutableSequence.

    Continue reading...

Compartilhe esta Página