Skip to content

Commit

Permalink
Added _inherit_fields option to structs to inherit Fields from base c…
Browse files Browse the repository at this point in the history
…lasses.
  • Loading branch information
brandjon committed Sep 25, 2014
1 parent 8fd3d55 commit 74567fd
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
6 changes: 6 additions & 0 deletions simplestruct/struct.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,12 @@ def __prepare__(mcls, name, bases, **kargs):
# Construct the _struct attribute on the new class.
def __new__(mcls, clsname, bases, namespace, **kargs):
fields = []
# If inheriting, gather fields from base classes.
if namespace.get('_inherit_fields', False):
for b in bases:
if isinstance(b, MetaStruct):
fields += b._struct
# Gather fields from this class's namespace.
for fname, f in namespace.copy().items():
if not isinstance(f, Field):
continue
Expand Down
11 changes: 11 additions & 0 deletions simplestruct/test_struct.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,17 @@ def testPickleability(self):

f3 = copy.deepcopy(f1)
self.assertEqual(f3, f1)

def testInheritFields(self):
class Foo(Struct):
a = Field()
class Bar(Foo):
_inherit_fields = True
b = Field()

bar = Bar(1, 2)
self.assertEqual(bar.a, 1)
self.assertEqual(bar.b, 2)


if __name__ == '__main__':
Expand Down

0 comments on commit 74567fd

Please sign in to comment.