[TriPython] Nested Properties

David Johnson znoop333 at hotmail.com
Tue Sep 29 11:23:48 EDT 2020


If you want a dict-based implementation, you don't have to define a new class just to change the behavior of __getattr__. You can use SimpleNamespace and put anything you want into it with as much nesting as you care to write out:

from types import SimpleNamespace
aa=SimpleNamespace()
aa.a=-543.
aa.bb=SimpleNamespace()
aa.bb.foo='bar'
aa.bb.cc=SimpleNamespace()
aa.bb.cc.dd=lambda x: x+1

print(aa)

namespace(a=-543.0, bb=namespace(cc=namespace(dd=<function...>), foo='bar'))


(I prefer the protobuf approach because it's more structured and interoperable, but SimpleNamespace works fine for internal data structures which will never be seen by other programs. I like SimpleNamespace better than namedtuple because namedtuple is immutable, but that makes it possible to use a namedtuple as a dict key, FWIW.)


-------------- next part --------------
   If you want a dict-based implementation, you don't have to define a new
   class just to change the behavior of __getattr__. You can use
   SimpleNamespace and put anything you want into it with as much nesting as
   you care to write out:
   from types import SimpleNamespace
   aa=SimpleNamespace()
   aa.a=-543.
   aa.bb=SimpleNamespace()
   aa.bb.foo='bar'
   aa.bb.cc=SimpleNamespace()
   aa.bb.cc.dd=lambda x: x+1
   print(aa)
   namespace(a=-543.0, bb=namespace(cc=namespace(dd=<function...>),
   foo='bar'))
   (I prefer the protobuf approach because it's more structured and
   interoperable, but SimpleNamespace works fine for internal data structures
   which will never be seen by other programs. I like SimpleNamespace better
   than namedtuple because namedtuple is immutable, but that makes it
   possible to use a namedtuple as a dict key, FWIW.)


More information about the TriZPUG mailing list