Skip to content

Commit

Permalink
Merge pull request #555 from timkpaine/callable
Browse files Browse the repository at this point in the history
cherrypick #333 and #523 onto 4.3.x
  • Loading branch information
rmorshea authored May 19, 2020
2 parents e5b681c + da2c3e4 commit 2b4f660
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
2 changes: 2 additions & 0 deletions docs/source/trait_types.rst
Original file line number Diff line number Diff line change
Expand Up @@ -110,5 +110,7 @@ Miscellaneous
.. autoclass:: Union
:members: __init__

.. autoclass:: Callable

.. autoclass:: Any

13 changes: 12 additions & 1 deletion traitlets/tests/test_traitlets.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
# Adapted from enthought.traits, Copyright (c) Enthought, Inc.,
# also under the terms of the Modified BSD License.

from __future__ import print_function
import pickle
import re
import sys
Expand All @@ -19,7 +20,7 @@
from traitlets import (
HasTraits, MetaHasTraits, TraitType, Any, Bool, CBytes, Dict, Enum,
Int, CInt, Long, CLong, Integer, Float, CFloat, Complex, Bytes, Unicode,
TraitError, Union, All, Undefined, Type, This, Instance, TCPAddress,
TraitError, Union, Callable, All, Undefined, Type, This, Instance, TCPAddress,
List, Tuple, ObjectName, DottedObjectName, CRegExp, link, directional_link,
ForwardDeclaredType, ForwardDeclaredInstance, validate, observe, default,
observe_compat, BaseDescriptor, HasDescriptors,
Expand Down Expand Up @@ -1143,6 +1144,16 @@ class UnionTraitTest(TraitTestBase):
_good_values = [int, float, True]
_bad_values = [[], (0,), 1j]

class CallableTrait(HasTraits):

value = Callable()

class CallableTraitTest(TraitTestBase):

obj = CallableTrait(value=lambda x: type(x))
_good_values = [int, sorted, lambda x: print(x)]
_bad_values = [[], 1, '']

class OrTrait(HasTraits):

value = Bool() | Unicode()
Expand Down
16 changes: 16 additions & 0 deletions traitlets/traitlets.py
Original file line number Diff line number Diff line change
Expand Up @@ -2688,3 +2688,19 @@ def info(self):
if self.allow_none:
return result + " or None"
return result

class Callable(TraitType):
"""A trait which is callable.
Notes
-----
Classes are callable, as are instances
with a __call__() method."""

info_text = 'a callable'

def validate(self, obj, value):
if six.callable(value):
return value
else:
self.error(obj, value)

0 comments on commit 2b4f660

Please sign in to comment.