From e25b123ca2befee44932c66b3a2d12a99413c283 2014-08-20 19:22:26 From: Brian E. Granger Date: 2014-08-20 19:22:26 Subject: [PATCH] Merge pull request #6331 from jasongrout/traitlet-metadata-default Add an optional `default` argument to trait metadata get, like the Python dict's .get() default argument --- diff --git a/IPython/utils/tests/test_traitlets.py b/IPython/utils/tests/test_traitlets.py index fcb3ca2..9251ae8 100644 --- a/IPython/utils/tests/test_traitlets.py +++ b/IPython/utils/tests/test_traitlets.py @@ -406,6 +406,13 @@ class TestHasTraits(TestCase): a = A() self.assertEqual(a.trait_metadata('i','config_key'), 'MY_VALUE') + def test_trait_metadata_default(self): + class A(HasTraits): + i = Int() + a = A() + self.assertEqual(a.trait_metadata('i', 'config_key'), None) + self.assertEqual(a.trait_metadata('i', 'config_key', 'default'), 'default') + def test_traits(self): class A(HasTraits): i = Int diff --git a/IPython/utils/traitlets.py b/IPython/utils/traitlets.py index 7b65196..c81f68a 100644 --- a/IPython/utils/traitlets.py +++ b/IPython/utils/traitlets.py @@ -458,8 +458,8 @@ class TraitType(object): % (self.name, self.info(), repr_type(value)) raise TraitError(e) - def get_metadata(self, key): - return getattr(self, '_metadata', {}).get(key, None) + def get_metadata(self, key, default=None): + return getattr(self, '_metadata', {}).get(key, default) def set_metadata(self, key, value): getattr(self, '_metadata', {})[key] = value @@ -728,7 +728,7 @@ class HasTraits(py3compat.with_metaclass(MetaHasTraits, object)): return result - def trait_metadata(self, traitname, key): + def trait_metadata(self, traitname, key, default=None): """Get metadata values for trait by key.""" try: trait = getattr(self.__class__, traitname) @@ -736,7 +736,7 @@ class HasTraits(py3compat.with_metaclass(MetaHasTraits, object)): raise TraitError("Class %s does not have a trait named %s" % (self.__class__.__name__, traitname)) else: - return trait.get_metadata(key) + return trait.get_metadata(key, default) #----------------------------------------------------------------------------- # Actual TraitTypes implementations/subclasses