Skip to content

Commit

Permalink
passthrough unused args to super.__init__
Browse files Browse the repository at this point in the history
only those not consumed by trait value-setting

for better inheritance
  • Loading branch information
minrk committed Feb 17, 2016
1 parent 1d31bd7 commit efd9958
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
18 changes: 17 additions & 1 deletion traitlets/tests/test_traitlets.py
Original file line number Diff line number Diff line change
Expand Up @@ -1025,7 +1025,7 @@ class Tree(HasTraits):

tree = Tree(
value='foo',
leaves=[Tree('bar'), Tree('buzz')]
leaves=[Tree(value='bar'), Tree(value='buzz')]
)

with self.assertRaises(TraitError):
Expand Down Expand Up @@ -2163,3 +2163,19 @@ def test_subclass_add_observer():
obj.trait = 5
nt.assert_true(obj.child_called)
nt.assert_true(obj.parent_called)

def test_super_args():
class SuperRecorder(object):
def __init__(self, *args, **kwargs):
self.super_args = args
self.super_kwargs = kwargs

class SuperHasTraits(HasTraits, SuperRecorder):
i = Integer()

obj = SuperHasTraits('a1', 'a2', b=10, i=5, c='x')
nt.assert_equal(obj.i, 5)
assert not hasattr(obj, 'b')
assert not hasattr(obj, 'c')
nt.assert_equal(obj.super_args, ('a1', 'a2'))
nt.assert_equal(obj.super_kwargs, {'b': 10, 'c': 'x'})
10 changes: 8 additions & 2 deletions traitlets/traitlets.py
Original file line number Diff line number Diff line change
Expand Up @@ -940,10 +940,16 @@ def __init__(self, *args, **kwargs):
# Allow trait values to be set using keyword arguments.
# We need to use setattr for this to trigger validation and
# notifications.
super_args = args
super_kwargs = {}
with self.hold_trait_notifications():
for key, value in iteritems(kwargs):
setattr(self, key, value)
super(HasTraits, self).__init__()
if self.has_trait(key):
setattr(self, key, value)
else:
# passthrough args that don't set traits to super
super_kwargs[key] = value
super(HasTraits, self).__init__(*super_args, **super_kwargs)

def __getstate__(self):
d = self.__dict__.copy()
Expand Down

0 comments on commit efd9958

Please sign in to comment.