diff options
author | Nathan Binkert <nate@binkert.org> | 2008-10-10 10:15:00 -0700 |
---|---|---|
committer | Nathan Binkert <nate@binkert.org> | 2008-10-10 10:15:00 -0700 |
commit | 84364f36d0f763d3cef9847396fa4195184cb930 (patch) | |
tree | 050ec14f8a606b3e1e693109dd90c43531970a7f /src/python/m5/util | |
parent | 5586b1539baf6dd9029473a4ec1596a9fc8b7765 (diff) | |
download | gem5-84364f36d0f763d3cef9847396fa4195184cb930.tar.xz |
python: Add a utility for nested attribute dicts.
Change attrdict so that attributes that begin with an underscore don't
go into the dict.
Diffstat (limited to 'src/python/m5/util')
-rw-r--r-- | src/python/m5/util/attrdict.py | 25 |
1 files changed, 21 insertions, 4 deletions
diff --git a/src/python/m5/util/attrdict.py b/src/python/m5/util/attrdict.py index 44479c456..56f67217b 100644 --- a/src/python/m5/util/attrdict.py +++ b/src/python/m5/util/attrdict.py @@ -26,16 +26,17 @@ # # Authors: Nathan Binkert -__all__ = [ 'attrdict', 'optiondict' ] +__all__ = [ 'attrdict', 'multiattrdict', 'optiondict' ] class attrdict(dict): + """Wrap dict, so you can use attribute access to get/set elements""" def __getattr__(self, attr): if attr in self: return self.__getitem__(attr) return super(attrdict, self).__getattribute__(attr) def __setattr__(self, attr, value): - if attr in dir(self): + if attr in dir(self) or attr.startswith('_'): return super(attrdict, self).__setattr__(attr, value) return self.__setitem__(attr, value) @@ -44,13 +45,23 @@ class attrdict(dict): return self.__delitem__(attr) return super(attrdict, self).__delattr__(attr, value) +class multiattrdict(attrdict): + """Wrap attrdict so that nested attribute accesses automatically create + nested dictionaries.""" + def __getattr__(self, attr): + try: + return super(multiattrdict, self).__getattr__(attr) + except AttributeError: + d = optiondict() + setattr(self, attr, d) + return d + class optiondict(attrdict): + """Modify attrdict so that a missing attribute just returns None""" def __getattr__(self, attr): try: return super(optiondict, self).__getattr__(attr) except AttributeError: - #d = optionsdict() - #setattr(self, attr, d) return None if __name__ == '__main__': @@ -68,3 +79,9 @@ if __name__ == '__main__': del x.z print dir(x) print(x) + + x = multiattrdict() + x.y.z = 9 + print x + print x.y + print x.y.z |