forked from enthought/traits
/
trait_handlers.py
3304 lines (2702 loc) · 120 KB
/
trait_handlers.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#------------------------------------------------------------------------------
#
# Copyright (c) 2005, Enthought, Inc.
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in enthought/LICENSE.txt and may be redistributed only
# under the conditions described in the aforementioned license. The license
# is also available online at http://www.enthought.com/licenses/BSD.txt
#
# Thanks for using Enthought open source!
#
# Author: David C. Morrill
# Date: 06/21/2002
#
# Refactored into a separate module: 07/04/2003
#
#------------------------------------------------------------------------------
"""
Defines the BaseTraitHandler class and a standard set of BaseTraitHandler
subclasses for use with the Traits package.
A trait handler mediates the assignment of values to object traits. It
verifies (via its validate() method) that a specified value is consistent
with the object trait, and generates a TraitError exception if it is not
consistent.
"""
#-------------------------------------------------------------------------------
# Imports:
#-------------------------------------------------------------------------------
from __future__ import absolute_import
import sys
import re
import copy
import copy_reg
from types import InstanceType, TypeType, FunctionType, MethodType
from weakref import ref
from .protocols.api import adapt
from .ctraits import CTraitMethod
from .trait_base import (strx, SequenceTypes, Undefined, TypeTypes, ClassTypes,
CoercableTypes, TraitsCache, class_of, enumerate, Missing)
from .trait_errors import TraitError, repr_type
# Patched by 'traits.py' once class is defined!
Trait = Event = None
# Set up a logger:
import logging
logger = logging.getLogger( __name__ )
#-------------------------------------------------------------------------------
# Constants:
#-------------------------------------------------------------------------------
# Trait 'comparison_mode' enum values:
NO_COMPARE = 0
OBJECT_IDENTITY_COMPARE = 1
RICH_COMPARE = 2
RangeTypes = ( int, long, float )
CallableTypes = ( FunctionType, MethodType, CTraitMethod )
# Mapping from trait metadata 'type' to CTrait 'type':
trait_types = {
'python': 1,
'event': 2
}
#-------------------------------------------------------------------------------
# Forward references:
#-------------------------------------------------------------------------------
trait_from = None # Patched by 'traits.py' when real 'trait_from' is defined
#-------------------------------------------------------------------------------
# Returns the correct argument count for a specified function or method:
#-------------------------------------------------------------------------------
def _arg_count ( func ):
""" Returns the correct argument count for a specified function or method.
"""
if (type( func ) is MethodType) and (func.im_self is not None):
return func.func_code.co_argcount - 1
return func.func_code.co_argcount
#-------------------------------------------------------------------------------
# Property error handling functions:
#-------------------------------------------------------------------------------
def _write_only ( object, name ):
raise TraitError, "The '%s' trait of %s instance is 'write only'." % (
name, class_of( object ) )
def _read_only ( object, name, value ):
raise TraitError, "The '%s' trait of %s instance is 'read only'." % (
name, class_of( object ) )
def _undefined_get ( object, name ):
raise TraitError, ("The '%s' trait of %s instance is a property that has "
"no 'get' or 'set' method") % (
name, class_of( object ) )
def _undefined_set ( object, name, value ):
_undefined_get( object, name )
#-------------------------------------------------------------------------------
# 'BaseTraitHandler' class (base class for all user defined traits and trait
# handlers):
#-------------------------------------------------------------------------------
class BaseTraitHandler ( object ):
""" The task of this class and its subclasses is to verify the correctness
of values assigned to object trait attributes.
This class is an alternative to trait validator functions. A trait handler
has several advantages over a trait validator function, due to being an
object:
* Trait handlers have constructors and state. Therefore, you can use
them to create *parameterized types*.
* Trait handlers can have multiple methods, whereas validator functions
can have only one callable interface. This feature allows more
flexibility in their implementation, and allows them to handle a
wider range of cases, such as interactions with other components.
"""
default_value_type = -1
has_items = False
is_mapped = False
editor = None
info_text = 'a legal value'
def is_valid ( self, object, name, value ):
try:
validate = self.validate
try:
validate( object, name, value )
return True
except:
return False
except:
return True
def error ( self, object, name, value ):
"""Raises a TraitError exception.
Parameters
----------
object : object
The object whose attribute is being assigned
name : string
The name of the attribute being assigned
value : object
The proposed new value for the attribute
Description
-----------
This method is called by the validate() method when an assigned value
is not valid. Raising a TraitError exception either notifies the user of
the problem, or, in the case of compound traits, provides a chance for
another trait handler to handle to validate the value.
"""
raise TraitError( object, name, self.full_info( object, name, value ),
value )
def arg_error ( self, method, arg_num, object, name, value ):
""" Raises a TraitError exception to notify the user that a method on
an instance received a positional argument of an incorrect type.
Parameters
----------
method : function
The method that encountered the error
arg_num : integer
The position of the incorrect argument in the argument list
object : object
The object whose method was called
name : string
The name of the parameter corresponding to the incorrect argument
value : object
The value passed to the argument
Description
-----------
This method can be called when type-checking a method.
"""
raise TraitError, ("The '%s' parameter (argument %d) of the %s method "
"of %s instance must be %s, but a value of %s was "
"specified." % (name, arg_num, method.tm_name,
class_of(object),
self.full_info(object, name, value),
repr_type(value)))
def keyword_error ( self, method, object, name, value ):
""" Raises a TraitError exception to notify the user that a method on
an instance received a keyword argument of an incorrect type.
Parameters
----------
method : function
The method that encountered the error
object : object
The object whose method was called
name : string
The name of the parameter corresponding to the incorrect argument
value
The value passed to the argument
Description
-----------
This method can be called when type-checking a method.
"""
raise TraitError, ("The '%s' keyword argument of the %s method of "
"%s instance must be %s, but a value of %s was "
"specified." % (name, method.tm_name,
class_of(object), self.info(object, name, value),
repr_type(value)))
def missing_arg_error ( self, method, arg_num, object, name ):
""" Raises a TraitError exception to notify the user that a method on
an instance failed to receive a required positional argument.
Parameters
----------
method : function
The method that encountered the error
arg_num : integer
The position of the incorrect argument in the argument list
object : object
The object whose method was called
name : string
The name of the parameter corresponding to the incorrect argument
Description
-----------
This method can be called when type-checking a method.
"""
raise TraitError, ("The '%s' parameter (argument %d) of the %s method "
"of %s instance must be specified, but was omitted."
% ( name, arg_num, method.tm_name,
class_of( object ) ) )
def dup_arg_error ( self, method, arg_num, object, name ):
""" Raises a TraitError exception to notify the user that a method on
an instance received an argument as both a keyword argument and a
positional argument.
Parameters
----------
method : function
The method that encountered the error
arg_num : integer
The position of the incorrect argument in the argument list
object : object
The object whose method was called
name : string
The name of the parameter corresponding to the incorrect argument
Description
-----------
This method can be called when type-checking a method.
"""
raise TraitError, ("The '%s' parameter (argument %d) of the %s method "
"of %s instance was specified as both a positional "
"and keyword value."
% ( name, arg_num, method.tm_name,
class_of( object ) ) )
def return_error ( self, method, object, value ):
""" Raises a TraitError exception to notify the user that a method on
an instance returned a value of incorrect type.
Parameters
----------
method : function
The method that encountered the error
object : object
The object whose method was called
value
The value returned by the method
Description
-----------
This method can be called when type-checking a method.
"""
raise TraitError, ("The result of the %s method of %s instance must "
"be %s, but a value of %s was returned." % (
method.tm_name, class_of(object), self.info(),
repr_type(value)))
def full_info ( self, object, name, value ):
"""Returns a string describing the type of value accepted by the
trait handler.
Parameters
----------
object : object
The object whose attribute is being assigned
name : string
The name of the attribute being assigned
value
The proposed new value for the attribute
Description
-----------
The string should be a phrase describing the type defined by the
TraitHandler subclass, rather than a complete sentence. For example, use
the phrase, "a square sprocket" instead of the sentence, "The value must
be a square sprocket." The value returned by full_info() is combined
with other information whenever an error occurs and therefore makes more
sense to the user if the result is a phrase. The full_info() method is
similar in purpose and use to the **info** attribute of a validator
function.
Note that the result can include information specific to the particular
trait handler instance. For example, TraitRange instances return a
string indicating the range of values acceptable to the handler (e.g.,
"an integer in the range from 1 to 9"). If the full_info() method is not
overridden, the default method returns the value of calling the info()
method.
"""
return self.info()
def info ( self ):
"""Must return a string describing the type of value accepted by the
trait handler.
The string should be a phrase describing the type defined by the
TraitHandler subclass, rather than a complete sentence. For example, use
the phrase, "a square sprocket" instead of the sentence, "The value must
be a square sprocket." The value returned by info() is combined with
other information whenever an error occurs and therefore makes more
sense to the user if the result is a phrase. The info() method is
similar in purpose and use to the **info** attribute of a validator
function.
Note that the result can include information specific to the particular
trait handler instance. For example, TraitRange instances return a
string indicating the range of values acceptable to the handler (e.g.,
"an integer in the range from 1 to 9"). If the info() method is not
overridden, the default method returns the value of the 'info_text'
attribute.
"""
return self.info_text
def repr ( self, value ):
""" Returns a printable representation of a value along with its type.
DEPRECATED: This functionality was only used to provide readable error
messages. This functionality has been incorporated into TraitError
itself.
Parameters
----------
value : object
The value to be printed.
"""
import warnings
warnings.warn("this functionality has been merged into TraitError; "
"just pass the raw value", DeprecationWarning)
return repr_type(value)
def get_editor ( self, trait = None ):
""" Returns a trait editor that allows the user to modify the *trait*
trait.
Parameters
----------
trait : trait
The trait to be edited
Description
-----------
This method only needs to be specified if traits defined using this
trait handler require a non-default trait editor in trait user
interfaces. The default implementation of this method returns a trait
editor that allows the user to type an arbitrary string as the value.
For more information on trait user interfaces, refer to the *Traits UI
User Guide*.
"""
if self.editor is None:
self.editor = self.create_editor()
return self.editor
def create_editor ( self ):
""" Returns the default traits UI editor to use for a trait.
"""
from traitsui.api import TextEditor
return TextEditor()
def inner_traits ( self ):
""" Returns a tuple containing the *inner traits* for this trait. Most
trait handlers do not have any inner traits, and so will return an
empty tuple. The exceptions are **List** and **Dict** trait types,
which have inner traits used to validate the values assigned to the
trait. For example, in *List( Int )*, the *inner traits* for
**List** are ( **Int**, ).
"""
return ()
#-------------------------------------------------------------------------------
# 'TraitType' (base class for class-based trait definitions:
#-------------------------------------------------------------------------------
# Create a singleton object for use in the TraitType constructor:
class NoDefaultSpecified ( object ): pass
NoDefaultSpecified = NoDefaultSpecified()
class TraitType ( BaseTraitHandler ):
""" Base class for new trait types.
This class enables you to define new traits using a class-based
approach, instead of by calling the Trait() factory function with an
instance of a TraitHandler derived object.
When subclassing this class, you can implement one or more of the
method signatures below. Note that these methods are defined only as
comments, because the absence of method definitions in the subclass
definition implicitly provides information about how the trait should
operate.
The optional methods are as follows:
* **get ( self, object, name ):**
This is the getter method of a trait that behaves like a property.
*Parameters*
object : an object
The object that the property applies to.
name : string
The name of the property on *object* property.
*Description*
If neither this method nor the set() method is defined, the value
of the trait is handled like a normal object attribute. If this
method is not defined, but the set() method is defined, the trait
behaves like a write-only property. This method should return the
value of the *name* property for the *object* object.
* **set ( self, object, name, value )**
This is the setter method of a trait that behaves like a property.
*Parameters*
object : instance
The object that the property applies to.
name : string
The name of the property on *object*.
value : any
The value being assigned as the value of the property.
*Description*
If neither this method nor the get() method is implemented, the
trait behaves like a normal trait attribute. If this method is not
defined, but the get() method is defined, the trait behaves like a
read-only property. This method does not need to return a value,
but it should raise a TraitError exception if the specified *value*
is not valid and cannot be coerced or adapted to a valid value.
* **validate ( self, object, name, value )**
This method validates, coerces, or adapts the specified *value* as
the value of the *name* trait of the *object* object. This method
is called when a value is assigned to an object trait that is
based on this subclass of *TraitType* and the class does not
contain a definition for either the get() or set() methods. This
method must return the original *value* or any suitably coerced or
adapted value that is a legal value for the trait. If *value* is
not a legal value for the trait, and cannot be coerced or adapted
to a legal value, the method should either raise a **TraitError** or
call the **error** method to raise the **TraitError** on its behalf.
* **is_valid_for ( self, value )**
As an alternative to implementing the **validate** method, you can
instead implement the **is_valid_for** method, which receives only
the *value* being assigned. It should return **True** if the value is
valid, and **False** otherwise.
* **value_for ( self, value )**
As another alternative to implementing the **validate** method, you
can instead implement the **value_for** method, which receives only
the *value* being assigned. It should return the validated form of
*value* if it is valid, or raise a **TraitError** if the value is not
valid.
* **post_setattr ( self, object, name, value )**
This method allows the trait to do additional processing after
*value* has been successfully assigned to the *name* trait of the
*object* object. For most traits there is no additional processing
that needs to be done, and this method need not be defined. It is
normally used for creating "shadow" (i.e., "mapped" traits), but
other uses may arise as well. This method does not need to return
a value, and should normally not raise any exceptions.
"""
default_value = Undefined
metadata = {}
def __init__ ( self, default_value = NoDefaultSpecified, **metadata ):
""" This constructor method is the only method normally called
directly by client code. It defines the trait. The
default implementation accepts an optional, untype-checked default
value, and caller-supplied trait metadata. Override this method
whenever a different method signature or a type-checked
default value is needed.
"""
if default_value is not NoDefaultSpecified:
self.default_value = default_value
if len( metadata ) > 0:
if len( self.metadata ) > 0:
self._metadata = self.metadata.copy()
self._metadata.update( metadata )
else:
self._metadata = metadata
else:
self._metadata = self.metadata
self.init()
def init ( self ):
""" Allows the trait to perform any additional initialization needed.
"""
pass
def get_default_value ( self ):
""" Returns a tuple of the form: (*default_value_type*, *default_value*)
which describes the default value for this trait. The default
implementation analyzes the value of the trait's **default_value**
attribute and determines an appropriate *default_value_type* for
*default_value*. If you need to override this method to provide a
different result tuple, the following values are valid values for
*default_value_type*:
- 0, 1: The *default_value* item of the tuple is the default
value.
- 2: The object containing the trait is the default value.
- 3: A new copy of the list specified by *default_value* is
the default value.
- 4: A new copy of the dictionary specified by *default_value*
is the default value.
- 5: A new instance of TraitListObject constructed using the
*default_value* list is the default value.
- 6: A new instance of TraitDictObject constructed using the
*default_value* dictionary is the default value.
- 7: *default_value* is a tuple of the form: (*callable*, *args*,
*kw*), where *callable* is a callable, *args* is a tuple, and
*kw* is either a dictionary or None. The default value is the
result obtained by invoking callable(\*args, \*\*kw).
- 8: *default_value* is a callable. The default value is the
result obtained by invoking *default_value*(*object*), where
*object* is the object containing the trait. If the trait has
a validate() method, the validate() method is also called to
validate the result.
- 9: A new instance of TraitSetObject constructed using the
*default_value* set is the default value.
"""
dv = self.default_value
dvt = self.default_value_type
if dvt < 0:
dvt = 0
if isinstance( dv, TraitListObject ):
dvt = 5
elif isinstance( dv, list ):
dvt = 3
elif isinstance( dv, TraitDictObject ):
dvt = 6
elif isinstance( dv, dict ):
dvt = 4
elif isinstance( dv, TraitSetObject ):
dvt = 9
self.default_value_type = dvt
return ( dvt, dv )
def clone ( self, default_value = Missing, **metadata ):
""" Clones the contents of this object into a new instance of the same
class, and then modifies the cloned copy using the specified
*default_value* and *metadata*. Returns the cloned object as the
result.
Note that subclasses can change the signature of this method if
needed, but should always call the 'super' method if possible.
"""
if 'parent' not in metadata:
metadata[ 'parent' ] = self
new = self.__class__.__new__( self.__class__ )
new_dict = new.__dict__
new_dict.update( self.__dict__ )
if 'editor' in new_dict:
del new_dict[ 'editor' ]
if '_metadata' in new_dict:
new._metadata = new._metadata.copy()
else:
new._metadata = {}
new._metadata.update( metadata )
if default_value is not Missing:
new.default_value = default_value
if self.validate is not None:
try:
new.default_value = self.validate( None, None,
default_value )
except:
pass
return new
def get_value ( self, object, name, trait = None ):
""" Returns the current value of a property-based trait.
"""
cname = TraitsCache + name
value = object.__dict__.get( cname, Undefined )
if value is Undefined:
if trait is None:
trait = object.trait( name )
object.__dict__[ cname ] = value = \
trait.default_value_for( object, name )
return value
def set_value ( self, object, name, value ):
""" Sets the cached value of a property-based trait and fires the
appropriate trait change event.
"""
cname = TraitsCache + name
old = object.__dict__.get( cname, Undefined )
if value != old:
object.__dict__[ cname ] = value
object.trait_property_changed( name, old, value )
#-- Private Methods --------------------------------------------------------
def __call__ ( self, *args, **kw ):
""" Allows a derivative trait to be defined from this one.
"""
return self.clone( *args, **kw ).as_ctrait()
def _is_valid_for ( self, object, name, value ):
""" Handles a simplified validator that only returns whether or not the
original value is valid.
"""
if self.is_valid_for( value ):
return value
self.error( object, name, value )
def _value_for ( self, object, name, value ):
""" Handles a simplified validator that only receives the value
argument.
"""
try:
return self.value_for( value )
except TraitError:
self.error( object, name, value )
def as_ctrait ( self ):
""" Returns a CTrait corresponding to the trait defined by this class.
"""
from .traits import CTrait
metadata = getattr( self, '_metadata', {} )
getter = getattr( self, 'get', None )
setter = getattr( self, 'set', None )
if (getter is not None) or (setter is not None):
if getter is None:
getter = _write_only
metadata.setdefault( 'transient', True )
elif setter is None:
setter = _read_only
metadata.setdefault( 'transient', True )
trait = CTrait( 4 )
n = 0
validate = getattr( self, 'validate', None )
if validate is not None:
n = _arg_count( validate )
trait.property( getter, _arg_count( getter ),
setter, _arg_count( setter ),
validate, n )
metadata.setdefault( 'type', 'property' )
else:
type = getattr( self, 'ctrait_type', None )
if type is None:
type = trait_types.get( metadata.get( 'type' ), 0 )
trait = CTrait( type )
validate = getattr( self, 'fast_validate', None )
if validate is None:
validate = getattr( self, 'validate', None )
if validate is None:
validate = getattr( self, 'is_valid_for', None )
if validate is not None:
validate = self._is_valid_for
else:
validate = getattr( self, 'value_for', None )
if validate is not None:
validate = self._value_for
if validate is not None:
trait.set_validate( validate )
post_setattr = getattr( self, 'post_setattr', None )
if post_setattr is not None:
trait.post_setattr = post_setattr
trait.is_mapped( self.is_mapped )
# Note: The use of 'rich_compare' metadata is deprecated; use
# 'comparison_mode' metadata instead:
rich_compare = metadata.get( 'rich_compare' )
if rich_compare is not None:
trait.rich_comparison( rich_compare is True )
comparison_mode = metadata.get( 'comparison_mode' )
if comparison_mode is not None:
trait.comparison_mode( comparison_mode )
metadata.setdefault( 'type', 'trait' )
trait.default_value( *self.get_default_value() )
trait.value_allowed( metadata.get( 'trait_value', False ) is True )
trait.handler = self
trait.__dict__ = metadata.copy()
return trait
def __getattr__ ( self, name ):
if (name[:2] == '__') and (name[-2:] == '__'):
raise AttributeError( "'%s' object has no attribute '%s'" % (
self.__class__.__name__, name ) )
return getattr( self, '_metadata', {} ).get( name, None )
#-------------------------------------------------------------------------------
# 'TraitHandler' class (base class for all trait handlers):
#-------------------------------------------------------------------------------
class TraitHandler ( BaseTraitHandler ):
""" The task of this class and its subclasses is to verify the correctness
of values assigned to object trait attributes.
This class is an alternative to trait validator functions. A trait handler
has several advantages over a trait validator function, due to being an
object:
* Trait handlers have constructors and state. Therefore, you can use
them to create *parameterized types*.
* Trait handlers can have multiple methods, whereas validator functions
can have only one callable interface. This feature allows more
flexibility in their implementation, and allows them to handle a
wider range of cases, such as interactions with other components.
The only method of TraitHandler that *must* be implemented by subclasses
is validate().
"""
def validate ( self, object, name, value ):
""" Verifies whether a new value assigned to a trait attribute is valid.
Parameters
----------
object : object
The object whose attribute is being assigned
name : string
The name of the attribute being assigned
value
The proposed new value for the attribute
Returns
-------
If the new value is valid, this method must return either the original
value passed to it, or an alternate value to be assigned in place of the
original value. Whatever value this method returns is the actual value
assigned to *object.name*.
Description
-----------
This method *must* be implemented by subclasses of TraitHandler. It is
called whenever a new value is assigned to a trait attribute defined
using this trait handler.
If the value received by validate() is not valid for the trait
attribute, the method must called the predefined error() method to
raise a TraitError exception
"""
raise TraitError, (
"The '%s' trait of %s instance has an unknown type. "
"Contact the developer to correct the problem." % (
name, class_of( object ) ) )
#-------------------------------------------------------------------------------
# 'TraitRange' class:
#-------------------------------------------------------------------------------
class TraitRange ( TraitHandler ):
"""Ensures that a trait attribute lies within a specified numeric range.
TraitRange is the underlying handler for the predefined Range() trait
factory.
Any value assigned to a trait containing a TraitRange handler must be of the
correct type and in the numeric range defined by the TraitRange instance.
No automatic coercion takes place. For example::
class Person(HasTraits):
age = Trait(0, TraitRange(0, 150))
weight = Trait(0.0, TraitRange(0.0, None))
This example defines a Person class, which has an **age** trait
attribute, which must be an integer/long in the range from 0 to 150, and a
**weight** trait attribute, which must be a non-negative float value.
"""
def __init__ ( self, low = None, high = None,
exclude_low = False, exclude_high = False ):
""" Creates a TraitRange handler.
Parameters
----------
low : number
The minimum value that the trait can accept
high : number
The maximum value that the trait can accept
exclude_low : Boolean
Should the *low* value be exclusive (or inclusive)
exclude_high : Boolean
Should the *high* value be exclusive (or inclusive)
Description
-----------
The *low* and *high* values must be of the same Python numeric type,
either ``int``, ``long`` or ``float``. Alternatively, one of the values
may be None, to indicate that that portion of the range is
unbounded. The *exclude_low* and *exclude_high* values can be used to
specify whether the *low* and *high* values should be exclusive (or
inclusive).
"""
vtype = type( high )
if (low is not None) and (vtype is not float):
vtype = type( low )
if vtype not in RangeTypes:
raise TraitError, ("TraitRange can only be use for int, long or "
"float values, but a value of type %s was "
"specified." % vtype)
if vtype is float:
self.validate = self.float_validate
kind = 4
self._type_desc = 'a floating point number'
if low is not None:
low = float( low )
if high is not None:
high = float( high )
elif vtype is long:
self.validate = self.long_validate
self._type_desc = 'a long integer'
if low is not None:
low = long( low )
if high is not None:
high = long( high )
else:
self.validate = self.int_validate
kind = 3
self._type_desc = 'an integer'
if low is not None:
low = int( low )
if high is not None:
high = int( high )
exclude_mask = 0
if exclude_low:
exclude_mask |= 1
if exclude_high:
exclude_mask |= 2
if vtype is not long:
self.fast_validate = ( kind, low, high, exclude_mask )
# Assign type-corrected arguments to handler attributes
self._low = low
self._high = high
self._exclude_low = exclude_low
self._exclude_high = exclude_high
def float_validate ( self, object, name, value ):
try:
if (isinstance( value, RangeTypes ) and
((self._low is None) or
(self._exclude_low and (self._low < value)) or
((not self._exclude_low) and (self._low <= value))) and
((self._high is None) or
(self._exclude_high and (self._high > value)) or
((not self._exclude_high) and (self._high >= value)))):
return float( value )
except:
pass
self.error( object, name, value )
def int_validate ( self, object, name, value ):
try:
if (isinstance( value, int ) and
((self._low is None) or
(self._exclude_low and (self._low < value)) or
((not self._exclude_low) and (self._low <= value))) and
((self._high is None) or
(self._exclude_high and (self._high > value)) or
((not self._exclude_high) and (self._high >= value)))):
return value
except:
pass
self.error( object, name, value )
def long_validate ( self, object, name, value ):
try:
if (isinstance( value, long ) and
((self._low is None) or
(self._exclude_low and (self._low < value)) or
((not self._exclude_low) and (self._low <= value))) and
((self._high is None) or
(self._exclude_high and (self._high > value)) or
((not self._exclude_high) and (self._high >= value)))):
return value
except:
pass
self.error( object, name, value )
def info ( self ):
if self._low is None:
if self._high is None:
return self._type_desc
return '%s <%s %s' % (
self._type_desc, '='[ self._exclude_high: ], self._high )
elif self._high is None:
return '%s >%s %s' % (
self._type_desc, '='[ self._exclude_low: ], self._low )
return '%s <%s %s <%s %s' % (
self._low, '='[ self._exclude_low: ], self._type_desc,
'='[ self._exclude_high: ], self._high )
def get_editor ( self, trait ):
from traitsui.api import RangeEditor
auto_set = trait.auto_set
if auto_set is None:
auto_set = True
return RangeEditor( self,
mode = trait.mode or 'auto',
cols = trait.cols or 3,
auto_set = auto_set,
enter_set = trait.enter_set or False,
low_label = trait.low or '',
high_label = trait.high or '' )
#-------------------------------------------------------------------------------
# 'TraitString' class:
#-------------------------------------------------------------------------------
class TraitString ( TraitHandler ):
""" Ensures that a trait attribute value is a string that satisfied some
additional, optional constraints.
The optional constraints include minimum and maximum lengths, and a regular
expression that the string must match.
If the value assigned to the trait attribute is a Python numeric type, the
TraitString handler first coerces the value to a string. Values of other
non-string types result in a TraitError being raised. The handler then
makes sure that the resulting string is within the specified length range
and that it matches the regular expression.
Example
-------
::
class Person(HasTraits):