Python における空オブジェクトを作成する方法
Published: 2022/11/6
Python で空オブジェクトを作成したくなる場合はたまにある。
ここで言う空オブジェクトとは、 None
ではなく、通常の attribute (__class__
などではない attribute) たちが何も指定されておらず、手動で attribute を代入していく、空の構造体インスタンスとして用いれるようなオブジェクト、を指す。
答え: types.SimpleNamespace()
Creating an empty object in Python
Are there any shortcuts for defining an empty object in Python or do you always have to create an instance of a custom empty class? Edit: I mean an empty object usable for duck typing.
stackoverflow.com

上記より、 types.SimpleNamespace
のクラスが利用できることが分かる。
抜粋して、
import types
x = types.SimpleNamespace()
x.happy = True
print(x.happy) # True
del x.happy
print(x.happy) # AttributeError. object has no attribute 'happy'
Tags: python
関連記事
Python で先頭の要素があれば取得し、なければ None を返す方法
2022/10/29