Skip to content

Commit

Permalink
Merge pull request #35 from takluyver/fix-cross-validation
Browse files Browse the repository at this point in the history
Set trait values from static defaults at instance_init
  • Loading branch information
minrk committed Jun 15, 2015
2 parents 1e89907 + aa4c11b commit b3988bc
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 6 deletions.
3 changes: 2 additions & 1 deletion traitlets/tests/test_traitlets.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ def test_get_undefined(self):
class A(HasTraits):
a = TraitType
a = A()
self.assertEqual(a.a, Undefined)
with self.assertRaises(TraitError):
a.a

def test_set(self):
class A(HasTraitsStub):
Expand Down
12 changes: 7 additions & 5 deletions traitlets/traitlets.py
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,9 @@ def instance_init(self, obj):
# use provides a static default, transfer that to obj._trait_values.
if (self._dynamic_default_callable(obj) is None) \
and (self.default_value is not Undefined):
self.validate_default_value(obj)
v = self.validate_default_value(obj)
if self.name is not None:
obj._trait_values[self.name] = v

def __get__(self, obj, cls=None):
"""Get the value of the trait by self.name for the instance.
Expand All @@ -432,10 +434,10 @@ def __get__(self, obj, cls=None):
except KeyError:
# Check for a dynamic initializer.
dynamic_default = self._dynamic_default_callable(obj)
if dynamic_default is not None:
value = self._validate(obj, dynamic_default())
else:
value = self.validate_default_value(obj)
if dynamic_default is None:
raise TraitError("No default value found for %s trait of %r"
% (self.name, obj))
value = self._validate(obj, dynamic_default())
obj._trait_values[self.name] = value
return value
except Exception:
Expand Down

0 comments on commit b3988bc

Please sign in to comment.