最小限のタイピング作業でオンザフライで作成でき、非常に読みやすいポリモーフィック構造を作成したいと考えています。例えば:
a.b = 1
a.c.d = 2
a.c.e = 3
a.f.g.a.b.c.d = cucu
a.aaa = bau
次のような中間コンテナを作成したくありません。
a.c = subobject()
a.c.d = 2
a.c.e = 3
私の質問はこれに似ています:
しかし、バグがあると思うので、そこの解決策には満足していません:
アイテムは、必要のない場合でも作成されます:2つのポリモーフィック構造を比較したいとします:2番目の構造に、存在する属性が作成されます1 つはチェックインされ、もう 1 つはチェックインされます。例えば:
a = {1:2, 3: 4}
b = {5:6}
# now compare them:
if b[1] == a[1]
# whoops, we just created b[1] = {} !
また、可能な限り簡単な表記法を取得したい
a.b.c.d = 1
# neat
a[b][c][d] = 1
# yuck
私はオブジェクトクラスから派生しようとしました...しかし、それらを読み取ろうとするだけで属性が生まれた上記と同じバグを残すことは避けられませんでした:単純な dir() は「メソッド」のような属性を作成しようとします...この例のように、明らかに壊れています:
class KeyList(object):
def __setattr__(self, name, value):
print "__setattr__ Name:", name, "value:", value
object.__setattr__(self, name, value)
def __getattribute__(self, name):
print "__getattribute__ called for:", name
return object.__getattribute__(self, name)
def __getattr__(self, name):
print "__getattr__ Name:", name
try:
ret = object.__getattribute__(self, name)
except AttributeError:
print "__getattr__ not found, creating..."
object.__setattr__(self, name, KeyList())
ret = object.__getattribute__(self, name)
return ret
>>> cucu = KeyList()
>>> dir(cucu)
__getattribute__ called for: __dict__
__getattribute__ called for: __members__
__getattr__ Name: __members__
__getattr__ not found, creating...
__getattribute__ called for: __methods__
__getattr__ Name: __methods__
__getattr__ not found, creating...
__getattribute__ called for: __class__
ありがとう、本当に!
ps:これまでに見つけた最良の解決策は次のとおりです。
class KeyList(dict):
def keylset(self, path, value):
attr = self
path_elements = path.split('.')
for i in path_elements[:-1]:
try:
attr = attr[i]
except KeyError:
attr[i] = KeyList()
attr = attr[i]
attr[path_elements[-1]] = value
# test
>>> a = KeyList()
>>> a.keylset("a.b.d.e", "ferfr")
>>> a.keylset("a.b.d", {})
>>> a
{'a': {'b': {'d': {}}}}
# shallow copy
>>> b = copy.copy(a)
>>> b
{'a': {'b': {'d': {}}}}
>>> b.keylset("a.b.d", 3)
>>> b
{'a': {'b': {'d': 3}}}
>>> a
{'a': {'b': {'d': 3}}}
# complete copy
>>> a.keylset("a.b.d", 2)
>>> a
{'a': {'b': {'d': 2}}}
>>> b
{'a': {'b': {'d': 2}}}
>>> b = copy.deepcopy(a)
>>> b.keylset("a.b.d", 4)
>>> b
{'a': {'b': {'d': 4}}}
>>> a
{'a': {'b': {'d': 2}}}