[Python] how to gracefully ignore non-matching keyword matching arguments in python dataclass

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

  1. Stack

    Stack Membro Participativo

    With normal classes you have **kwargs in the __init__ so non-matching keyword arguments can be ignored:

    class MyClass:
    def __init__(self, a, **kwargs):
    self.a=a

    my_class = MyClass(20, **{"kwarg1" : 1})


    Is there an equivalent for @dataclass that can gracefully ignore non-matching keyword arguments without having to include an __init__?

    from dataclasses import dataclass

    @dataclass
    class MyClass:
    a: int

    my_class = MyClass(20, **{"kwarg1" : 1}) # TypeError: MyClass.__init__() got an unexpected keyword argument 'kwarg1'

    Continue reading...

Compartilhe esta Página