LoginSignup
2
4

More than 3 years have passed since last update.

型に厳密なdataclass

Last updated at Posted at 2019-09-27

シンプルなdataclasses.dataclassはアトリビュートの型が定義と異なってもインスタンス化が可能。つまり以下のような例が実行可能。

@dataclasses.dataclass
class NormalDataclass:
    foo: int

NormalDataclass(foo=1.1)  # ok

厳密に型をチェックしたい場合は__post_init__を定義すれば良い。__init__の後に呼ばれるのでここで型チェックをしてみよう。

@dataclasses.dataclass
class StrictDataclass:
    def __post_init__(self):
        for key, val in self.__dataclass_fields__.items():
            member = getattr(self, key)
            assert isinstance(member, val.type), f"Invalid Type of member: {type(member)} != {val.type}"

    foo: int


StrictDataclass(foo=1)  # ok
StrictDataclass(foo=1.2)  # AsertionError: Invalid Type of member: <class 'float'> != <class 'int'>

不正な値が入ってきた場合にいち早くassertionを投げてくれるのでデバックがしやすくなるかもしれない。

2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4