Class inheritance in Python 3.7 dataclasses

前端 未结 8 767
离开以前
离开以前 2020-11-28 22:12

I\'m currently trying my hands on the new dataclass constructions introduced in Python 3.7. I am currently stuck on trying to do some inheritance of a parent class. It looks

8条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 22:36

    based on Martijn Pieters solution I did the following:

    1) Create a mixing implementing the post_init

    from dataclasses import dataclass
    
    no_default = object()
    
    
    @dataclass
    class NoDefaultAttributesPostInitMixin:
    
        def __post_init__(self):
            for key, value in self.__dict__.items():
                if value is no_default:
                    raise TypeError(
                        f"__init__ missing 1 required argument: '{key}'"
                    )
    

    2) Then in the classes with the inheritance problem:

    from src.utils import no_default, NoDefaultAttributesChild
    
    @dataclass
    class MyDataclass(DataclassWithDefaults, NoDefaultAttributesPostInitMixin):
        attr1: str = no_default
    

    EDIT:

    After a time I also find problems with this solution with mypy, the following code fix the issue.

    from dataclasses import dataclass
    from typing import TypeVar, Generic, Union
    
    T = TypeVar("T")
    
    
    class NoDefault(Generic[T]):
        ...
    
    
    NoDefaultVar = Union[NoDefault[T], T]
    no_default: NoDefault = NoDefault()
    
    
    @dataclass
    class NoDefaultAttributesPostInitMixin:
        def __post_init__(self):
            for key, value in self.__dict__.items():
                if value is NoDefault:
                    raise TypeError(f"__init__ missing 1 required argument: '{key}'")
    
    
    @dataclass
    class Parent(NoDefaultAttributesPostInitMixin):
        a: str = ""
    
    @dataclass
    class Child(Foo):
        b: NoDefaultVar[str] = no_default
    

提交回复
热议问题