Allow type checking on elements of List,Tuple,Set traits #423

wants to merge 3 commits into


None yet
4 participants

minrk commented May 10, 2011

This commit allows checking types of elements in a Container

Ref: #400 (comment)

So you can do:

class C(HasTraits):
    a = List([Int, Str])
    b = List(Int)
    c = List([0,'a'], types=[Int, Str])
  • a enforces length 2 with Int and Str on elements 0 and 1. Default value is None.
  • b enforces that all elements are Ints, but does not enforce length
  • c is the same as a, but with a default value of [0,'a']

The check is only made on assignment, (so index-assignment, or calls to append/extend are not checked), but should cover enough cases to be useful.

Obviously only style b makes sense for Sets since they are unordered.

It also fixes an incorrect error message if validation fails in a ClassTypeTrait


rkern commented May 10, 2011

Please follow Traits semantics or use different names. In Traits, List() only takes one trait for type-checking.


minrk commented May 10, 2011

Okay, now they look more similar to Traits, thanks. List/Set take single trait as first arg, and Tuple takes *traits e.g.:

a = List(Int, range(5))
b = Set(CStr, range(5))
c = Tuple(Int,Str,Unicode)

For traitlets consistency, however, I do allow them to be used as they have been - passing a single argument as the default value:

a = List(['abc',1,2,3])
b = Set([1,'a'])
c = Tuple((1,2,'a'))

In which case, no type checking will be performed, as no trait has been specified.

And they all keep the default_value kwarg that all traitlets have:

a = List(Int, default_value=range(5))
b = Tuple(Int,Int, default_value=(1,2))

ellisonbg commented May 10, 2011

Min, this look great. I think it is a good idea to follow the traits api as closely as possible, because eventually we will likely be using it.


fperez commented May 17, 2011

Yes, we should definitely try to keep api compatibility with the real traits everywhere. I don't lose hope we'll be able to reunite the two completely in the future, and api differences will just make it trickier.


minrk commented May 17, 2011

minlen/maxlen being added to List, I think List,Tuple,Set should match the Traits api.

@minrk minrk closed this in 02aee17 May 17, 2011

mattvonrocketstein pushed a commit to mattvonrocketstein/ipython that referenced this pull request Nov 3, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment