ネストされた名前付きタプルを使用してデータ構造を作成しています (不変の関数型プログラミングのスキルを練習しています) が、ネストされた名前付きタプルの値を簡単に置き換える方法を見つけるのに苦労しています。
次のようなデータ構造があるとします。
from collections import namedtuple
Root = namedtuple("Root", "inventory history")
Inventory = namedtuple("Inventory", "item1 item2")
Item = namedtuple("Item", "name num")
Event = namedtuple("Event", "action item num")
r = Root(
inventory=Inventory(
item1=Item(name="item1", num=1),
item2=Item(name="item2", num=2)
),
history=(
Event(action="buy", item="item1", num=1),
Event(action="buy", item="item2", num=2)
)
)
# Updating nested namedtuples is very clunky
num_bought = 4
r_prime = r._replace(
history = r.history + (Event(action="buy", item="item2", num=num_bought),),
inventory = r.inventory._replace(
item2 = r.inventory.item2._replace(
num = r.inventory.item2.num + num_bought
)
)
)
# Contrast with the ease of using a version of this based on mutable classes:
r.history += Event(action="buy", item="item2", num=num_bought),
r.inventory.item2.num += num_bought
ご覧のとおり、a) 値がネストされているすべてのレイヤーを個別に更新する必要があり、b) のような演算子にアクセスできないため、インベントリ内のアイテムの値を変更するのは非常に面倒です+=
。
私が更新しているインベントリ内のアイテムが動的である場合、これはさらに醜くなりますgetattr
。
これを処理する簡単な方法はありますか?