Created
April 15, 2010 12:19
-
-
Save satra/367024 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
In [13]: from enthought.traits.api import * | |
In [14]: class A(HasTraits): | |
....: pass | |
....: | |
In [16]: a = A() | |
In [17]: a.add_trait('foo',MultiPath(File(exists=True))) | |
In [18]: a.foo = 'fsl_tutorial.py' | |
In [19]: a.trait_names() | |
Out[19]: ['trait_added', 'trait_modified'] | |
In [20]: a.goo = 'fsl_tutorial.py' | |
In [22]: a.trait_names() | |
Out[22]: ['trait_added', 'goo', 'trait_modified'] | |
In [24]: a.foo = 'fsl_tutorial.p' | |
--------------------------------------------------------------------------- | |
TraitError Traceback (most recent call last) | |
TraitError: Each element of the 'foo' trait of an A instance must be a file name, but a value of 'fsl_tutorial.p' <type 'str'> was specified. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MultiPath(List): | |
""" Implements a user friendly traits that accepts one or more | |
paths to files or directories and return a single string whenever | |
possible (when it was set to a single value or a list of length 1). | |
>>> class A(HasTraits): | |
... foo = MultiPath(File(exists=False)) | |
>>> a = A() | |
>>> a.foo = '/software/temp/foo.txt' | |
>>> a.foo | |
'/software/temp/foo.txt' | |
>>> a.foo = ['/software/temp/foo.txt'] | |
>>> a.foo | |
'/software/temp/foo.txt' | |
>>> a.foo = ['/software/temp/foo.txt', '/software/temp/goo.txt'] | |
>>> a.foo | |
['/software/temp/foo.txt', '/software/temp/goo.txt'] | |
""" | |
def validate(self, object, name, value): | |
if not isdefined(value) or (isinstance(value, list) and len(value)==0): | |
return _Undefined() | |
newvalue = value | |
if not isinstance(value, list): | |
newvalue = [value] | |
value = super(MultiPath, self).validate(object, name, newvalue) | |
if len(value) > 0: | |
return value | |
self.error( object, name, value ) | |
def get(self, object, name): | |
value = self.get_value(object, name) | |
if len(value) == 0: | |
return Undefined | |
elif len(value)==1: | |
return value[0] | |
else: | |
return value | |
def set(self, object, name, value): | |
self.set_value(object, name, value) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment