I want to create a polymorphic structure that can be created on the fly with minimum typing effort and be very readable. For example:
a.b = 1
a.c.d = 2
a.c.e = 3
a.f.g.a.b.c.d = cucu
a.aaa = bau
I do not want to create an intermediate container such as:
a.c = subobject()
a.c.d = 2
a.c.e = 3
My question is similar to this one:
But I am not happy with the solution there because I think there is a bug:
Items will be created even when you don't want: suppose you want to compare 2 polymorphic structures: it will create in the 2nd structure any attribute that exists in the first and is just checked in the other. e.g:
a = {1:2, 3: 4}
b = {5:6}
# now compare them:
if b[1] == a[1]
# whoops, we just created b[1] = {} !
I also want to get the simplest possible notation
a.b.c.d = 1
# neat
a[b][c][d] = 1
# yuck
I did try to derive from the object class... but I couldn't avoid to leave the same bug as above where attributes were born just by trying to read them: a simple dir() would try to create attributes like "methods"... like in this example, which is obviously broken:
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__
Thanks, really!
p.s.: the best solution I found so far is:
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}}}