[Python] How to 'pythonically' merging python data classes with unique attribute names

Discussão em 'Python' iniciado por Stack, Janeiro 23, 2025.

  1. Stack

    Stack Membro Participativo

    In python, the dataclasses module provides a slick interface for storing data.

    Suppose I have 2 classes, decorated with the @dataclass decorator, like

    from dataclasses import dataclass, field

    @dataclass
    class A:
    data_value1 : str = field(default='foo', metadata={'help': 'info about data_value2'})

    @dataclass
    class B:
    data_value2 : float = field(default=0,9, metadata={'help': 'info about data_value2'})
    def __post_init__(self):
    self.data_value2 += 10


    where I would like to perform the operation

    C = A + B


    resulting in C, a class which once instantiated, would behave like:

    @cdataclass
    class c:
    data_value1 : str = field(default='foo', metadata={'help': 'info about data_value2'})
    data_value2 : float = field(default=0,9, metadata={'help': 'info about data_value2'})
    def __post_init__(self):
    self.data_value2 += 10


    I can see why the addition operation may not have been defined for the type but I thought as long as there were not overlapping attribute names it should be possible. Unless some how there are conflicting operations across different methods of the classes, like conflicts that could occur in __post_init__ functions.

    Does anyone know a pythonic way to achieve this goal? I can think of ways, but they would be very convoluted.

    Thank you for your help and time to read this question.

    I have tried directly adding them together, but the addition operation was not defined for the type. Would the easiest thing to do be to defined the addition operation myself? But I wouldn't be too familiar with how to do so on the class decorator. Could anyone help?

    Continue reading...

Compartilhe esta Página