##// END OF EJS Templates
add HasTraits.delay_trait_notifications...
Min RK -
Show More
@@ -1,1493 +1,1537 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Tests for IPython.utils.traitlets."""
2 """Tests for IPython.utils.traitlets."""
3
3
4 # Copyright (c) IPython Development Team.
4 # Copyright (c) IPython Development Team.
5 # Distributed under the terms of the Modified BSD License.
5 # Distributed under the terms of the Modified BSD License.
6 #
6 #
7 # Adapted from enthought.traits, Copyright (c) Enthought, Inc.,
7 # Adapted from enthought.traits, Copyright (c) Enthought, Inc.,
8 # also under the terms of the Modified BSD License.
8 # also under the terms of the Modified BSD License.
9
9
10 import pickle
10 import pickle
11 import re
11 import re
12 import sys
12 import sys
13 from unittest import TestCase
13 from unittest import TestCase
14
14
15 import nose.tools as nt
15 import nose.tools as nt
16 from nose import SkipTest
16 from nose import SkipTest
17
17
18 from IPython.utils.traitlets import (
18 from IPython.utils.traitlets import (
19 HasTraits, MetaHasTraits, TraitType, Any, Bool, CBytes, Dict, Enum,
19 HasTraits, MetaHasTraits, TraitType, Any, Bool, CBytes, Dict, Enum,
20 Int, Long, Integer, Float, Complex, Bytes, Unicode, TraitError,
20 Int, Long, Integer, Float, Complex, Bytes, Unicode, TraitError,
21 Union, Undefined, Type, This, Instance, TCPAddress, List, Tuple,
21 Union, Undefined, Type, This, Instance, TCPAddress, List, Tuple,
22 ObjectName, DottedObjectName, CRegExp, link, directional_link,
22 ObjectName, DottedObjectName, CRegExp, link, directional_link,
23 EventfulList, EventfulDict, ForwardDeclaredType, ForwardDeclaredInstance,
23 EventfulList, EventfulDict, ForwardDeclaredType, ForwardDeclaredInstance,
24 )
24 )
25 from IPython.utils import py3compat
25 from IPython.utils import py3compat
26 from IPython.testing.decorators import skipif
26 from IPython.testing.decorators import skipif
27
27
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29 # Helper classes for testing
29 # Helper classes for testing
30 #-----------------------------------------------------------------------------
30 #-----------------------------------------------------------------------------
31
31
32
32
33 class HasTraitsStub(HasTraits):
33 class HasTraitsStub(HasTraits):
34
34
35 def _notify_trait(self, name, old, new):
35 def _notify_trait(self, name, old, new):
36 self._notify_name = name
36 self._notify_name = name
37 self._notify_old = old
37 self._notify_old = old
38 self._notify_new = new
38 self._notify_new = new
39
39
40
40
41 #-----------------------------------------------------------------------------
41 #-----------------------------------------------------------------------------
42 # Test classes
42 # Test classes
43 #-----------------------------------------------------------------------------
43 #-----------------------------------------------------------------------------
44
44
45
45
46 class TestTraitType(TestCase):
46 class TestTraitType(TestCase):
47
47
48 def test_get_undefined(self):
48 def test_get_undefined(self):
49 class A(HasTraits):
49 class A(HasTraits):
50 a = TraitType
50 a = TraitType
51 a = A()
51 a = A()
52 self.assertEqual(a.a, Undefined)
52 self.assertEqual(a.a, Undefined)
53
53
54 def test_set(self):
54 def test_set(self):
55 class A(HasTraitsStub):
55 class A(HasTraitsStub):
56 a = TraitType
56 a = TraitType
57
57
58 a = A()
58 a = A()
59 a.a = 10
59 a.a = 10
60 self.assertEqual(a.a, 10)
60 self.assertEqual(a.a, 10)
61 self.assertEqual(a._notify_name, 'a')
61 self.assertEqual(a._notify_name, 'a')
62 self.assertEqual(a._notify_old, Undefined)
62 self.assertEqual(a._notify_old, Undefined)
63 self.assertEqual(a._notify_new, 10)
63 self.assertEqual(a._notify_new, 10)
64
64
65 def test_validate(self):
65 def test_validate(self):
66 class MyTT(TraitType):
66 class MyTT(TraitType):
67 def validate(self, inst, value):
67 def validate(self, inst, value):
68 return -1
68 return -1
69 class A(HasTraitsStub):
69 class A(HasTraitsStub):
70 tt = MyTT
70 tt = MyTT
71
71
72 a = A()
72 a = A()
73 a.tt = 10
73 a.tt = 10
74 self.assertEqual(a.tt, -1)
74 self.assertEqual(a.tt, -1)
75
75
76 def test_default_validate(self):
76 def test_default_validate(self):
77 class MyIntTT(TraitType):
77 class MyIntTT(TraitType):
78 def validate(self, obj, value):
78 def validate(self, obj, value):
79 if isinstance(value, int):
79 if isinstance(value, int):
80 return value
80 return value
81 self.error(obj, value)
81 self.error(obj, value)
82 class A(HasTraits):
82 class A(HasTraits):
83 tt = MyIntTT(10)
83 tt = MyIntTT(10)
84 a = A()
84 a = A()
85 self.assertEqual(a.tt, 10)
85 self.assertEqual(a.tt, 10)
86
86
87 # Defaults are validated when the HasTraits is instantiated
87 # Defaults are validated when the HasTraits is instantiated
88 class B(HasTraits):
88 class B(HasTraits):
89 tt = MyIntTT('bad default')
89 tt = MyIntTT('bad default')
90 self.assertRaises(TraitError, B)
90 self.assertRaises(TraitError, B)
91
91
92 def test_info(self):
92 def test_info(self):
93 class A(HasTraits):
93 class A(HasTraits):
94 tt = TraitType
94 tt = TraitType
95 a = A()
95 a = A()
96 self.assertEqual(A.tt.info(), 'any value')
96 self.assertEqual(A.tt.info(), 'any value')
97
97
98 def test_error(self):
98 def test_error(self):
99 class A(HasTraits):
99 class A(HasTraits):
100 tt = TraitType
100 tt = TraitType
101 a = A()
101 a = A()
102 self.assertRaises(TraitError, A.tt.error, a, 10)
102 self.assertRaises(TraitError, A.tt.error, a, 10)
103
103
104 def test_dynamic_initializer(self):
104 def test_dynamic_initializer(self):
105 class A(HasTraits):
105 class A(HasTraits):
106 x = Int(10)
106 x = Int(10)
107 def _x_default(self):
107 def _x_default(self):
108 return 11
108 return 11
109 class B(A):
109 class B(A):
110 x = Int(20)
110 x = Int(20)
111 class C(A):
111 class C(A):
112 def _x_default(self):
112 def _x_default(self):
113 return 21
113 return 21
114
114
115 a = A()
115 a = A()
116 self.assertEqual(a._trait_values, {})
116 self.assertEqual(a._trait_values, {})
117 self.assertEqual(list(a._trait_dyn_inits.keys()), ['x'])
117 self.assertEqual(list(a._trait_dyn_inits.keys()), ['x'])
118 self.assertEqual(a.x, 11)
118 self.assertEqual(a.x, 11)
119 self.assertEqual(a._trait_values, {'x': 11})
119 self.assertEqual(a._trait_values, {'x': 11})
120 b = B()
120 b = B()
121 self.assertEqual(b._trait_values, {'x': 20})
121 self.assertEqual(b._trait_values, {'x': 20})
122 self.assertEqual(list(a._trait_dyn_inits.keys()), ['x'])
122 self.assertEqual(list(a._trait_dyn_inits.keys()), ['x'])
123 self.assertEqual(b.x, 20)
123 self.assertEqual(b.x, 20)
124 c = C()
124 c = C()
125 self.assertEqual(c._trait_values, {})
125 self.assertEqual(c._trait_values, {})
126 self.assertEqual(list(a._trait_dyn_inits.keys()), ['x'])
126 self.assertEqual(list(a._trait_dyn_inits.keys()), ['x'])
127 self.assertEqual(c.x, 21)
127 self.assertEqual(c.x, 21)
128 self.assertEqual(c._trait_values, {'x': 21})
128 self.assertEqual(c._trait_values, {'x': 21})
129 # Ensure that the base class remains unmolested when the _default
129 # Ensure that the base class remains unmolested when the _default
130 # initializer gets overridden in a subclass.
130 # initializer gets overridden in a subclass.
131 a = A()
131 a = A()
132 c = C()
132 c = C()
133 self.assertEqual(a._trait_values, {})
133 self.assertEqual(a._trait_values, {})
134 self.assertEqual(list(a._trait_dyn_inits.keys()), ['x'])
134 self.assertEqual(list(a._trait_dyn_inits.keys()), ['x'])
135 self.assertEqual(a.x, 11)
135 self.assertEqual(a.x, 11)
136 self.assertEqual(a._trait_values, {'x': 11})
136 self.assertEqual(a._trait_values, {'x': 11})
137
137
138
138
139
139
140 class TestHasTraitsMeta(TestCase):
140 class TestHasTraitsMeta(TestCase):
141
141
142 def test_metaclass(self):
142 def test_metaclass(self):
143 self.assertEqual(type(HasTraits), MetaHasTraits)
143 self.assertEqual(type(HasTraits), MetaHasTraits)
144
144
145 class A(HasTraits):
145 class A(HasTraits):
146 a = Int
146 a = Int
147
147
148 a = A()
148 a = A()
149 self.assertEqual(type(a.__class__), MetaHasTraits)
149 self.assertEqual(type(a.__class__), MetaHasTraits)
150 self.assertEqual(a.a,0)
150 self.assertEqual(a.a,0)
151 a.a = 10
151 a.a = 10
152 self.assertEqual(a.a,10)
152 self.assertEqual(a.a,10)
153
153
154 class B(HasTraits):
154 class B(HasTraits):
155 b = Int()
155 b = Int()
156
156
157 b = B()
157 b = B()
158 self.assertEqual(b.b,0)
158 self.assertEqual(b.b,0)
159 b.b = 10
159 b.b = 10
160 self.assertEqual(b.b,10)
160 self.assertEqual(b.b,10)
161
161
162 class C(HasTraits):
162 class C(HasTraits):
163 c = Int(30)
163 c = Int(30)
164
164
165 c = C()
165 c = C()
166 self.assertEqual(c.c,30)
166 self.assertEqual(c.c,30)
167 c.c = 10
167 c.c = 10
168 self.assertEqual(c.c,10)
168 self.assertEqual(c.c,10)
169
169
170 def test_this_class(self):
170 def test_this_class(self):
171 class A(HasTraits):
171 class A(HasTraits):
172 t = This()
172 t = This()
173 tt = This()
173 tt = This()
174 class B(A):
174 class B(A):
175 tt = This()
175 tt = This()
176 ttt = This()
176 ttt = This()
177 self.assertEqual(A.t.this_class, A)
177 self.assertEqual(A.t.this_class, A)
178 self.assertEqual(B.t.this_class, A)
178 self.assertEqual(B.t.this_class, A)
179 self.assertEqual(B.tt.this_class, B)
179 self.assertEqual(B.tt.this_class, B)
180 self.assertEqual(B.ttt.this_class, B)
180 self.assertEqual(B.ttt.this_class, B)
181
181
182 class TestHasTraitsNotify(TestCase):
182 class TestHasTraitsNotify(TestCase):
183
183
184 def setUp(self):
184 def setUp(self):
185 self._notify1 = []
185 self._notify1 = []
186 self._notify2 = []
186 self._notify2 = []
187
187
188 def notify1(self, name, old, new):
188 def notify1(self, name, old, new):
189 self._notify1.append((name, old, new))
189 self._notify1.append((name, old, new))
190
190
191 def notify2(self, name, old, new):
191 def notify2(self, name, old, new):
192 self._notify2.append((name, old, new))
192 self._notify2.append((name, old, new))
193
193
194 def test_notify_all(self):
194 def test_notify_all(self):
195
195
196 class A(HasTraits):
196 class A(HasTraits):
197 a = Int
197 a = Int
198 b = Float
198 b = Float
199
199
200 a = A()
200 a = A()
201 a.on_trait_change(self.notify1)
201 a.on_trait_change(self.notify1)
202 a.a = 0
202 a.a = 0
203 self.assertEqual(len(self._notify1),0)
203 self.assertEqual(len(self._notify1),0)
204 a.b = 0.0
204 a.b = 0.0
205 self.assertEqual(len(self._notify1),0)
205 self.assertEqual(len(self._notify1),0)
206 a.a = 10
206 a.a = 10
207 self.assertTrue(('a',0,10) in self._notify1)
207 self.assertTrue(('a',0,10) in self._notify1)
208 a.b = 10.0
208 a.b = 10.0
209 self.assertTrue(('b',0.0,10.0) in self._notify1)
209 self.assertTrue(('b',0.0,10.0) in self._notify1)
210 self.assertRaises(TraitError,setattr,a,'a','bad string')
210 self.assertRaises(TraitError,setattr,a,'a','bad string')
211 self.assertRaises(TraitError,setattr,a,'b','bad string')
211 self.assertRaises(TraitError,setattr,a,'b','bad string')
212 self._notify1 = []
212 self._notify1 = []
213 a.on_trait_change(self.notify1,remove=True)
213 a.on_trait_change(self.notify1,remove=True)
214 a.a = 20
214 a.a = 20
215 a.b = 20.0
215 a.b = 20.0
216 self.assertEqual(len(self._notify1),0)
216 self.assertEqual(len(self._notify1),0)
217
217
218 def test_notify_one(self):
218 def test_notify_one(self):
219
219
220 class A(HasTraits):
220 class A(HasTraits):
221 a = Int
221 a = Int
222 b = Float
222 b = Float
223
223
224 a = A()
224 a = A()
225 a.on_trait_change(self.notify1, 'a')
225 a.on_trait_change(self.notify1, 'a')
226 a.a = 0
226 a.a = 0
227 self.assertEqual(len(self._notify1),0)
227 self.assertEqual(len(self._notify1),0)
228 a.a = 10
228 a.a = 10
229 self.assertTrue(('a',0,10) in self._notify1)
229 self.assertTrue(('a',0,10) in self._notify1)
230 self.assertRaises(TraitError,setattr,a,'a','bad string')
230 self.assertRaises(TraitError,setattr,a,'a','bad string')
231
231
232 def test_subclass(self):
232 def test_subclass(self):
233
233
234 class A(HasTraits):
234 class A(HasTraits):
235 a = Int
235 a = Int
236
236
237 class B(A):
237 class B(A):
238 b = Float
238 b = Float
239
239
240 b = B()
240 b = B()
241 self.assertEqual(b.a,0)
241 self.assertEqual(b.a,0)
242 self.assertEqual(b.b,0.0)
242 self.assertEqual(b.b,0.0)
243 b.a = 100
243 b.a = 100
244 b.b = 100.0
244 b.b = 100.0
245 self.assertEqual(b.a,100)
245 self.assertEqual(b.a,100)
246 self.assertEqual(b.b,100.0)
246 self.assertEqual(b.b,100.0)
247
247
248 def test_notify_subclass(self):
248 def test_notify_subclass(self):
249
249
250 class A(HasTraits):
250 class A(HasTraits):
251 a = Int
251 a = Int
252
252
253 class B(A):
253 class B(A):
254 b = Float
254 b = Float
255
255
256 b = B()
256 b = B()
257 b.on_trait_change(self.notify1, 'a')
257 b.on_trait_change(self.notify1, 'a')
258 b.on_trait_change(self.notify2, 'b')
258 b.on_trait_change(self.notify2, 'b')
259 b.a = 0
259 b.a = 0
260 b.b = 0.0
260 b.b = 0.0
261 self.assertEqual(len(self._notify1),0)
261 self.assertEqual(len(self._notify1),0)
262 self.assertEqual(len(self._notify2),0)
262 self.assertEqual(len(self._notify2),0)
263 b.a = 10
263 b.a = 10
264 b.b = 10.0
264 b.b = 10.0
265 self.assertTrue(('a',0,10) in self._notify1)
265 self.assertTrue(('a',0,10) in self._notify1)
266 self.assertTrue(('b',0.0,10.0) in self._notify2)
266 self.assertTrue(('b',0.0,10.0) in self._notify2)
267
267
268 def test_static_notify(self):
268 def test_static_notify(self):
269
269
270 class A(HasTraits):
270 class A(HasTraits):
271 a = Int
271 a = Int
272 _notify1 = []
272 _notify1 = []
273 def _a_changed(self, name, old, new):
273 def _a_changed(self, name, old, new):
274 self._notify1.append((name, old, new))
274 self._notify1.append((name, old, new))
275
275
276 a = A()
276 a = A()
277 a.a = 0
277 a.a = 0
278 # This is broken!!!
278 # This is broken!!!
279 self.assertEqual(len(a._notify1),0)
279 self.assertEqual(len(a._notify1),0)
280 a.a = 10
280 a.a = 10
281 self.assertTrue(('a',0,10) in a._notify1)
281 self.assertTrue(('a',0,10) in a._notify1)
282
282
283 class B(A):
283 class B(A):
284 b = Float
284 b = Float
285 _notify2 = []
285 _notify2 = []
286 def _b_changed(self, name, old, new):
286 def _b_changed(self, name, old, new):
287 self._notify2.append((name, old, new))
287 self._notify2.append((name, old, new))
288
288
289 b = B()
289 b = B()
290 b.a = 10
290 b.a = 10
291 b.b = 10.0
291 b.b = 10.0
292 self.assertTrue(('a',0,10) in b._notify1)
292 self.assertTrue(('a',0,10) in b._notify1)
293 self.assertTrue(('b',0.0,10.0) in b._notify2)
293 self.assertTrue(('b',0.0,10.0) in b._notify2)
294
294
295 def test_notify_args(self):
295 def test_notify_args(self):
296
296
297 def callback0():
297 def callback0():
298 self.cb = ()
298 self.cb = ()
299 def callback1(name):
299 def callback1(name):
300 self.cb = (name,)
300 self.cb = (name,)
301 def callback2(name, new):
301 def callback2(name, new):
302 self.cb = (name, new)
302 self.cb = (name, new)
303 def callback3(name, old, new):
303 def callback3(name, old, new):
304 self.cb = (name, old, new)
304 self.cb = (name, old, new)
305
305
306 class A(HasTraits):
306 class A(HasTraits):
307 a = Int
307 a = Int
308
308
309 a = A()
309 a = A()
310 a.on_trait_change(callback0, 'a')
310 a.on_trait_change(callback0, 'a')
311 a.a = 10
311 a.a = 10
312 self.assertEqual(self.cb,())
312 self.assertEqual(self.cb,())
313 a.on_trait_change(callback0, 'a', remove=True)
313 a.on_trait_change(callback0, 'a', remove=True)
314
314
315 a.on_trait_change(callback1, 'a')
315 a.on_trait_change(callback1, 'a')
316 a.a = 100
316 a.a = 100
317 self.assertEqual(self.cb,('a',))
317 self.assertEqual(self.cb,('a',))
318 a.on_trait_change(callback1, 'a', remove=True)
318 a.on_trait_change(callback1, 'a', remove=True)
319
319
320 a.on_trait_change(callback2, 'a')
320 a.on_trait_change(callback2, 'a')
321 a.a = 1000
321 a.a = 1000
322 self.assertEqual(self.cb,('a',1000))
322 self.assertEqual(self.cb,('a',1000))
323 a.on_trait_change(callback2, 'a', remove=True)
323 a.on_trait_change(callback2, 'a', remove=True)
324
324
325 a.on_trait_change(callback3, 'a')
325 a.on_trait_change(callback3, 'a')
326 a.a = 10000
326 a.a = 10000
327 self.assertEqual(self.cb,('a',1000,10000))
327 self.assertEqual(self.cb,('a',1000,10000))
328 a.on_trait_change(callback3, 'a', remove=True)
328 a.on_trait_change(callback3, 'a', remove=True)
329
329
330 self.assertEqual(len(a._trait_notifiers['a']),0)
330 self.assertEqual(len(a._trait_notifiers['a']),0)
331
331
332 def test_notify_only_once(self):
332 def test_notify_only_once(self):
333
333
334 class A(HasTraits):
334 class A(HasTraits):
335 listen_to = ['a']
335 listen_to = ['a']
336
336
337 a = Int(0)
337 a = Int(0)
338 b = 0
338 b = 0
339
339
340 def __init__(self, **kwargs):
340 def __init__(self, **kwargs):
341 super(A, self).__init__(**kwargs)
341 super(A, self).__init__(**kwargs)
342 self.on_trait_change(self.listener1, ['a'])
342 self.on_trait_change(self.listener1, ['a'])
343
343
344 def listener1(self, name, old, new):
344 def listener1(self, name, old, new):
345 self.b += 1
345 self.b += 1
346
346
347 class B(A):
347 class B(A):
348
348
349 c = 0
349 c = 0
350 d = 0
350 d = 0
351
351
352 def __init__(self, **kwargs):
352 def __init__(self, **kwargs):
353 super(B, self).__init__(**kwargs)
353 super(B, self).__init__(**kwargs)
354 self.on_trait_change(self.listener2)
354 self.on_trait_change(self.listener2)
355
355
356 def listener2(self, name, old, new):
356 def listener2(self, name, old, new):
357 self.c += 1
357 self.c += 1
358
358
359 def _a_changed(self, name, old, new):
359 def _a_changed(self, name, old, new):
360 self.d += 1
360 self.d += 1
361
361
362 b = B()
362 b = B()
363 b.a += 1
363 b.a += 1
364 self.assertEqual(b.b, b.c)
364 self.assertEqual(b.b, b.c)
365 self.assertEqual(b.b, b.d)
365 self.assertEqual(b.b, b.d)
366 b.a += 1
366 b.a += 1
367 self.assertEqual(b.b, b.c)
367 self.assertEqual(b.b, b.c)
368 self.assertEqual(b.b, b.d)
368 self.assertEqual(b.b, b.d)
369
369
370
370
371 class TestHasTraits(TestCase):
371 class TestHasTraits(TestCase):
372
372
373 def test_trait_names(self):
373 def test_trait_names(self):
374 class A(HasTraits):
374 class A(HasTraits):
375 i = Int
375 i = Int
376 f = Float
376 f = Float
377 a = A()
377 a = A()
378 self.assertEqual(sorted(a.trait_names()),['f','i'])
378 self.assertEqual(sorted(a.trait_names()),['f','i'])
379 self.assertEqual(sorted(A.class_trait_names()),['f','i'])
379 self.assertEqual(sorted(A.class_trait_names()),['f','i'])
380
380
381 def test_trait_metadata(self):
381 def test_trait_metadata(self):
382 class A(HasTraits):
382 class A(HasTraits):
383 i = Int(config_key='MY_VALUE')
383 i = Int(config_key='MY_VALUE')
384 a = A()
384 a = A()
385 self.assertEqual(a.trait_metadata('i','config_key'), 'MY_VALUE')
385 self.assertEqual(a.trait_metadata('i','config_key'), 'MY_VALUE')
386
386
387 def test_trait_metadata_default(self):
387 def test_trait_metadata_default(self):
388 class A(HasTraits):
388 class A(HasTraits):
389 i = Int()
389 i = Int()
390 a = A()
390 a = A()
391 self.assertEqual(a.trait_metadata('i', 'config_key'), None)
391 self.assertEqual(a.trait_metadata('i', 'config_key'), None)
392 self.assertEqual(a.trait_metadata('i', 'config_key', 'default'), 'default')
392 self.assertEqual(a.trait_metadata('i', 'config_key', 'default'), 'default')
393
393
394 def test_traits(self):
394 def test_traits(self):
395 class A(HasTraits):
395 class A(HasTraits):
396 i = Int
396 i = Int
397 f = Float
397 f = Float
398 a = A()
398 a = A()
399 self.assertEqual(a.traits(), dict(i=A.i, f=A.f))
399 self.assertEqual(a.traits(), dict(i=A.i, f=A.f))
400 self.assertEqual(A.class_traits(), dict(i=A.i, f=A.f))
400 self.assertEqual(A.class_traits(), dict(i=A.i, f=A.f))
401
401
402 def test_traits_metadata(self):
402 def test_traits_metadata(self):
403 class A(HasTraits):
403 class A(HasTraits):
404 i = Int(config_key='VALUE1', other_thing='VALUE2')
404 i = Int(config_key='VALUE1', other_thing='VALUE2')
405 f = Float(config_key='VALUE3', other_thing='VALUE2')
405 f = Float(config_key='VALUE3', other_thing='VALUE2')
406 j = Int(0)
406 j = Int(0)
407 a = A()
407 a = A()
408 self.assertEqual(a.traits(), dict(i=A.i, f=A.f, j=A.j))
408 self.assertEqual(a.traits(), dict(i=A.i, f=A.f, j=A.j))
409 traits = a.traits(config_key='VALUE1', other_thing='VALUE2')
409 traits = a.traits(config_key='VALUE1', other_thing='VALUE2')
410 self.assertEqual(traits, dict(i=A.i))
410 self.assertEqual(traits, dict(i=A.i))
411
411
412 # This passes, but it shouldn't because I am replicating a bug in
412 # This passes, but it shouldn't because I am replicating a bug in
413 # traits.
413 # traits.
414 traits = a.traits(config_key=lambda v: True)
414 traits = a.traits(config_key=lambda v: True)
415 self.assertEqual(traits, dict(i=A.i, f=A.f, j=A.j))
415 self.assertEqual(traits, dict(i=A.i, f=A.f, j=A.j))
416
416
417 def test_init(self):
417 def test_init(self):
418 class A(HasTraits):
418 class A(HasTraits):
419 i = Int()
419 i = Int()
420 x = Float()
420 x = Float()
421 a = A(i=1, x=10.0)
421 a = A(i=1, x=10.0)
422 self.assertEqual(a.i, 1)
422 self.assertEqual(a.i, 1)
423 self.assertEqual(a.x, 10.0)
423 self.assertEqual(a.x, 10.0)
424
424
425 def test_positional_args(self):
425 def test_positional_args(self):
426 class A(HasTraits):
426 class A(HasTraits):
427 i = Int(0)
427 i = Int(0)
428 def __init__(self, i):
428 def __init__(self, i):
429 super(A, self).__init__()
429 super(A, self).__init__()
430 self.i = i
430 self.i = i
431
431
432 a = A(5)
432 a = A(5)
433 self.assertEqual(a.i, 5)
433 self.assertEqual(a.i, 5)
434 # should raise TypeError if no positional arg given
434 # should raise TypeError if no positional arg given
435 self.assertRaises(TypeError, A)
435 self.assertRaises(TypeError, A)
436
436
437 #-----------------------------------------------------------------------------
437 #-----------------------------------------------------------------------------
438 # Tests for specific trait types
438 # Tests for specific trait types
439 #-----------------------------------------------------------------------------
439 #-----------------------------------------------------------------------------
440
440
441
441
442 class TestType(TestCase):
442 class TestType(TestCase):
443
443
444 def test_default(self):
444 def test_default(self):
445
445
446 class B(object): pass
446 class B(object): pass
447 class A(HasTraits):
447 class A(HasTraits):
448 klass = Type
448 klass = Type
449
449
450 a = A()
450 a = A()
451 self.assertEqual(a.klass, None)
451 self.assertEqual(a.klass, None)
452
452
453 a.klass = B
453 a.klass = B
454 self.assertEqual(a.klass, B)
454 self.assertEqual(a.klass, B)
455 self.assertRaises(TraitError, setattr, a, 'klass', 10)
455 self.assertRaises(TraitError, setattr, a, 'klass', 10)
456
456
457 def test_value(self):
457 def test_value(self):
458
458
459 class B(object): pass
459 class B(object): pass
460 class C(object): pass
460 class C(object): pass
461 class A(HasTraits):
461 class A(HasTraits):
462 klass = Type(B)
462 klass = Type(B)
463
463
464 a = A()
464 a = A()
465 self.assertEqual(a.klass, B)
465 self.assertEqual(a.klass, B)
466 self.assertRaises(TraitError, setattr, a, 'klass', C)
466 self.assertRaises(TraitError, setattr, a, 'klass', C)
467 self.assertRaises(TraitError, setattr, a, 'klass', object)
467 self.assertRaises(TraitError, setattr, a, 'klass', object)
468 a.klass = B
468 a.klass = B
469
469
470 def test_allow_none(self):
470 def test_allow_none(self):
471
471
472 class B(object): pass
472 class B(object): pass
473 class C(B): pass
473 class C(B): pass
474 class A(HasTraits):
474 class A(HasTraits):
475 klass = Type(B, allow_none=False)
475 klass = Type(B, allow_none=False)
476
476
477 a = A()
477 a = A()
478 self.assertEqual(a.klass, B)
478 self.assertEqual(a.klass, B)
479 self.assertRaises(TraitError, setattr, a, 'klass', None)
479 self.assertRaises(TraitError, setattr, a, 'klass', None)
480 a.klass = C
480 a.klass = C
481 self.assertEqual(a.klass, C)
481 self.assertEqual(a.klass, C)
482
482
483 def test_validate_klass(self):
483 def test_validate_klass(self):
484
484
485 class A(HasTraits):
485 class A(HasTraits):
486 klass = Type('no strings allowed')
486 klass = Type('no strings allowed')
487
487
488 self.assertRaises(ImportError, A)
488 self.assertRaises(ImportError, A)
489
489
490 class A(HasTraits):
490 class A(HasTraits):
491 klass = Type('rub.adub.Duck')
491 klass = Type('rub.adub.Duck')
492
492
493 self.assertRaises(ImportError, A)
493 self.assertRaises(ImportError, A)
494
494
495 def test_validate_default(self):
495 def test_validate_default(self):
496
496
497 class B(object): pass
497 class B(object): pass
498 class A(HasTraits):
498 class A(HasTraits):
499 klass = Type('bad default', B)
499 klass = Type('bad default', B)
500
500
501 self.assertRaises(ImportError, A)
501 self.assertRaises(ImportError, A)
502
502
503 class C(HasTraits):
503 class C(HasTraits):
504 klass = Type(None, B, allow_none=False)
504 klass = Type(None, B, allow_none=False)
505
505
506 self.assertRaises(TraitError, C)
506 self.assertRaises(TraitError, C)
507
507
508 def test_str_klass(self):
508 def test_str_klass(self):
509
509
510 class A(HasTraits):
510 class A(HasTraits):
511 klass = Type('IPython.utils.ipstruct.Struct')
511 klass = Type('IPython.utils.ipstruct.Struct')
512
512
513 from IPython.utils.ipstruct import Struct
513 from IPython.utils.ipstruct import Struct
514 a = A()
514 a = A()
515 a.klass = Struct
515 a.klass = Struct
516 self.assertEqual(a.klass, Struct)
516 self.assertEqual(a.klass, Struct)
517
517
518 self.assertRaises(TraitError, setattr, a, 'klass', 10)
518 self.assertRaises(TraitError, setattr, a, 'klass', 10)
519
519
520 def test_set_str_klass(self):
520 def test_set_str_klass(self):
521
521
522 class A(HasTraits):
522 class A(HasTraits):
523 klass = Type()
523 klass = Type()
524
524
525 a = A(klass='IPython.utils.ipstruct.Struct')
525 a = A(klass='IPython.utils.ipstruct.Struct')
526 from IPython.utils.ipstruct import Struct
526 from IPython.utils.ipstruct import Struct
527 self.assertEqual(a.klass, Struct)
527 self.assertEqual(a.klass, Struct)
528
528
529 class TestInstance(TestCase):
529 class TestInstance(TestCase):
530
530
531 def test_basic(self):
531 def test_basic(self):
532 class Foo(object): pass
532 class Foo(object): pass
533 class Bar(Foo): pass
533 class Bar(Foo): pass
534 class Bah(object): pass
534 class Bah(object): pass
535
535
536 class A(HasTraits):
536 class A(HasTraits):
537 inst = Instance(Foo)
537 inst = Instance(Foo)
538
538
539 a = A()
539 a = A()
540 self.assertTrue(a.inst is None)
540 self.assertTrue(a.inst is None)
541 a.inst = Foo()
541 a.inst = Foo()
542 self.assertTrue(isinstance(a.inst, Foo))
542 self.assertTrue(isinstance(a.inst, Foo))
543 a.inst = Bar()
543 a.inst = Bar()
544 self.assertTrue(isinstance(a.inst, Foo))
544 self.assertTrue(isinstance(a.inst, Foo))
545 self.assertRaises(TraitError, setattr, a, 'inst', Foo)
545 self.assertRaises(TraitError, setattr, a, 'inst', Foo)
546 self.assertRaises(TraitError, setattr, a, 'inst', Bar)
546 self.assertRaises(TraitError, setattr, a, 'inst', Bar)
547 self.assertRaises(TraitError, setattr, a, 'inst', Bah())
547 self.assertRaises(TraitError, setattr, a, 'inst', Bah())
548
548
549 def test_default_klass(self):
549 def test_default_klass(self):
550 class Foo(object): pass
550 class Foo(object): pass
551 class Bar(Foo): pass
551 class Bar(Foo): pass
552 class Bah(object): pass
552 class Bah(object): pass
553
553
554 class FooInstance(Instance):
554 class FooInstance(Instance):
555 klass = Foo
555 klass = Foo
556
556
557 class A(HasTraits):
557 class A(HasTraits):
558 inst = FooInstance()
558 inst = FooInstance()
559
559
560 a = A()
560 a = A()
561 self.assertTrue(a.inst is None)
561 self.assertTrue(a.inst is None)
562 a.inst = Foo()
562 a.inst = Foo()
563 self.assertTrue(isinstance(a.inst, Foo))
563 self.assertTrue(isinstance(a.inst, Foo))
564 a.inst = Bar()
564 a.inst = Bar()
565 self.assertTrue(isinstance(a.inst, Foo))
565 self.assertTrue(isinstance(a.inst, Foo))
566 self.assertRaises(TraitError, setattr, a, 'inst', Foo)
566 self.assertRaises(TraitError, setattr, a, 'inst', Foo)
567 self.assertRaises(TraitError, setattr, a, 'inst', Bar)
567 self.assertRaises(TraitError, setattr, a, 'inst', Bar)
568 self.assertRaises(TraitError, setattr, a, 'inst', Bah())
568 self.assertRaises(TraitError, setattr, a, 'inst', Bah())
569
569
570 def test_unique_default_value(self):
570 def test_unique_default_value(self):
571 class Foo(object): pass
571 class Foo(object): pass
572 class A(HasTraits):
572 class A(HasTraits):
573 inst = Instance(Foo,(),{})
573 inst = Instance(Foo,(),{})
574
574
575 a = A()
575 a = A()
576 b = A()
576 b = A()
577 self.assertTrue(a.inst is not b.inst)
577 self.assertTrue(a.inst is not b.inst)
578
578
579 def test_args_kw(self):
579 def test_args_kw(self):
580 class Foo(object):
580 class Foo(object):
581 def __init__(self, c): self.c = c
581 def __init__(self, c): self.c = c
582 class Bar(object): pass
582 class Bar(object): pass
583 class Bah(object):
583 class Bah(object):
584 def __init__(self, c, d):
584 def __init__(self, c, d):
585 self.c = c; self.d = d
585 self.c = c; self.d = d
586
586
587 class A(HasTraits):
587 class A(HasTraits):
588 inst = Instance(Foo, (10,))
588 inst = Instance(Foo, (10,))
589 a = A()
589 a = A()
590 self.assertEqual(a.inst.c, 10)
590 self.assertEqual(a.inst.c, 10)
591
591
592 class B(HasTraits):
592 class B(HasTraits):
593 inst = Instance(Bah, args=(10,), kw=dict(d=20))
593 inst = Instance(Bah, args=(10,), kw=dict(d=20))
594 b = B()
594 b = B()
595 self.assertEqual(b.inst.c, 10)
595 self.assertEqual(b.inst.c, 10)
596 self.assertEqual(b.inst.d, 20)
596 self.assertEqual(b.inst.d, 20)
597
597
598 class C(HasTraits):
598 class C(HasTraits):
599 inst = Instance(Foo)
599 inst = Instance(Foo)
600 c = C()
600 c = C()
601 self.assertTrue(c.inst is None)
601 self.assertTrue(c.inst is None)
602
602
603 def test_bad_default(self):
603 def test_bad_default(self):
604 class Foo(object): pass
604 class Foo(object): pass
605
605
606 class A(HasTraits):
606 class A(HasTraits):
607 inst = Instance(Foo, allow_none=False)
607 inst = Instance(Foo, allow_none=False)
608
608
609 self.assertRaises(TraitError, A)
609 self.assertRaises(TraitError, A)
610
610
611 def test_instance(self):
611 def test_instance(self):
612 class Foo(object): pass
612 class Foo(object): pass
613
613
614 def inner():
614 def inner():
615 class A(HasTraits):
615 class A(HasTraits):
616 inst = Instance(Foo())
616 inst = Instance(Foo())
617
617
618 self.assertRaises(TraitError, inner)
618 self.assertRaises(TraitError, inner)
619
619
620
620
621 class TestThis(TestCase):
621 class TestThis(TestCase):
622
622
623 def test_this_class(self):
623 def test_this_class(self):
624 class Foo(HasTraits):
624 class Foo(HasTraits):
625 this = This
625 this = This
626
626
627 f = Foo()
627 f = Foo()
628 self.assertEqual(f.this, None)
628 self.assertEqual(f.this, None)
629 g = Foo()
629 g = Foo()
630 f.this = g
630 f.this = g
631 self.assertEqual(f.this, g)
631 self.assertEqual(f.this, g)
632 self.assertRaises(TraitError, setattr, f, 'this', 10)
632 self.assertRaises(TraitError, setattr, f, 'this', 10)
633
633
634 def test_this_inst(self):
634 def test_this_inst(self):
635 class Foo(HasTraits):
635 class Foo(HasTraits):
636 this = This()
636 this = This()
637
637
638 f = Foo()
638 f = Foo()
639 f.this = Foo()
639 f.this = Foo()
640 self.assertTrue(isinstance(f.this, Foo))
640 self.assertTrue(isinstance(f.this, Foo))
641
641
642 def test_subclass(self):
642 def test_subclass(self):
643 class Foo(HasTraits):
643 class Foo(HasTraits):
644 t = This()
644 t = This()
645 class Bar(Foo):
645 class Bar(Foo):
646 pass
646 pass
647 f = Foo()
647 f = Foo()
648 b = Bar()
648 b = Bar()
649 f.t = b
649 f.t = b
650 b.t = f
650 b.t = f
651 self.assertEqual(f.t, b)
651 self.assertEqual(f.t, b)
652 self.assertEqual(b.t, f)
652 self.assertEqual(b.t, f)
653
653
654 def test_subclass_override(self):
654 def test_subclass_override(self):
655 class Foo(HasTraits):
655 class Foo(HasTraits):
656 t = This()
656 t = This()
657 class Bar(Foo):
657 class Bar(Foo):
658 t = This()
658 t = This()
659 f = Foo()
659 f = Foo()
660 b = Bar()
660 b = Bar()
661 f.t = b
661 f.t = b
662 self.assertEqual(f.t, b)
662 self.assertEqual(f.t, b)
663 self.assertRaises(TraitError, setattr, b, 't', f)
663 self.assertRaises(TraitError, setattr, b, 't', f)
664
664
665 def test_this_in_container(self):
665 def test_this_in_container(self):
666
666
667 class Tree(HasTraits):
667 class Tree(HasTraits):
668 value = Unicode()
668 value = Unicode()
669 leaves = List(This())
669 leaves = List(This())
670
670
671 tree = Tree(
671 tree = Tree(
672 value='foo',
672 value='foo',
673 leaves=[Tree('bar'), Tree('buzz')]
673 leaves=[Tree('bar'), Tree('buzz')]
674 )
674 )
675
675
676 with self.assertRaises(TraitError):
676 with self.assertRaises(TraitError):
677 tree.leaves = [1, 2]
677 tree.leaves = [1, 2]
678
678
679 class TraitTestBase(TestCase):
679 class TraitTestBase(TestCase):
680 """A best testing class for basic trait types."""
680 """A best testing class for basic trait types."""
681
681
682 def assign(self, value):
682 def assign(self, value):
683 self.obj.value = value
683 self.obj.value = value
684
684
685 def coerce(self, value):
685 def coerce(self, value):
686 return value
686 return value
687
687
688 def test_good_values(self):
688 def test_good_values(self):
689 if hasattr(self, '_good_values'):
689 if hasattr(self, '_good_values'):
690 for value in self._good_values:
690 for value in self._good_values:
691 self.assign(value)
691 self.assign(value)
692 self.assertEqual(self.obj.value, self.coerce(value))
692 self.assertEqual(self.obj.value, self.coerce(value))
693
693
694 def test_bad_values(self):
694 def test_bad_values(self):
695 if hasattr(self, '_bad_values'):
695 if hasattr(self, '_bad_values'):
696 for value in self._bad_values:
696 for value in self._bad_values:
697 try:
697 try:
698 self.assertRaises(TraitError, self.assign, value)
698 self.assertRaises(TraitError, self.assign, value)
699 except AssertionError:
699 except AssertionError:
700 assert False, value
700 assert False, value
701
701
702 def test_default_value(self):
702 def test_default_value(self):
703 if hasattr(self, '_default_value'):
703 if hasattr(self, '_default_value'):
704 self.assertEqual(self._default_value, self.obj.value)
704 self.assertEqual(self._default_value, self.obj.value)
705
705
706 def test_allow_none(self):
706 def test_allow_none(self):
707 if (hasattr(self, '_bad_values') and hasattr(self, '_good_values') and
707 if (hasattr(self, '_bad_values') and hasattr(self, '_good_values') and
708 None in self._bad_values):
708 None in self._bad_values):
709 trait=self.obj.traits()['value']
709 trait=self.obj.traits()['value']
710 try:
710 try:
711 trait.allow_none = True
711 trait.allow_none = True
712 self._bad_values.remove(None)
712 self._bad_values.remove(None)
713 #skip coerce. Allow None casts None to None.
713 #skip coerce. Allow None casts None to None.
714 self.assign(None)
714 self.assign(None)
715 self.assertEqual(self.obj.value,None)
715 self.assertEqual(self.obj.value,None)
716 self.test_good_values()
716 self.test_good_values()
717 self.test_bad_values()
717 self.test_bad_values()
718 finally:
718 finally:
719 #tear down
719 #tear down
720 trait.allow_none = False
720 trait.allow_none = False
721 self._bad_values.append(None)
721 self._bad_values.append(None)
722
722
723 def tearDown(self):
723 def tearDown(self):
724 # restore default value after tests, if set
724 # restore default value after tests, if set
725 if hasattr(self, '_default_value'):
725 if hasattr(self, '_default_value'):
726 self.obj.value = self._default_value
726 self.obj.value = self._default_value
727
727
728
728
729 class AnyTrait(HasTraits):
729 class AnyTrait(HasTraits):
730
730
731 value = Any
731 value = Any
732
732
733 class AnyTraitTest(TraitTestBase):
733 class AnyTraitTest(TraitTestBase):
734
734
735 obj = AnyTrait()
735 obj = AnyTrait()
736
736
737 _default_value = None
737 _default_value = None
738 _good_values = [10.0, 'ten', u'ten', [10], {'ten': 10},(10,), None, 1j]
738 _good_values = [10.0, 'ten', u'ten', [10], {'ten': 10},(10,), None, 1j]
739 _bad_values = []
739 _bad_values = []
740
740
741 class UnionTrait(HasTraits):
741 class UnionTrait(HasTraits):
742
742
743 value = Union([Type(), Bool()])
743 value = Union([Type(), Bool()])
744
744
745 class UnionTraitTest(TraitTestBase):
745 class UnionTraitTest(TraitTestBase):
746
746
747 obj = UnionTrait(value='IPython.utils.ipstruct.Struct')
747 obj = UnionTrait(value='IPython.utils.ipstruct.Struct')
748 _good_values = [int, float, True]
748 _good_values = [int, float, True]
749 _bad_values = [[], (0,), 1j]
749 _bad_values = [[], (0,), 1j]
750
750
751 class OrTrait(HasTraits):
751 class OrTrait(HasTraits):
752
752
753 value = Bool() | Unicode()
753 value = Bool() | Unicode()
754
754
755 class OrTraitTest(TraitTestBase):
755 class OrTraitTest(TraitTestBase):
756
756
757 obj = OrTrait()
757 obj = OrTrait()
758 _good_values = [True, False, 'ten']
758 _good_values = [True, False, 'ten']
759 _bad_values = [[], (0,), 1j]
759 _bad_values = [[], (0,), 1j]
760
760
761 class IntTrait(HasTraits):
761 class IntTrait(HasTraits):
762
762
763 value = Int(99)
763 value = Int(99)
764
764
765 class TestInt(TraitTestBase):
765 class TestInt(TraitTestBase):
766
766
767 obj = IntTrait()
767 obj = IntTrait()
768 _default_value = 99
768 _default_value = 99
769 _good_values = [10, -10]
769 _good_values = [10, -10]
770 _bad_values = ['ten', u'ten', [10], {'ten': 10},(10,), None, 1j,
770 _bad_values = ['ten', u'ten', [10], {'ten': 10},(10,), None, 1j,
771 10.1, -10.1, '10L', '-10L', '10.1', '-10.1', u'10L',
771 10.1, -10.1, '10L', '-10L', '10.1', '-10.1', u'10L',
772 u'-10L', u'10.1', u'-10.1', '10', '-10', u'10', u'-10']
772 u'-10L', u'10.1', u'-10.1', '10', '-10', u'10', u'-10']
773 if not py3compat.PY3:
773 if not py3compat.PY3:
774 _bad_values.extend([long(10), long(-10), 10*sys.maxint, -10*sys.maxint])
774 _bad_values.extend([long(10), long(-10), 10*sys.maxint, -10*sys.maxint])
775
775
776
776
777 class LongTrait(HasTraits):
777 class LongTrait(HasTraits):
778
778
779 value = Long(99 if py3compat.PY3 else long(99))
779 value = Long(99 if py3compat.PY3 else long(99))
780
780
781 class TestLong(TraitTestBase):
781 class TestLong(TraitTestBase):
782
782
783 obj = LongTrait()
783 obj = LongTrait()
784
784
785 _default_value = 99 if py3compat.PY3 else long(99)
785 _default_value = 99 if py3compat.PY3 else long(99)
786 _good_values = [10, -10]
786 _good_values = [10, -10]
787 _bad_values = ['ten', u'ten', [10], {'ten': 10},(10,),
787 _bad_values = ['ten', u'ten', [10], {'ten': 10},(10,),
788 None, 1j, 10.1, -10.1, '10', '-10', '10L', '-10L', '10.1',
788 None, 1j, 10.1, -10.1, '10', '-10', '10L', '-10L', '10.1',
789 '-10.1', u'10', u'-10', u'10L', u'-10L', u'10.1',
789 '-10.1', u'10', u'-10', u'10L', u'-10L', u'10.1',
790 u'-10.1']
790 u'-10.1']
791 if not py3compat.PY3:
791 if not py3compat.PY3:
792 # maxint undefined on py3, because int == long
792 # maxint undefined on py3, because int == long
793 _good_values.extend([long(10), long(-10), 10*sys.maxint, -10*sys.maxint])
793 _good_values.extend([long(10), long(-10), 10*sys.maxint, -10*sys.maxint])
794 _bad_values.extend([[long(10)], (long(10),)])
794 _bad_values.extend([[long(10)], (long(10),)])
795
795
796 @skipif(py3compat.PY3, "not relevant on py3")
796 @skipif(py3compat.PY3, "not relevant on py3")
797 def test_cast_small(self):
797 def test_cast_small(self):
798 """Long casts ints to long"""
798 """Long casts ints to long"""
799 self.obj.value = 10
799 self.obj.value = 10
800 self.assertEqual(type(self.obj.value), long)
800 self.assertEqual(type(self.obj.value), long)
801
801
802
802
803 class IntegerTrait(HasTraits):
803 class IntegerTrait(HasTraits):
804 value = Integer(1)
804 value = Integer(1)
805
805
806 class TestInteger(TestLong):
806 class TestInteger(TestLong):
807 obj = IntegerTrait()
807 obj = IntegerTrait()
808 _default_value = 1
808 _default_value = 1
809
809
810 def coerce(self, n):
810 def coerce(self, n):
811 return int(n)
811 return int(n)
812
812
813 @skipif(py3compat.PY3, "not relevant on py3")
813 @skipif(py3compat.PY3, "not relevant on py3")
814 def test_cast_small(self):
814 def test_cast_small(self):
815 """Integer casts small longs to int"""
815 """Integer casts small longs to int"""
816 if py3compat.PY3:
816 if py3compat.PY3:
817 raise SkipTest("not relevant on py3")
817 raise SkipTest("not relevant on py3")
818
818
819 self.obj.value = long(100)
819 self.obj.value = long(100)
820 self.assertEqual(type(self.obj.value), int)
820 self.assertEqual(type(self.obj.value), int)
821
821
822
822
823 class FloatTrait(HasTraits):
823 class FloatTrait(HasTraits):
824
824
825 value = Float(99.0)
825 value = Float(99.0)
826
826
827 class TestFloat(TraitTestBase):
827 class TestFloat(TraitTestBase):
828
828
829 obj = FloatTrait()
829 obj = FloatTrait()
830
830
831 _default_value = 99.0
831 _default_value = 99.0
832 _good_values = [10, -10, 10.1, -10.1]
832 _good_values = [10, -10, 10.1, -10.1]
833 _bad_values = ['ten', u'ten', [10], {'ten': 10},(10,), None,
833 _bad_values = ['ten', u'ten', [10], {'ten': 10},(10,), None,
834 1j, '10', '-10', '10L', '-10L', '10.1', '-10.1', u'10',
834 1j, '10', '-10', '10L', '-10L', '10.1', '-10.1', u'10',
835 u'-10', u'10L', u'-10L', u'10.1', u'-10.1']
835 u'-10', u'10L', u'-10L', u'10.1', u'-10.1']
836 if not py3compat.PY3:
836 if not py3compat.PY3:
837 _bad_values.extend([long(10), long(-10)])
837 _bad_values.extend([long(10), long(-10)])
838
838
839
839
840 class ComplexTrait(HasTraits):
840 class ComplexTrait(HasTraits):
841
841
842 value = Complex(99.0-99.0j)
842 value = Complex(99.0-99.0j)
843
843
844 class TestComplex(TraitTestBase):
844 class TestComplex(TraitTestBase):
845
845
846 obj = ComplexTrait()
846 obj = ComplexTrait()
847
847
848 _default_value = 99.0-99.0j
848 _default_value = 99.0-99.0j
849 _good_values = [10, -10, 10.1, -10.1, 10j, 10+10j, 10-10j,
849 _good_values = [10, -10, 10.1, -10.1, 10j, 10+10j, 10-10j,
850 10.1j, 10.1+10.1j, 10.1-10.1j]
850 10.1j, 10.1+10.1j, 10.1-10.1j]
851 _bad_values = [u'10L', u'-10L', 'ten', [10], {'ten': 10},(10,), None]
851 _bad_values = [u'10L', u'-10L', 'ten', [10], {'ten': 10},(10,), None]
852 if not py3compat.PY3:
852 if not py3compat.PY3:
853 _bad_values.extend([long(10), long(-10)])
853 _bad_values.extend([long(10), long(-10)])
854
854
855
855
856 class BytesTrait(HasTraits):
856 class BytesTrait(HasTraits):
857
857
858 value = Bytes(b'string')
858 value = Bytes(b'string')
859
859
860 class TestBytes(TraitTestBase):
860 class TestBytes(TraitTestBase):
861
861
862 obj = BytesTrait()
862 obj = BytesTrait()
863
863
864 _default_value = b'string'
864 _default_value = b'string'
865 _good_values = [b'10', b'-10', b'10L',
865 _good_values = [b'10', b'-10', b'10L',
866 b'-10L', b'10.1', b'-10.1', b'string']
866 b'-10L', b'10.1', b'-10.1', b'string']
867 _bad_values = [10, -10, 10.1, -10.1, 1j, [10],
867 _bad_values = [10, -10, 10.1, -10.1, 1j, [10],
868 ['ten'],{'ten': 10},(10,), None, u'string']
868 ['ten'],{'ten': 10},(10,), None, u'string']
869 if not py3compat.PY3:
869 if not py3compat.PY3:
870 _bad_values.extend([long(10), long(-10)])
870 _bad_values.extend([long(10), long(-10)])
871
871
872
872
873 class UnicodeTrait(HasTraits):
873 class UnicodeTrait(HasTraits):
874
874
875 value = Unicode(u'unicode')
875 value = Unicode(u'unicode')
876
876
877 class TestUnicode(TraitTestBase):
877 class TestUnicode(TraitTestBase):
878
878
879 obj = UnicodeTrait()
879 obj = UnicodeTrait()
880
880
881 _default_value = u'unicode'
881 _default_value = u'unicode'
882 _good_values = ['10', '-10', '10L', '-10L', '10.1',
882 _good_values = ['10', '-10', '10L', '-10L', '10.1',
883 '-10.1', '', u'', 'string', u'string', u"€"]
883 '-10.1', '', u'', 'string', u'string', u"€"]
884 _bad_values = [10, -10, 10.1, -10.1, 1j,
884 _bad_values = [10, -10, 10.1, -10.1, 1j,
885 [10], ['ten'], [u'ten'], {'ten': 10},(10,), None]
885 [10], ['ten'], [u'ten'], {'ten': 10},(10,), None]
886 if not py3compat.PY3:
886 if not py3compat.PY3:
887 _bad_values.extend([long(10), long(-10)])
887 _bad_values.extend([long(10), long(-10)])
888
888
889
889
890 class ObjectNameTrait(HasTraits):
890 class ObjectNameTrait(HasTraits):
891 value = ObjectName("abc")
891 value = ObjectName("abc")
892
892
893 class TestObjectName(TraitTestBase):
893 class TestObjectName(TraitTestBase):
894 obj = ObjectNameTrait()
894 obj = ObjectNameTrait()
895
895
896 _default_value = "abc"
896 _default_value = "abc"
897 _good_values = ["a", "gh", "g9", "g_", "_G", u"a345_"]
897 _good_values = ["a", "gh", "g9", "g_", "_G", u"a345_"]
898 _bad_values = [1, "", u"€", "9g", "!", "#abc", "aj@", "a.b", "a()", "a[0]",
898 _bad_values = [1, "", u"€", "9g", "!", "#abc", "aj@", "a.b", "a()", "a[0]",
899 None, object(), object]
899 None, object(), object]
900 if sys.version_info[0] < 3:
900 if sys.version_info[0] < 3:
901 _bad_values.append(u"þ")
901 _bad_values.append(u"þ")
902 else:
902 else:
903 _good_values.append(u"þ") # þ=1 is valid in Python 3 (PEP 3131).
903 _good_values.append(u"þ") # þ=1 is valid in Python 3 (PEP 3131).
904
904
905
905
906 class DottedObjectNameTrait(HasTraits):
906 class DottedObjectNameTrait(HasTraits):
907 value = DottedObjectName("a.b")
907 value = DottedObjectName("a.b")
908
908
909 class TestDottedObjectName(TraitTestBase):
909 class TestDottedObjectName(TraitTestBase):
910 obj = DottedObjectNameTrait()
910 obj = DottedObjectNameTrait()
911
911
912 _default_value = "a.b"
912 _default_value = "a.b"
913 _good_values = ["A", "y.t", "y765.__repr__", "os.path.join", u"os.path.join"]
913 _good_values = ["A", "y.t", "y765.__repr__", "os.path.join", u"os.path.join"]
914 _bad_values = [1, u"abc.€", "_.@", ".", ".abc", "abc.", ".abc.", None]
914 _bad_values = [1, u"abc.€", "_.@", ".", ".abc", "abc.", ".abc.", None]
915 if sys.version_info[0] < 3:
915 if sys.version_info[0] < 3:
916 _bad_values.append(u"t.þ")
916 _bad_values.append(u"t.þ")
917 else:
917 else:
918 _good_values.append(u"t.þ")
918 _good_values.append(u"t.þ")
919
919
920
920
921 class TCPAddressTrait(HasTraits):
921 class TCPAddressTrait(HasTraits):
922 value = TCPAddress()
922 value = TCPAddress()
923
923
924 class TestTCPAddress(TraitTestBase):
924 class TestTCPAddress(TraitTestBase):
925
925
926 obj = TCPAddressTrait()
926 obj = TCPAddressTrait()
927
927
928 _default_value = ('127.0.0.1',0)
928 _default_value = ('127.0.0.1',0)
929 _good_values = [('localhost',0),('192.168.0.1',1000),('www.google.com',80)]
929 _good_values = [('localhost',0),('192.168.0.1',1000),('www.google.com',80)]
930 _bad_values = [(0,0),('localhost',10.0),('localhost',-1), None]
930 _bad_values = [(0,0),('localhost',10.0),('localhost',-1), None]
931
931
932 class ListTrait(HasTraits):
932 class ListTrait(HasTraits):
933
933
934 value = List(Int)
934 value = List(Int)
935
935
936 class TestList(TraitTestBase):
936 class TestList(TraitTestBase):
937
937
938 obj = ListTrait()
938 obj = ListTrait()
939
939
940 _default_value = []
940 _default_value = []
941 _good_values = [[], [1], list(range(10)), (1,2)]
941 _good_values = [[], [1], list(range(10)), (1,2)]
942 _bad_values = [10, [1,'a'], 'a']
942 _bad_values = [10, [1,'a'], 'a']
943
943
944 def coerce(self, value):
944 def coerce(self, value):
945 if value is not None:
945 if value is not None:
946 value = list(value)
946 value = list(value)
947 return value
947 return value
948
948
949 class Foo(object):
949 class Foo(object):
950 pass
950 pass
951
951
952 class NoneInstanceListTrait(HasTraits):
952 class NoneInstanceListTrait(HasTraits):
953
953
954 value = List(Instance(Foo, allow_none=False))
954 value = List(Instance(Foo, allow_none=False))
955
955
956 class TestNoneInstanceList(TraitTestBase):
956 class TestNoneInstanceList(TraitTestBase):
957
957
958 obj = NoneInstanceListTrait()
958 obj = NoneInstanceListTrait()
959
959
960 _default_value = []
960 _default_value = []
961 _good_values = [[Foo(), Foo()], []]
961 _good_values = [[Foo(), Foo()], []]
962 _bad_values = [[None], [Foo(), None]]
962 _bad_values = [[None], [Foo(), None]]
963
963
964
964
965 class InstanceListTrait(HasTraits):
965 class InstanceListTrait(HasTraits):
966
966
967 value = List(Instance(__name__+'.Foo'))
967 value = List(Instance(__name__+'.Foo'))
968
968
969 class TestInstanceList(TraitTestBase):
969 class TestInstanceList(TraitTestBase):
970
970
971 obj = InstanceListTrait()
971 obj = InstanceListTrait()
972
972
973 def test_klass(self):
973 def test_klass(self):
974 """Test that the instance klass is properly assigned."""
974 """Test that the instance klass is properly assigned."""
975 self.assertIs(self.obj.traits()['value']._trait.klass, Foo)
975 self.assertIs(self.obj.traits()['value']._trait.klass, Foo)
976
976
977 _default_value = []
977 _default_value = []
978 _good_values = [[Foo(), Foo(), None], []]
978 _good_values = [[Foo(), Foo(), None], []]
979 _bad_values = [['1', 2,], '1', [Foo], None]
979 _bad_values = [['1', 2,], '1', [Foo], None]
980
980
981 class UnionListTrait(HasTraits):
981 class UnionListTrait(HasTraits):
982
982
983 value = List(Int() | Bool())
983 value = List(Int() | Bool())
984
984
985 class TestUnionListTrait(HasTraits):
985 class TestUnionListTrait(HasTraits):
986
986
987 obj = UnionListTrait()
987 obj = UnionListTrait()
988
988
989 _default_value = []
989 _default_value = []
990 _good_values = [[True, 1], [False, True]]
990 _good_values = [[True, 1], [False, True]]
991 _bad_values = [[1, 'True'], False]
991 _bad_values = [[1, 'True'], False]
992
992
993
993
994 class LenListTrait(HasTraits):
994 class LenListTrait(HasTraits):
995
995
996 value = List(Int, [0], minlen=1, maxlen=2)
996 value = List(Int, [0], minlen=1, maxlen=2)
997
997
998 class TestLenList(TraitTestBase):
998 class TestLenList(TraitTestBase):
999
999
1000 obj = LenListTrait()
1000 obj = LenListTrait()
1001
1001
1002 _default_value = [0]
1002 _default_value = [0]
1003 _good_values = [[1], [1,2], (1,2)]
1003 _good_values = [[1], [1,2], (1,2)]
1004 _bad_values = [10, [1,'a'], 'a', [], list(range(3))]
1004 _bad_values = [10, [1,'a'], 'a', [], list(range(3))]
1005
1005
1006 def coerce(self, value):
1006 def coerce(self, value):
1007 if value is not None:
1007 if value is not None:
1008 value = list(value)
1008 value = list(value)
1009 return value
1009 return value
1010
1010
1011 class TupleTrait(HasTraits):
1011 class TupleTrait(HasTraits):
1012
1012
1013 value = Tuple(Int(allow_none=True))
1013 value = Tuple(Int(allow_none=True))
1014
1014
1015 class TestTupleTrait(TraitTestBase):
1015 class TestTupleTrait(TraitTestBase):
1016
1016
1017 obj = TupleTrait()
1017 obj = TupleTrait()
1018
1018
1019 _default_value = None
1019 _default_value = None
1020 _good_values = [(1,), None, (0,), [1], (None,)]
1020 _good_values = [(1,), None, (0,), [1], (None,)]
1021 _bad_values = [10, (1,2), ('a'), ()]
1021 _bad_values = [10, (1,2), ('a'), ()]
1022
1022
1023 def coerce(self, value):
1023 def coerce(self, value):
1024 if value is not None:
1024 if value is not None:
1025 value = tuple(value)
1025 value = tuple(value)
1026 return value
1026 return value
1027
1027
1028 def test_invalid_args(self):
1028 def test_invalid_args(self):
1029 self.assertRaises(TypeError, Tuple, 5)
1029 self.assertRaises(TypeError, Tuple, 5)
1030 self.assertRaises(TypeError, Tuple, default_value='hello')
1030 self.assertRaises(TypeError, Tuple, default_value='hello')
1031 t = Tuple(Int, CBytes, default_value=(1,5))
1031 t = Tuple(Int, CBytes, default_value=(1,5))
1032
1032
1033 class LooseTupleTrait(HasTraits):
1033 class LooseTupleTrait(HasTraits):
1034
1034
1035 value = Tuple((1,2,3))
1035 value = Tuple((1,2,3))
1036
1036
1037 class TestLooseTupleTrait(TraitTestBase):
1037 class TestLooseTupleTrait(TraitTestBase):
1038
1038
1039 obj = LooseTupleTrait()
1039 obj = LooseTupleTrait()
1040
1040
1041 _default_value = (1,2,3)
1041 _default_value = (1,2,3)
1042 _good_values = [(1,), None, [1], (0,), tuple(range(5)), tuple('hello'), ('a',5), ()]
1042 _good_values = [(1,), None, [1], (0,), tuple(range(5)), tuple('hello'), ('a',5), ()]
1043 _bad_values = [10, 'hello', {}]
1043 _bad_values = [10, 'hello', {}]
1044
1044
1045 def coerce(self, value):
1045 def coerce(self, value):
1046 if value is not None:
1046 if value is not None:
1047 value = tuple(value)
1047 value = tuple(value)
1048 return value
1048 return value
1049
1049
1050 def test_invalid_args(self):
1050 def test_invalid_args(self):
1051 self.assertRaises(TypeError, Tuple, 5)
1051 self.assertRaises(TypeError, Tuple, 5)
1052 self.assertRaises(TypeError, Tuple, default_value='hello')
1052 self.assertRaises(TypeError, Tuple, default_value='hello')
1053 t = Tuple(Int, CBytes, default_value=(1,5))
1053 t = Tuple(Int, CBytes, default_value=(1,5))
1054
1054
1055
1055
1056 class MultiTupleTrait(HasTraits):
1056 class MultiTupleTrait(HasTraits):
1057
1057
1058 value = Tuple(Int, Bytes, default_value=[99,b'bottles'])
1058 value = Tuple(Int, Bytes, default_value=[99,b'bottles'])
1059
1059
1060 class TestMultiTuple(TraitTestBase):
1060 class TestMultiTuple(TraitTestBase):
1061
1061
1062 obj = MultiTupleTrait()
1062 obj = MultiTupleTrait()
1063
1063
1064 _default_value = (99,b'bottles')
1064 _default_value = (99,b'bottles')
1065 _good_values = [(1,b'a'), (2,b'b')]
1065 _good_values = [(1,b'a'), (2,b'b')]
1066 _bad_values = ((),10, b'a', (1,b'a',3), (b'a',1), (1, u'a'))
1066 _bad_values = ((),10, b'a', (1,b'a',3), (b'a',1), (1, u'a'))
1067
1067
1068 class CRegExpTrait(HasTraits):
1068 class CRegExpTrait(HasTraits):
1069
1069
1070 value = CRegExp(r'')
1070 value = CRegExp(r'')
1071
1071
1072 class TestCRegExp(TraitTestBase):
1072 class TestCRegExp(TraitTestBase):
1073
1073
1074 def coerce(self, value):
1074 def coerce(self, value):
1075 return re.compile(value)
1075 return re.compile(value)
1076
1076
1077 obj = CRegExpTrait()
1077 obj = CRegExpTrait()
1078
1078
1079 _default_value = re.compile(r'')
1079 _default_value = re.compile(r'')
1080 _good_values = [r'\d+', re.compile(r'\d+')]
1080 _good_values = [r'\d+', re.compile(r'\d+')]
1081 _bad_values = ['(', None, ()]
1081 _bad_values = ['(', None, ()]
1082
1082
1083 class DictTrait(HasTraits):
1083 class DictTrait(HasTraits):
1084 value = Dict()
1084 value = Dict()
1085
1085
1086 def test_dict_assignment():
1086 def test_dict_assignment():
1087 d = dict()
1087 d = dict()
1088 c = DictTrait()
1088 c = DictTrait()
1089 c.value = d
1089 c.value = d
1090 d['a'] = 5
1090 d['a'] = 5
1091 nt.assert_equal(d, c.value)
1091 nt.assert_equal(d, c.value)
1092 nt.assert_true(c.value is d)
1092 nt.assert_true(c.value is d)
1093
1093
1094 class ValidatedDictTrait(HasTraits):
1094 class ValidatedDictTrait(HasTraits):
1095
1095
1096 value = Dict(Unicode())
1096 value = Dict(Unicode())
1097
1097
1098 class TestInstanceDict(TraitTestBase):
1098 class TestInstanceDict(TraitTestBase):
1099
1099
1100 obj = ValidatedDictTrait()
1100 obj = ValidatedDictTrait()
1101
1101
1102 _default_value = {}
1102 _default_value = {}
1103 _good_values = [{'0': 'foo'}, {'1': 'bar'}]
1103 _good_values = [{'0': 'foo'}, {'1': 'bar'}]
1104 _bad_values = [{'0': 0}, {'1': 1}]
1104 _bad_values = [{'0': 0}, {'1': 1}]
1105
1105
1106
1106
1107 def test_dict_default_value():
1107 def test_dict_default_value():
1108 """Check that the `{}` default value of the Dict traitlet constructor is
1108 """Check that the `{}` default value of the Dict traitlet constructor is
1109 actually copied."""
1109 actually copied."""
1110
1110
1111 d1, d2 = Dict(), Dict()
1111 d1, d2 = Dict(), Dict()
1112 nt.assert_false(d1.get_default_value() is d2.get_default_value())
1112 nt.assert_false(d1.get_default_value() is d2.get_default_value())
1113
1113
1114
1114
1115 class TestValidationHook(TestCase):
1115 class TestValidationHook(TestCase):
1116
1116
1117 def test_parity_trait(self):
1117 def test_parity_trait(self):
1118 """Verify that the early validation hook is effective"""
1118 """Verify that the early validation hook is effective"""
1119
1119
1120 class Parity(HasTraits):
1120 class Parity(HasTraits):
1121
1121
1122 value = Int(0)
1122 value = Int(0)
1123 parity = Enum(['odd', 'even'], default_value='even', allow_none=False)
1123 parity = Enum(['odd', 'even'], default_value='even', allow_none=False)
1124
1124
1125 def _value_validate(self, value, trait):
1125 def _value_validate(self, value, trait):
1126 if self.parity == 'even' and value % 2:
1126 if self.parity == 'even' and value % 2:
1127 raise TraitError('Expected an even number')
1127 raise TraitError('Expected an even number')
1128 if self.parity == 'odd' and (value % 2 == 0):
1128 if self.parity == 'odd' and (value % 2 == 0):
1129 raise TraitError('Expected an odd number')
1129 raise TraitError('Expected an odd number')
1130 return value
1130 return value
1131
1131
1132 u = Parity()
1132 u = Parity()
1133 u.parity = 'odd'
1133 u.parity = 'odd'
1134 u.value = 1 # OK
1134 u.value = 1 # OK
1135 with self.assertRaises(TraitError):
1135 with self.assertRaises(TraitError):
1136 u.value = 2 # Trait Error
1136 u.value = 2 # Trait Error
1137
1137
1138 u.parity = 'even'
1138 u.parity = 'even'
1139 u.value = 2 # OK
1139 u.value = 2 # OK
1140
1140
1141
1141
1142 class TestLink(TestCase):
1142 class TestLink(TestCase):
1143
1143
1144 def test_connect_same(self):
1144 def test_connect_same(self):
1145 """Verify two traitlets of the same type can be linked together using link."""
1145 """Verify two traitlets of the same type can be linked together using link."""
1146
1146
1147 # Create two simple classes with Int traitlets.
1147 # Create two simple classes with Int traitlets.
1148 class A(HasTraits):
1148 class A(HasTraits):
1149 value = Int()
1149 value = Int()
1150 a = A(value=9)
1150 a = A(value=9)
1151 b = A(value=8)
1151 b = A(value=8)
1152
1152
1153 # Conenct the two classes.
1153 # Conenct the two classes.
1154 c = link((a, 'value'), (b, 'value'))
1154 c = link((a, 'value'), (b, 'value'))
1155
1155
1156 # Make sure the values are the same at the point of linking.
1156 # Make sure the values are the same at the point of linking.
1157 self.assertEqual(a.value, b.value)
1157 self.assertEqual(a.value, b.value)
1158
1158
1159 # Change one of the values to make sure they stay in sync.
1159 # Change one of the values to make sure they stay in sync.
1160 a.value = 5
1160 a.value = 5
1161 self.assertEqual(a.value, b.value)
1161 self.assertEqual(a.value, b.value)
1162 b.value = 6
1162 b.value = 6
1163 self.assertEqual(a.value, b.value)
1163 self.assertEqual(a.value, b.value)
1164
1164
1165 def test_link_different(self):
1165 def test_link_different(self):
1166 """Verify two traitlets of different types can be linked together using link."""
1166 """Verify two traitlets of different types can be linked together using link."""
1167
1167
1168 # Create two simple classes with Int traitlets.
1168 # Create two simple classes with Int traitlets.
1169 class A(HasTraits):
1169 class A(HasTraits):
1170 value = Int()
1170 value = Int()
1171 class B(HasTraits):
1171 class B(HasTraits):
1172 count = Int()
1172 count = Int()
1173 a = A(value=9)
1173 a = A(value=9)
1174 b = B(count=8)
1174 b = B(count=8)
1175
1175
1176 # Conenct the two classes.
1176 # Conenct the two classes.
1177 c = link((a, 'value'), (b, 'count'))
1177 c = link((a, 'value'), (b, 'count'))
1178
1178
1179 # Make sure the values are the same at the point of linking.
1179 # Make sure the values are the same at the point of linking.
1180 self.assertEqual(a.value, b.count)
1180 self.assertEqual(a.value, b.count)
1181
1181
1182 # Change one of the values to make sure they stay in sync.
1182 # Change one of the values to make sure they stay in sync.
1183 a.value = 5
1183 a.value = 5
1184 self.assertEqual(a.value, b.count)
1184 self.assertEqual(a.value, b.count)
1185 b.count = 4
1185 b.count = 4
1186 self.assertEqual(a.value, b.count)
1186 self.assertEqual(a.value, b.count)
1187
1187
1188 def test_unlink(self):
1188 def test_unlink(self):
1189 """Verify two linked traitlets can be unlinked."""
1189 """Verify two linked traitlets can be unlinked."""
1190
1190
1191 # Create two simple classes with Int traitlets.
1191 # Create two simple classes with Int traitlets.
1192 class A(HasTraits):
1192 class A(HasTraits):
1193 value = Int()
1193 value = Int()
1194 a = A(value=9)
1194 a = A(value=9)
1195 b = A(value=8)
1195 b = A(value=8)
1196
1196
1197 # Connect the two classes.
1197 # Connect the two classes.
1198 c = link((a, 'value'), (b, 'value'))
1198 c = link((a, 'value'), (b, 'value'))
1199 a.value = 4
1199 a.value = 4
1200 c.unlink()
1200 c.unlink()
1201
1201
1202 # Change one of the values to make sure they don't stay in sync.
1202 # Change one of the values to make sure they don't stay in sync.
1203 a.value = 5
1203 a.value = 5
1204 self.assertNotEqual(a.value, b.value)
1204 self.assertNotEqual(a.value, b.value)
1205
1205
1206 def test_callbacks(self):
1206 def test_callbacks(self):
1207 """Verify two linked traitlets have their callbacks called once."""
1207 """Verify two linked traitlets have their callbacks called once."""
1208
1208
1209 # Create two simple classes with Int traitlets.
1209 # Create two simple classes with Int traitlets.
1210 class A(HasTraits):
1210 class A(HasTraits):
1211 value = Int()
1211 value = Int()
1212 class B(HasTraits):
1212 class B(HasTraits):
1213 count = Int()
1213 count = Int()
1214 a = A(value=9)
1214 a = A(value=9)
1215 b = B(count=8)
1215 b = B(count=8)
1216
1216
1217 # Register callbacks that count.
1217 # Register callbacks that count.
1218 callback_count = []
1218 callback_count = []
1219 def a_callback(name, old, new):
1219 def a_callback(name, old, new):
1220 callback_count.append('a')
1220 callback_count.append('a')
1221 a.on_trait_change(a_callback, 'value')
1221 a.on_trait_change(a_callback, 'value')
1222 def b_callback(name, old, new):
1222 def b_callback(name, old, new):
1223 callback_count.append('b')
1223 callback_count.append('b')
1224 b.on_trait_change(b_callback, 'count')
1224 b.on_trait_change(b_callback, 'count')
1225
1225
1226 # Connect the two classes.
1226 # Connect the two classes.
1227 c = link((a, 'value'), (b, 'count'))
1227 c = link((a, 'value'), (b, 'count'))
1228
1228
1229 # Make sure b's count was set to a's value once.
1229 # Make sure b's count was set to a's value once.
1230 self.assertEqual(''.join(callback_count), 'b')
1230 self.assertEqual(''.join(callback_count), 'b')
1231 del callback_count[:]
1231 del callback_count[:]
1232
1232
1233 # Make sure a's value was set to b's count once.
1233 # Make sure a's value was set to b's count once.
1234 b.count = 5
1234 b.count = 5
1235 self.assertEqual(''.join(callback_count), 'ba')
1235 self.assertEqual(''.join(callback_count), 'ba')
1236 del callback_count[:]
1236 del callback_count[:]
1237
1237
1238 # Make sure b's count was set to a's value once.
1238 # Make sure b's count was set to a's value once.
1239 a.value = 4
1239 a.value = 4
1240 self.assertEqual(''.join(callback_count), 'ab')
1240 self.assertEqual(''.join(callback_count), 'ab')
1241 del callback_count[:]
1241 del callback_count[:]
1242
1242
1243 class TestDirectionalLink(TestCase):
1243 class TestDirectionalLink(TestCase):
1244 def test_connect_same(self):
1244 def test_connect_same(self):
1245 """Verify two traitlets of the same type can be linked together using directional_link."""
1245 """Verify two traitlets of the same type can be linked together using directional_link."""
1246
1246
1247 # Create two simple classes with Int traitlets.
1247 # Create two simple classes with Int traitlets.
1248 class A(HasTraits):
1248 class A(HasTraits):
1249 value = Int()
1249 value = Int()
1250 a = A(value=9)
1250 a = A(value=9)
1251 b = A(value=8)
1251 b = A(value=8)
1252
1252
1253 # Conenct the two classes.
1253 # Conenct the two classes.
1254 c = directional_link((a, 'value'), (b, 'value'))
1254 c = directional_link((a, 'value'), (b, 'value'))
1255
1255
1256 # Make sure the values are the same at the point of linking.
1256 # Make sure the values are the same at the point of linking.
1257 self.assertEqual(a.value, b.value)
1257 self.assertEqual(a.value, b.value)
1258
1258
1259 # Change one the value of the source and check that it synchronizes the target.
1259 # Change one the value of the source and check that it synchronizes the target.
1260 a.value = 5
1260 a.value = 5
1261 self.assertEqual(b.value, 5)
1261 self.assertEqual(b.value, 5)
1262 # Change one the value of the target and check that it has no impact on the source
1262 # Change one the value of the target and check that it has no impact on the source
1263 b.value = 6
1263 b.value = 6
1264 self.assertEqual(a.value, 5)
1264 self.assertEqual(a.value, 5)
1265
1265
1266 def test_link_different(self):
1266 def test_link_different(self):
1267 """Verify two traitlets of different types can be linked together using link."""
1267 """Verify two traitlets of different types can be linked together using link."""
1268
1268
1269 # Create two simple classes with Int traitlets.
1269 # Create two simple classes with Int traitlets.
1270 class A(HasTraits):
1270 class A(HasTraits):
1271 value = Int()
1271 value = Int()
1272 class B(HasTraits):
1272 class B(HasTraits):
1273 count = Int()
1273 count = Int()
1274 a = A(value=9)
1274 a = A(value=9)
1275 b = B(count=8)
1275 b = B(count=8)
1276
1276
1277 # Conenct the two classes.
1277 # Conenct the two classes.
1278 c = directional_link((a, 'value'), (b, 'count'))
1278 c = directional_link((a, 'value'), (b, 'count'))
1279
1279
1280 # Make sure the values are the same at the point of linking.
1280 # Make sure the values are the same at the point of linking.
1281 self.assertEqual(a.value, b.count)
1281 self.assertEqual(a.value, b.count)
1282
1282
1283 # Change one the value of the source and check that it synchronizes the target.
1283 # Change one the value of the source and check that it synchronizes the target.
1284 a.value = 5
1284 a.value = 5
1285 self.assertEqual(b.count, 5)
1285 self.assertEqual(b.count, 5)
1286 # Change one the value of the target and check that it has no impact on the source
1286 # Change one the value of the target and check that it has no impact on the source
1287 b.value = 6
1287 b.value = 6
1288 self.assertEqual(a.value, 5)
1288 self.assertEqual(a.value, 5)
1289
1289
1290 def test_unlink(self):
1290 def test_unlink(self):
1291 """Verify two linked traitlets can be unlinked."""
1291 """Verify two linked traitlets can be unlinked."""
1292
1292
1293 # Create two simple classes with Int traitlets.
1293 # Create two simple classes with Int traitlets.
1294 class A(HasTraits):
1294 class A(HasTraits):
1295 value = Int()
1295 value = Int()
1296 a = A(value=9)
1296 a = A(value=9)
1297 b = A(value=8)
1297 b = A(value=8)
1298
1298
1299 # Connect the two classes.
1299 # Connect the two classes.
1300 c = directional_link((a, 'value'), (b, 'value'))
1300 c = directional_link((a, 'value'), (b, 'value'))
1301 a.value = 4
1301 a.value = 4
1302 c.unlink()
1302 c.unlink()
1303
1303
1304 # Change one of the values to make sure they don't stay in sync.
1304 # Change one of the values to make sure they don't stay in sync.
1305 a.value = 5
1305 a.value = 5
1306 self.assertNotEqual(a.value, b.value)
1306 self.assertNotEqual(a.value, b.value)
1307
1307
1308 class Pickleable(HasTraits):
1308 class Pickleable(HasTraits):
1309 i = Int()
1309 i = Int()
1310 j = Int()
1310 j = Int()
1311
1311
1312 def _i_default(self):
1312 def _i_default(self):
1313 return 1
1313 return 1
1314
1314
1315 def _i_changed(self, name, old, new):
1315 def _i_changed(self, name, old, new):
1316 self.j = new
1316 self.j = new
1317
1317
1318 def test_pickle_hastraits():
1318 def test_pickle_hastraits():
1319 c = Pickleable()
1319 c = Pickleable()
1320 for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
1320 for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
1321 p = pickle.dumps(c, protocol)
1321 p = pickle.dumps(c, protocol)
1322 c2 = pickle.loads(p)
1322 c2 = pickle.loads(p)
1323 nt.assert_equal(c2.i, c.i)
1323 nt.assert_equal(c2.i, c.i)
1324 nt.assert_equal(c2.j, c.j)
1324 nt.assert_equal(c2.j, c.j)
1325
1325
1326 c.i = 5
1326 c.i = 5
1327 for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
1327 for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
1328 p = pickle.dumps(c, protocol)
1328 p = pickle.dumps(c, protocol)
1329 c2 = pickle.loads(p)
1329 c2 = pickle.loads(p)
1330 nt.assert_equal(c2.i, c.i)
1330 nt.assert_equal(c2.i, c.i)
1331 nt.assert_equal(c2.j, c.j)
1331 nt.assert_equal(c2.j, c.j)
1332
1332
1333
1334 class OrderTraits(HasTraits):
1335 notified = Dict()
1336
1337 a = Unicode()
1338 b = Unicode()
1339 c = Unicode()
1340 d = Unicode()
1341 e = Unicode()
1342 f = Unicode()
1343 g = Unicode()
1344 h = Unicode()
1345 i = Unicode()
1346 j = Unicode()
1347 k = Unicode()
1348 l = Unicode()
1349
1350 def _notify(self, name, old, new):
1351 """check the value of all traits when each trait change is triggered
1352
1353 This verifies that the values are not sensitive
1354 to dict ordering when loaded from kwargs
1355 """
1356 # check the value of the other traits
1357 # when a given trait change notification fires
1358 self.notified[name] = {
1359 c: getattr(self, c) for c in 'abcdefghijkl'
1360 }
1361
1362 def __init__(self, **kwargs):
1363 self.on_trait_change(self._notify)
1364 super(OrderTraits, self).__init__(**kwargs)
1365
1366 def test_notification_order():
1367 d = {c:c for c in 'abcdefghijkl'}
1368 obj = OrderTraits()
1369 nt.assert_equal(obj.notified, {})
1370 obj = OrderTraits(**d)
1371 notifications = {
1372 c: d for c in 'abcdefghijkl'
1373 }
1374 nt.assert_equal(obj.notified, notifications)
1375
1376
1333 class TestEventful(TestCase):
1377 class TestEventful(TestCase):
1334
1378
1335 def test_list(self):
1379 def test_list(self):
1336 """Does the EventfulList work?"""
1380 """Does the EventfulList work?"""
1337 event_cache = []
1381 event_cache = []
1338
1382
1339 class A(HasTraits):
1383 class A(HasTraits):
1340 x = EventfulList([c for c in 'abc'])
1384 x = EventfulList([c for c in 'abc'])
1341 a = A()
1385 a = A()
1342 a.x.on_events(lambda i, x: event_cache.append('insert'), \
1386 a.x.on_events(lambda i, x: event_cache.append('insert'), \
1343 lambda i, x: event_cache.append('set'), \
1387 lambda i, x: event_cache.append('set'), \
1344 lambda i: event_cache.append('del'), \
1388 lambda i: event_cache.append('del'), \
1345 lambda: event_cache.append('reverse'), \
1389 lambda: event_cache.append('reverse'), \
1346 lambda *p, **k: event_cache.append('sort'))
1390 lambda *p, **k: event_cache.append('sort'))
1347
1391
1348 a.x.remove('c')
1392 a.x.remove('c')
1349 # ab
1393 # ab
1350 a.x.insert(0, 'z')
1394 a.x.insert(0, 'z')
1351 # zab
1395 # zab
1352 del a.x[1]
1396 del a.x[1]
1353 # zb
1397 # zb
1354 a.x.reverse()
1398 a.x.reverse()
1355 # bz
1399 # bz
1356 a.x[1] = 'o'
1400 a.x[1] = 'o'
1357 # bo
1401 # bo
1358 a.x.append('a')
1402 a.x.append('a')
1359 # boa
1403 # boa
1360 a.x.sort()
1404 a.x.sort()
1361 # abo
1405 # abo
1362
1406
1363 # Were the correct events captured?
1407 # Were the correct events captured?
1364 self.assertEqual(event_cache, ['del', 'insert', 'del', 'reverse', 'set', 'set', 'sort'])
1408 self.assertEqual(event_cache, ['del', 'insert', 'del', 'reverse', 'set', 'set', 'sort'])
1365
1409
1366 # Is the output correct?
1410 # Is the output correct?
1367 self.assertEqual(a.x, [c for c in 'abo'])
1411 self.assertEqual(a.x, [c for c in 'abo'])
1368
1412
1369 def test_dict(self):
1413 def test_dict(self):
1370 """Does the EventfulDict work?"""
1414 """Does the EventfulDict work?"""
1371 event_cache = []
1415 event_cache = []
1372
1416
1373 class A(HasTraits):
1417 class A(HasTraits):
1374 x = EventfulDict({c: c for c in 'abc'})
1418 x = EventfulDict({c: c for c in 'abc'})
1375 a = A()
1419 a = A()
1376 a.x.on_events(lambda k, v: event_cache.append('add'), \
1420 a.x.on_events(lambda k, v: event_cache.append('add'), \
1377 lambda k, v: event_cache.append('set'), \
1421 lambda k, v: event_cache.append('set'), \
1378 lambda k: event_cache.append('del'))
1422 lambda k: event_cache.append('del'))
1379
1423
1380 del a.x['c']
1424 del a.x['c']
1381 # ab
1425 # ab
1382 a.x['z'] = 1
1426 a.x['z'] = 1
1383 # abz
1427 # abz
1384 a.x['z'] = 'z'
1428 a.x['z'] = 'z'
1385 # abz
1429 # abz
1386 a.x.pop('a')
1430 a.x.pop('a')
1387 # bz
1431 # bz
1388
1432
1389 # Were the correct events captured?
1433 # Were the correct events captured?
1390 self.assertEqual(event_cache, ['del', 'add', 'set', 'del'])
1434 self.assertEqual(event_cache, ['del', 'add', 'set', 'del'])
1391
1435
1392 # Is the output correct?
1436 # Is the output correct?
1393 self.assertEqual(a.x, {c: c for c in 'bz'})
1437 self.assertEqual(a.x, {c: c for c in 'bz'})
1394
1438
1395 ###
1439 ###
1396 # Traits for Forward Declaration Tests
1440 # Traits for Forward Declaration Tests
1397 ###
1441 ###
1398 class ForwardDeclaredInstanceTrait(HasTraits):
1442 class ForwardDeclaredInstanceTrait(HasTraits):
1399
1443
1400 value = ForwardDeclaredInstance('ForwardDeclaredBar')
1444 value = ForwardDeclaredInstance('ForwardDeclaredBar')
1401
1445
1402 class ForwardDeclaredTypeTrait(HasTraits):
1446 class ForwardDeclaredTypeTrait(HasTraits):
1403
1447
1404 value = ForwardDeclaredType('ForwardDeclaredBar')
1448 value = ForwardDeclaredType('ForwardDeclaredBar')
1405
1449
1406 class ForwardDeclaredInstanceListTrait(HasTraits):
1450 class ForwardDeclaredInstanceListTrait(HasTraits):
1407
1451
1408 value = List(ForwardDeclaredInstance('ForwardDeclaredBar'))
1452 value = List(ForwardDeclaredInstance('ForwardDeclaredBar'))
1409
1453
1410 class ForwardDeclaredTypeListTrait(HasTraits):
1454 class ForwardDeclaredTypeListTrait(HasTraits):
1411
1455
1412 value = List(ForwardDeclaredType('ForwardDeclaredBar'))
1456 value = List(ForwardDeclaredType('ForwardDeclaredBar'))
1413 ###
1457 ###
1414 # End Traits for Forward Declaration Tests
1458 # End Traits for Forward Declaration Tests
1415 ###
1459 ###
1416
1460
1417 ###
1461 ###
1418 # Classes for Forward Declaration Tests
1462 # Classes for Forward Declaration Tests
1419 ###
1463 ###
1420 class ForwardDeclaredBar(object):
1464 class ForwardDeclaredBar(object):
1421 pass
1465 pass
1422
1466
1423 class ForwardDeclaredBarSub(ForwardDeclaredBar):
1467 class ForwardDeclaredBarSub(ForwardDeclaredBar):
1424 pass
1468 pass
1425 ###
1469 ###
1426 # End Classes for Forward Declaration Tests
1470 # End Classes for Forward Declaration Tests
1427 ###
1471 ###
1428
1472
1429 ###
1473 ###
1430 # Forward Declaration Tests
1474 # Forward Declaration Tests
1431 ###
1475 ###
1432 class TestForwardDeclaredInstanceTrait(TraitTestBase):
1476 class TestForwardDeclaredInstanceTrait(TraitTestBase):
1433
1477
1434 obj = ForwardDeclaredInstanceTrait()
1478 obj = ForwardDeclaredInstanceTrait()
1435 _default_value = None
1479 _default_value = None
1436 _good_values = [None, ForwardDeclaredBar(), ForwardDeclaredBarSub()]
1480 _good_values = [None, ForwardDeclaredBar(), ForwardDeclaredBarSub()]
1437 _bad_values = ['foo', 3, ForwardDeclaredBar, ForwardDeclaredBarSub]
1481 _bad_values = ['foo', 3, ForwardDeclaredBar, ForwardDeclaredBarSub]
1438
1482
1439 class TestForwardDeclaredTypeTrait(TraitTestBase):
1483 class TestForwardDeclaredTypeTrait(TraitTestBase):
1440
1484
1441 obj = ForwardDeclaredTypeTrait()
1485 obj = ForwardDeclaredTypeTrait()
1442 _default_value = None
1486 _default_value = None
1443 _good_values = [None, ForwardDeclaredBar, ForwardDeclaredBarSub]
1487 _good_values = [None, ForwardDeclaredBar, ForwardDeclaredBarSub]
1444 _bad_values = ['foo', 3, ForwardDeclaredBar(), ForwardDeclaredBarSub()]
1488 _bad_values = ['foo', 3, ForwardDeclaredBar(), ForwardDeclaredBarSub()]
1445
1489
1446 class TestForwardDeclaredInstanceList(TraitTestBase):
1490 class TestForwardDeclaredInstanceList(TraitTestBase):
1447
1491
1448 obj = ForwardDeclaredInstanceListTrait()
1492 obj = ForwardDeclaredInstanceListTrait()
1449
1493
1450 def test_klass(self):
1494 def test_klass(self):
1451 """Test that the instance klass is properly assigned."""
1495 """Test that the instance klass is properly assigned."""
1452 self.assertIs(self.obj.traits()['value']._trait.klass, ForwardDeclaredBar)
1496 self.assertIs(self.obj.traits()['value']._trait.klass, ForwardDeclaredBar)
1453
1497
1454 _default_value = []
1498 _default_value = []
1455 _good_values = [
1499 _good_values = [
1456 [ForwardDeclaredBar(), ForwardDeclaredBarSub(), None],
1500 [ForwardDeclaredBar(), ForwardDeclaredBarSub(), None],
1457 [None],
1501 [None],
1458 [],
1502 [],
1459 ]
1503 ]
1460 _bad_values = [
1504 _bad_values = [
1461 ForwardDeclaredBar(),
1505 ForwardDeclaredBar(),
1462 [ForwardDeclaredBar(), 3],
1506 [ForwardDeclaredBar(), 3],
1463 '1',
1507 '1',
1464 # Note that this is the type, not an instance.
1508 # Note that this is the type, not an instance.
1465 [ForwardDeclaredBar],
1509 [ForwardDeclaredBar],
1466 None,
1510 None,
1467 ]
1511 ]
1468
1512
1469 class TestForwardDeclaredTypeList(TraitTestBase):
1513 class TestForwardDeclaredTypeList(TraitTestBase):
1470
1514
1471 obj = ForwardDeclaredTypeListTrait()
1515 obj = ForwardDeclaredTypeListTrait()
1472
1516
1473 def test_klass(self):
1517 def test_klass(self):
1474 """Test that the instance klass is properly assigned."""
1518 """Test that the instance klass is properly assigned."""
1475 self.assertIs(self.obj.traits()['value']._trait.klass, ForwardDeclaredBar)
1519 self.assertIs(self.obj.traits()['value']._trait.klass, ForwardDeclaredBar)
1476
1520
1477 _default_value = []
1521 _default_value = []
1478 _good_values = [
1522 _good_values = [
1479 [ForwardDeclaredBar, ForwardDeclaredBarSub, None],
1523 [ForwardDeclaredBar, ForwardDeclaredBarSub, None],
1480 [],
1524 [],
1481 [None],
1525 [None],
1482 ]
1526 ]
1483 _bad_values = [
1527 _bad_values = [
1484 ForwardDeclaredBar,
1528 ForwardDeclaredBar,
1485 [ForwardDeclaredBar, 3],
1529 [ForwardDeclaredBar, 3],
1486 '1',
1530 '1',
1487 # Note that this is an instance, not the type.
1531 # Note that this is an instance, not the type.
1488 [ForwardDeclaredBar()],
1532 [ForwardDeclaredBar()],
1489 None,
1533 None,
1490 ]
1534 ]
1491 ###
1535 ###
1492 # End Forward Declaration Tests
1536 # End Forward Declaration Tests
1493 ###
1537 ###
@@ -1,1803 +1,1826 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 A lightweight Traits like module.
3 A lightweight Traits like module.
4
4
5 This is designed to provide a lightweight, simple, pure Python version of
5 This is designed to provide a lightweight, simple, pure Python version of
6 many of the capabilities of enthought.traits. This includes:
6 many of the capabilities of enthought.traits. This includes:
7
7
8 * Validation
8 * Validation
9 * Type specification with defaults
9 * Type specification with defaults
10 * Static and dynamic notification
10 * Static and dynamic notification
11 * Basic predefined types
11 * Basic predefined types
12 * An API that is similar to enthought.traits
12 * An API that is similar to enthought.traits
13
13
14 We don't support:
14 We don't support:
15
15
16 * Delegation
16 * Delegation
17 * Automatic GUI generation
17 * Automatic GUI generation
18 * A full set of trait types. Most importantly, we don't provide container
18 * A full set of trait types. Most importantly, we don't provide container
19 traits (list, dict, tuple) that can trigger notifications if their
19 traits (list, dict, tuple) that can trigger notifications if their
20 contents change.
20 contents change.
21 * API compatibility with enthought.traits
21 * API compatibility with enthought.traits
22
22
23 There are also some important difference in our design:
23 There are also some important difference in our design:
24
24
25 * enthought.traits does not validate default values. We do.
25 * enthought.traits does not validate default values. We do.
26
26
27 We choose to create this module because we need these capabilities, but
27 We choose to create this module because we need these capabilities, but
28 we need them to be pure Python so they work in all Python implementations,
28 we need them to be pure Python so they work in all Python implementations,
29 including Jython and IronPython.
29 including Jython and IronPython.
30
30
31 Inheritance diagram:
31 Inheritance diagram:
32
32
33 .. inheritance-diagram:: IPython.utils.traitlets
33 .. inheritance-diagram:: IPython.utils.traitlets
34 :parts: 3
34 :parts: 3
35 """
35 """
36
36
37 # Copyright (c) IPython Development Team.
37 # Copyright (c) IPython Development Team.
38 # Distributed under the terms of the Modified BSD License.
38 # Distributed under the terms of the Modified BSD License.
39 #
39 #
40 # Adapted from enthought.traits, Copyright (c) Enthought, Inc.,
40 # Adapted from enthought.traits, Copyright (c) Enthought, Inc.,
41 # also under the terms of the Modified BSD License.
41 # also under the terms of the Modified BSD License.
42
42
43 import contextlib
43 import contextlib
44 import inspect
44 import inspect
45 import re
45 import re
46 import sys
46 import sys
47 import types
47 import types
48 from types import FunctionType
48 from types import FunctionType
49 try:
49 try:
50 from types import ClassType, InstanceType
50 from types import ClassType, InstanceType
51 ClassTypes = (ClassType, type)
51 ClassTypes = (ClassType, type)
52 except:
52 except:
53 ClassTypes = (type,)
53 ClassTypes = (type,)
54 from warnings import warn
54 from warnings import warn
55
55
56 from .importstring import import_item
56 from .importstring import import_item
57 from IPython.utils import py3compat
57 from IPython.utils import py3compat
58 from IPython.utils import eventful
58 from IPython.utils import eventful
59 from IPython.utils.py3compat import iteritems, string_types
59 from IPython.utils.py3compat import iteritems, string_types
60 from IPython.testing.skipdoctest import skip_doctest
60 from IPython.testing.skipdoctest import skip_doctest
61
61
62 SequenceTypes = (list, tuple, set, frozenset)
62 SequenceTypes = (list, tuple, set, frozenset)
63
63
64 #-----------------------------------------------------------------------------
64 #-----------------------------------------------------------------------------
65 # Basic classes
65 # Basic classes
66 #-----------------------------------------------------------------------------
66 #-----------------------------------------------------------------------------
67
67
68
68
69 class NoDefaultSpecified ( object ): pass
69 class NoDefaultSpecified ( object ): pass
70 NoDefaultSpecified = NoDefaultSpecified()
70 NoDefaultSpecified = NoDefaultSpecified()
71
71
72
72
73 class Undefined ( object ): pass
73 class Undefined ( object ): pass
74 Undefined = Undefined()
74 Undefined = Undefined()
75
75
76 class TraitError(Exception):
76 class TraitError(Exception):
77 pass
77 pass
78
78
79 #-----------------------------------------------------------------------------
79 #-----------------------------------------------------------------------------
80 # Utilities
80 # Utilities
81 #-----------------------------------------------------------------------------
81 #-----------------------------------------------------------------------------
82
82
83
83
84 def class_of ( object ):
84 def class_of ( object ):
85 """ Returns a string containing the class name of an object with the
85 """ Returns a string containing the class name of an object with the
86 correct indefinite article ('a' or 'an') preceding it (e.g., 'an Image',
86 correct indefinite article ('a' or 'an') preceding it (e.g., 'an Image',
87 'a PlotValue').
87 'a PlotValue').
88 """
88 """
89 if isinstance( object, py3compat.string_types ):
89 if isinstance( object, py3compat.string_types ):
90 return add_article( object )
90 return add_article( object )
91
91
92 return add_article( object.__class__.__name__ )
92 return add_article( object.__class__.__name__ )
93
93
94
94
95 def add_article ( name ):
95 def add_article ( name ):
96 """ Returns a string containing the correct indefinite article ('a' or 'an')
96 """ Returns a string containing the correct indefinite article ('a' or 'an')
97 prefixed to the specified string.
97 prefixed to the specified string.
98 """
98 """
99 if name[:1].lower() in 'aeiou':
99 if name[:1].lower() in 'aeiou':
100 return 'an ' + name
100 return 'an ' + name
101
101
102 return 'a ' + name
102 return 'a ' + name
103
103
104
104
105 def repr_type(obj):
105 def repr_type(obj):
106 """ Return a string representation of a value and its type for readable
106 """ Return a string representation of a value and its type for readable
107 error messages.
107 error messages.
108 """
108 """
109 the_type = type(obj)
109 the_type = type(obj)
110 if (not py3compat.PY3) and the_type is InstanceType:
110 if (not py3compat.PY3) and the_type is InstanceType:
111 # Old-style class.
111 # Old-style class.
112 the_type = obj.__class__
112 the_type = obj.__class__
113 msg = '%r %r' % (obj, the_type)
113 msg = '%r %r' % (obj, the_type)
114 return msg
114 return msg
115
115
116
116
117 def is_trait(t):
117 def is_trait(t):
118 """ Returns whether the given value is an instance or subclass of TraitType.
118 """ Returns whether the given value is an instance or subclass of TraitType.
119 """
119 """
120 return (isinstance(t, TraitType) or
120 return (isinstance(t, TraitType) or
121 (isinstance(t, type) and issubclass(t, TraitType)))
121 (isinstance(t, type) and issubclass(t, TraitType)))
122
122
123
123
124 def parse_notifier_name(name):
124 def parse_notifier_name(name):
125 """Convert the name argument to a list of names.
125 """Convert the name argument to a list of names.
126
126
127 Examples
127 Examples
128 --------
128 --------
129
129
130 >>> parse_notifier_name('a')
130 >>> parse_notifier_name('a')
131 ['a']
131 ['a']
132 >>> parse_notifier_name(['a','b'])
132 >>> parse_notifier_name(['a','b'])
133 ['a', 'b']
133 ['a', 'b']
134 >>> parse_notifier_name(None)
134 >>> parse_notifier_name(None)
135 ['anytrait']
135 ['anytrait']
136 """
136 """
137 if isinstance(name, string_types):
137 if isinstance(name, string_types):
138 return [name]
138 return [name]
139 elif name is None:
139 elif name is None:
140 return ['anytrait']
140 return ['anytrait']
141 elif isinstance(name, (list, tuple)):
141 elif isinstance(name, (list, tuple)):
142 for n in name:
142 for n in name:
143 assert isinstance(n, string_types), "names must be strings"
143 assert isinstance(n, string_types), "names must be strings"
144 return name
144 return name
145
145
146
146
147 class _SimpleTest:
147 class _SimpleTest:
148 def __init__ ( self, value ): self.value = value
148 def __init__ ( self, value ): self.value = value
149 def __call__ ( self, test ):
149 def __call__ ( self, test ):
150 return test == self.value
150 return test == self.value
151 def __repr__(self):
151 def __repr__(self):
152 return "<SimpleTest(%r)" % self.value
152 return "<SimpleTest(%r)" % self.value
153 def __str__(self):
153 def __str__(self):
154 return self.__repr__()
154 return self.__repr__()
155
155
156
156
157 def getmembers(object, predicate=None):
157 def getmembers(object, predicate=None):
158 """A safe version of inspect.getmembers that handles missing attributes.
158 """A safe version of inspect.getmembers that handles missing attributes.
159
159
160 This is useful when there are descriptor based attributes that for
160 This is useful when there are descriptor based attributes that for
161 some reason raise AttributeError even though they exist. This happens
161 some reason raise AttributeError even though they exist. This happens
162 in zope.inteface with the __provides__ attribute.
162 in zope.inteface with the __provides__ attribute.
163 """
163 """
164 results = []
164 results = []
165 for key in dir(object):
165 for key in dir(object):
166 try:
166 try:
167 value = getattr(object, key)
167 value = getattr(object, key)
168 except AttributeError:
168 except AttributeError:
169 pass
169 pass
170 else:
170 else:
171 if not predicate or predicate(value):
171 if not predicate or predicate(value):
172 results.append((key, value))
172 results.append((key, value))
173 results.sort()
173 results.sort()
174 return results
174 return results
175
175
176 def _validate_link(*tuples):
176 def _validate_link(*tuples):
177 """Validate arguments for traitlet link functions"""
177 """Validate arguments for traitlet link functions"""
178 for t in tuples:
178 for t in tuples:
179 if not len(t) == 2:
179 if not len(t) == 2:
180 raise TypeError("Each linked traitlet must be specified as (HasTraits, 'trait_name'), not %r" % t)
180 raise TypeError("Each linked traitlet must be specified as (HasTraits, 'trait_name'), not %r" % t)
181 obj, trait_name = t
181 obj, trait_name = t
182 if not isinstance(obj, HasTraits):
182 if not isinstance(obj, HasTraits):
183 raise TypeError("Each object must be HasTraits, not %r" % type(obj))
183 raise TypeError("Each object must be HasTraits, not %r" % type(obj))
184 if not trait_name in obj.traits():
184 if not trait_name in obj.traits():
185 raise TypeError("%r has no trait %r" % (obj, trait_name))
185 raise TypeError("%r has no trait %r" % (obj, trait_name))
186
186
187 @skip_doctest
187 @skip_doctest
188 class link(object):
188 class link(object):
189 """Link traits from different objects together so they remain in sync.
189 """Link traits from different objects together so they remain in sync.
190
190
191 Parameters
191 Parameters
192 ----------
192 ----------
193 *args : pairs of objects/attributes
193 *args : pairs of objects/attributes
194
194
195 Examples
195 Examples
196 --------
196 --------
197
197
198 >>> c = link((obj1, 'value'), (obj2, 'value'), (obj3, 'value'))
198 >>> c = link((obj1, 'value'), (obj2, 'value'), (obj3, 'value'))
199 >>> obj1.value = 5 # updates other objects as well
199 >>> obj1.value = 5 # updates other objects as well
200 """
200 """
201 updating = False
201 updating = False
202 def __init__(self, *args):
202 def __init__(self, *args):
203 if len(args) < 2:
203 if len(args) < 2:
204 raise TypeError('At least two traitlets must be provided.')
204 raise TypeError('At least two traitlets must be provided.')
205 _validate_link(*args)
205 _validate_link(*args)
206
206
207 self.objects = {}
207 self.objects = {}
208
208
209 initial = getattr(args[0][0], args[0][1])
209 initial = getattr(args[0][0], args[0][1])
210 for obj, attr in args:
210 for obj, attr in args:
211 setattr(obj, attr, initial)
211 setattr(obj, attr, initial)
212
212
213 callback = self._make_closure(obj, attr)
213 callback = self._make_closure(obj, attr)
214 obj.on_trait_change(callback, attr)
214 obj.on_trait_change(callback, attr)
215 self.objects[(obj, attr)] = callback
215 self.objects[(obj, attr)] = callback
216
216
217 @contextlib.contextmanager
217 @contextlib.contextmanager
218 def _busy_updating(self):
218 def _busy_updating(self):
219 self.updating = True
219 self.updating = True
220 try:
220 try:
221 yield
221 yield
222 finally:
222 finally:
223 self.updating = False
223 self.updating = False
224
224
225 def _make_closure(self, sending_obj, sending_attr):
225 def _make_closure(self, sending_obj, sending_attr):
226 def update(name, old, new):
226 def update(name, old, new):
227 self._update(sending_obj, sending_attr, new)
227 self._update(sending_obj, sending_attr, new)
228 return update
228 return update
229
229
230 def _update(self, sending_obj, sending_attr, new):
230 def _update(self, sending_obj, sending_attr, new):
231 if self.updating:
231 if self.updating:
232 return
232 return
233 with self._busy_updating():
233 with self._busy_updating():
234 for obj, attr in self.objects.keys():
234 for obj, attr in self.objects.keys():
235 setattr(obj, attr, new)
235 setattr(obj, attr, new)
236
236
237 def unlink(self):
237 def unlink(self):
238 for key, callback in self.objects.items():
238 for key, callback in self.objects.items():
239 (obj, attr) = key
239 (obj, attr) = key
240 obj.on_trait_change(callback, attr, remove=True)
240 obj.on_trait_change(callback, attr, remove=True)
241
241
242 @skip_doctest
242 @skip_doctest
243 class directional_link(object):
243 class directional_link(object):
244 """Link the trait of a source object with traits of target objects.
244 """Link the trait of a source object with traits of target objects.
245
245
246 Parameters
246 Parameters
247 ----------
247 ----------
248 source : pair of object, name
248 source : pair of object, name
249 targets : pairs of objects/attributes
249 targets : pairs of objects/attributes
250
250
251 Examples
251 Examples
252 --------
252 --------
253
253
254 >>> c = directional_link((src, 'value'), (tgt1, 'value'), (tgt2, 'value'))
254 >>> c = directional_link((src, 'value'), (tgt1, 'value'), (tgt2, 'value'))
255 >>> src.value = 5 # updates target objects
255 >>> src.value = 5 # updates target objects
256 >>> tgt1.value = 6 # does not update other objects
256 >>> tgt1.value = 6 # does not update other objects
257 """
257 """
258 updating = False
258 updating = False
259
259
260 def __init__(self, source, *targets):
260 def __init__(self, source, *targets):
261 if len(targets) < 1:
261 if len(targets) < 1:
262 raise TypeError('At least two traitlets must be provided.')
262 raise TypeError('At least two traitlets must be provided.')
263 _validate_link(source, *targets)
263 _validate_link(source, *targets)
264 self.source = source
264 self.source = source
265 self.targets = targets
265 self.targets = targets
266
266
267 # Update current value
267 # Update current value
268 src_attr_value = getattr(source[0], source[1])
268 src_attr_value = getattr(source[0], source[1])
269 for obj, attr in targets:
269 for obj, attr in targets:
270 setattr(obj, attr, src_attr_value)
270 setattr(obj, attr, src_attr_value)
271
271
272 # Wire
272 # Wire
273 self.source[0].on_trait_change(self._update, self.source[1])
273 self.source[0].on_trait_change(self._update, self.source[1])
274
274
275 @contextlib.contextmanager
275 @contextlib.contextmanager
276 def _busy_updating(self):
276 def _busy_updating(self):
277 self.updating = True
277 self.updating = True
278 try:
278 try:
279 yield
279 yield
280 finally:
280 finally:
281 self.updating = False
281 self.updating = False
282
282
283 def _update(self, name, old, new):
283 def _update(self, name, old, new):
284 if self.updating:
284 if self.updating:
285 return
285 return
286 with self._busy_updating():
286 with self._busy_updating():
287 for obj, attr in self.targets:
287 for obj, attr in self.targets:
288 setattr(obj, attr, new)
288 setattr(obj, attr, new)
289
289
290 def unlink(self):
290 def unlink(self):
291 self.source[0].on_trait_change(self._update, self.source[1], remove=True)
291 self.source[0].on_trait_change(self._update, self.source[1], remove=True)
292 self.source = None
292 self.source = None
293 self.targets = []
293 self.targets = []
294
294
295 dlink = directional_link
295 dlink = directional_link
296
296
297 #-----------------------------------------------------------------------------
297 #-----------------------------------------------------------------------------
298 # Base TraitType for all traits
298 # Base TraitType for all traits
299 #-----------------------------------------------------------------------------
299 #-----------------------------------------------------------------------------
300
300
301
301
302 class TraitType(object):
302 class TraitType(object):
303 """A base class for all trait descriptors.
303 """A base class for all trait descriptors.
304
304
305 Notes
305 Notes
306 -----
306 -----
307 Our implementation of traits is based on Python's descriptor
307 Our implementation of traits is based on Python's descriptor
308 prototol. This class is the base class for all such descriptors. The
308 prototol. This class is the base class for all such descriptors. The
309 only magic we use is a custom metaclass for the main :class:`HasTraits`
309 only magic we use is a custom metaclass for the main :class:`HasTraits`
310 class that does the following:
310 class that does the following:
311
311
312 1. Sets the :attr:`name` attribute of every :class:`TraitType`
312 1. Sets the :attr:`name` attribute of every :class:`TraitType`
313 instance in the class dict to the name of the attribute.
313 instance in the class dict to the name of the attribute.
314 2. Sets the :attr:`this_class` attribute of every :class:`TraitType`
314 2. Sets the :attr:`this_class` attribute of every :class:`TraitType`
315 instance in the class dict to the *class* that declared the trait.
315 instance in the class dict to the *class* that declared the trait.
316 This is used by the :class:`This` trait to allow subclasses to
316 This is used by the :class:`This` trait to allow subclasses to
317 accept superclasses for :class:`This` values.
317 accept superclasses for :class:`This` values.
318 """
318 """
319
319
320
320
321 metadata = {}
321 metadata = {}
322 default_value = Undefined
322 default_value = Undefined
323 allow_none = False
323 allow_none = False
324 info_text = 'any value'
324 info_text = 'any value'
325
325
326 def __init__(self, default_value=NoDefaultSpecified, allow_none=None, **metadata):
326 def __init__(self, default_value=NoDefaultSpecified, allow_none=None, **metadata):
327 """Create a TraitType.
327 """Create a TraitType.
328 """
328 """
329 if default_value is not NoDefaultSpecified:
329 if default_value is not NoDefaultSpecified:
330 self.default_value = default_value
330 self.default_value = default_value
331 if allow_none is not None:
331 if allow_none is not None:
332 self.allow_none = allow_none
332 self.allow_none = allow_none
333
333
334 if 'default' in metadata:
334 if 'default' in metadata:
335 # Warn the user that they probably meant default_value.
335 # Warn the user that they probably meant default_value.
336 warn(
336 warn(
337 "Parameter 'default' passed to TraitType. "
337 "Parameter 'default' passed to TraitType. "
338 "Did you mean 'default_value'?"
338 "Did you mean 'default_value'?"
339 )
339 )
340
340
341 if len(metadata) > 0:
341 if len(metadata) > 0:
342 if len(self.metadata) > 0:
342 if len(self.metadata) > 0:
343 self._metadata = self.metadata.copy()
343 self._metadata = self.metadata.copy()
344 self._metadata.update(metadata)
344 self._metadata.update(metadata)
345 else:
345 else:
346 self._metadata = metadata
346 self._metadata = metadata
347 else:
347 else:
348 self._metadata = self.metadata
348 self._metadata = self.metadata
349
349
350 self.init()
350 self.init()
351
351
352 def init(self):
352 def init(self):
353 pass
353 pass
354
354
355 def get_default_value(self):
355 def get_default_value(self):
356 """Create a new instance of the default value."""
356 """Create a new instance of the default value."""
357 return self.default_value
357 return self.default_value
358
358
359 def instance_init(self):
359 def instance_init(self):
360 """Part of the initialization which may depends on the underlying
360 """Part of the initialization which may depends on the underlying
361 HasTraits instance.
361 HasTraits instance.
362
362
363 It is typically overloaded for specific trait types.
363 It is typically overloaded for specific trait types.
364
364
365 This method is called by :meth:`HasTraits.__new__` and in the
365 This method is called by :meth:`HasTraits.__new__` and in the
366 :meth:`TraitType.instance_init` method of trait types holding
366 :meth:`TraitType.instance_init` method of trait types holding
367 other trait types.
367 other trait types.
368 """
368 """
369 pass
369 pass
370
370
371 def init_default_value(self, obj):
371 def init_default_value(self, obj):
372 """Instantiate the default value for the trait type.
372 """Instantiate the default value for the trait type.
373
373
374 This method is called by :meth:`TraitType.set_default_value` in the
374 This method is called by :meth:`TraitType.set_default_value` in the
375 case a default value is provided at construction time or later when
375 case a default value is provided at construction time or later when
376 accessing the trait value for the first time in
376 accessing the trait value for the first time in
377 :meth:`HasTraits.__get__`.
377 :meth:`HasTraits.__get__`.
378 """
378 """
379 value = self.get_default_value()
379 value = self.get_default_value()
380 value = self._validate(obj, value)
380 value = self._validate(obj, value)
381 obj._trait_values[self.name] = value
381 obj._trait_values[self.name] = value
382 return value
382 return value
383
383
384 def set_default_value(self, obj):
384 def set_default_value(self, obj):
385 """Set the default value on a per instance basis.
385 """Set the default value on a per instance basis.
386
386
387 This method is called by :meth:`HasTraits.__new__` to instantiate and
387 This method is called by :meth:`HasTraits.__new__` to instantiate and
388 validate the default value. The creation and validation of
388 validate the default value. The creation and validation of
389 default values must be delayed until the parent :class:`HasTraits`
389 default values must be delayed until the parent :class:`HasTraits`
390 class has been instantiated.
390 class has been instantiated.
391 Parameters
391 Parameters
392 ----------
392 ----------
393 obj : :class:`HasTraits` instance
393 obj : :class:`HasTraits` instance
394 The parent :class:`HasTraits` instance that has just been
394 The parent :class:`HasTraits` instance that has just been
395 created.
395 created.
396 """
396 """
397 # Check for a deferred initializer defined in the same class as the
397 # Check for a deferred initializer defined in the same class as the
398 # trait declaration or above.
398 # trait declaration or above.
399 mro = type(obj).mro()
399 mro = type(obj).mro()
400 meth_name = '_%s_default' % self.name
400 meth_name = '_%s_default' % self.name
401 for cls in mro[:mro.index(self.this_class)+1]:
401 for cls in mro[:mro.index(self.this_class)+1]:
402 if meth_name in cls.__dict__:
402 if meth_name in cls.__dict__:
403 break
403 break
404 else:
404 else:
405 # We didn't find one. Do static initialization.
405 # We didn't find one. Do static initialization.
406 self.init_default_value(obj)
406 self.init_default_value(obj)
407 return
407 return
408 # Complete the dynamic initialization.
408 # Complete the dynamic initialization.
409 obj._trait_dyn_inits[self.name] = meth_name
409 obj._trait_dyn_inits[self.name] = meth_name
410
410
411 def __get__(self, obj, cls=None):
411 def __get__(self, obj, cls=None):
412 """Get the value of the trait by self.name for the instance.
412 """Get the value of the trait by self.name for the instance.
413
413
414 Default values are instantiated when :meth:`HasTraits.__new__`
414 Default values are instantiated when :meth:`HasTraits.__new__`
415 is called. Thus by the time this method gets called either the
415 is called. Thus by the time this method gets called either the
416 default value or a user defined value (they called :meth:`__set__`)
416 default value or a user defined value (they called :meth:`__set__`)
417 is in the :class:`HasTraits` instance.
417 is in the :class:`HasTraits` instance.
418 """
418 """
419 if obj is None:
419 if obj is None:
420 return self
420 return self
421 else:
421 else:
422 try:
422 try:
423 value = obj._trait_values[self.name]
423 value = obj._trait_values[self.name]
424 except KeyError:
424 except KeyError:
425 # Check for a dynamic initializer.
425 # Check for a dynamic initializer.
426 if self.name in obj._trait_dyn_inits:
426 if self.name in obj._trait_dyn_inits:
427 method = getattr(obj, obj._trait_dyn_inits[self.name])
427 method = getattr(obj, obj._trait_dyn_inits[self.name])
428 value = method()
428 value = method()
429 # FIXME: Do we really validate here?
429 # FIXME: Do we really validate here?
430 value = self._validate(obj, value)
430 value = self._validate(obj, value)
431 obj._trait_values[self.name] = value
431 obj._trait_values[self.name] = value
432 return value
432 return value
433 else:
433 else:
434 return self.init_default_value(obj)
434 return self.init_default_value(obj)
435 except Exception:
435 except Exception:
436 # HasTraits should call set_default_value to populate
436 # HasTraits should call set_default_value to populate
437 # this. So this should never be reached.
437 # this. So this should never be reached.
438 raise TraitError('Unexpected error in TraitType: '
438 raise TraitError('Unexpected error in TraitType: '
439 'default value not set properly')
439 'default value not set properly')
440 else:
440 else:
441 return value
441 return value
442
442
443 def __set__(self, obj, value):
443 def __set__(self, obj, value):
444 new_value = self._validate(obj, value)
444 new_value = self._validate(obj, value)
445 try:
445 try:
446 old_value = obj._trait_values[self.name]
446 old_value = obj._trait_values[self.name]
447 except KeyError:
447 except KeyError:
448 old_value = None
448 old_value = None
449
449
450 obj._trait_values[self.name] = new_value
450 obj._trait_values[self.name] = new_value
451 try:
451 try:
452 silent = bool(old_value == new_value)
452 silent = bool(old_value == new_value)
453 except:
453 except:
454 # if there is an error in comparing, default to notify
454 # if there is an error in comparing, default to notify
455 silent = False
455 silent = False
456 if silent is not True:
456 if silent is not True:
457 # we explicitly compare silent to True just in case the equality
457 # we explicitly compare silent to True just in case the equality
458 # comparison above returns something other than True/False
458 # comparison above returns something other than True/False
459 obj._notify_trait(self.name, old_value, new_value)
459 obj._notify_trait(self.name, old_value, new_value)
460
460
461 def _validate(self, obj, value):
461 def _validate(self, obj, value):
462 if value is None and self.allow_none:
462 if value is None and self.allow_none:
463 return value
463 return value
464 if hasattr(self, 'validate'):
464 if hasattr(self, 'validate'):
465 value = self.validate(obj, value)
465 value = self.validate(obj, value)
466 try:
466 try:
467 obj_validate = getattr(obj, '_%s_validate' % self.name)
467 obj_validate = getattr(obj, '_%s_validate' % self.name)
468 except (AttributeError, RuntimeError):
468 except (AttributeError, RuntimeError):
469 # Qt mixins raise RuntimeError on missing attrs accessed before __init__
469 # Qt mixins raise RuntimeError on missing attrs accessed before __init__
470 pass
470 pass
471 else:
471 else:
472 value = obj_validate(value, self)
472 value = obj_validate(value, self)
473 return value
473 return value
474
474
475 def __or__(self, other):
475 def __or__(self, other):
476 if isinstance(other, Union):
476 if isinstance(other, Union):
477 return Union([self] + other.trait_types)
477 return Union([self] + other.trait_types)
478 else:
478 else:
479 return Union([self, other])
479 return Union([self, other])
480
480
481 def info(self):
481 def info(self):
482 return self.info_text
482 return self.info_text
483
483
484 def error(self, obj, value):
484 def error(self, obj, value):
485 if obj is not None:
485 if obj is not None:
486 e = "The '%s' trait of %s instance must be %s, but a value of %s was specified." \
486 e = "The '%s' trait of %s instance must be %s, but a value of %s was specified." \
487 % (self.name, class_of(obj),
487 % (self.name, class_of(obj),
488 self.info(), repr_type(value))
488 self.info(), repr_type(value))
489 else:
489 else:
490 e = "The '%s' trait must be %s, but a value of %r was specified." \
490 e = "The '%s' trait must be %s, but a value of %r was specified." \
491 % (self.name, self.info(), repr_type(value))
491 % (self.name, self.info(), repr_type(value))
492 raise TraitError(e)
492 raise TraitError(e)
493
493
494 def get_metadata(self, key, default=None):
494 def get_metadata(self, key, default=None):
495 return getattr(self, '_metadata', {}).get(key, default)
495 return getattr(self, '_metadata', {}).get(key, default)
496
496
497 def set_metadata(self, key, value):
497 def set_metadata(self, key, value):
498 getattr(self, '_metadata', {})[key] = value
498 getattr(self, '_metadata', {})[key] = value
499
499
500
500
501 #-----------------------------------------------------------------------------
501 #-----------------------------------------------------------------------------
502 # The HasTraits implementation
502 # The HasTraits implementation
503 #-----------------------------------------------------------------------------
503 #-----------------------------------------------------------------------------
504
504
505
505
506 class MetaHasTraits(type):
506 class MetaHasTraits(type):
507 """A metaclass for HasTraits.
507 """A metaclass for HasTraits.
508
508
509 This metaclass makes sure that any TraitType class attributes are
509 This metaclass makes sure that any TraitType class attributes are
510 instantiated and sets their name attribute.
510 instantiated and sets their name attribute.
511 """
511 """
512
512
513 def __new__(mcls, name, bases, classdict):
513 def __new__(mcls, name, bases, classdict):
514 """Create the HasTraits class.
514 """Create the HasTraits class.
515
515
516 This instantiates all TraitTypes in the class dict and sets their
516 This instantiates all TraitTypes in the class dict and sets their
517 :attr:`name` attribute.
517 :attr:`name` attribute.
518 """
518 """
519 # print "MetaHasTraitlets (mcls, name): ", mcls, name
519 # print "MetaHasTraitlets (mcls, name): ", mcls, name
520 # print "MetaHasTraitlets (bases): ", bases
520 # print "MetaHasTraitlets (bases): ", bases
521 # print "MetaHasTraitlets (classdict): ", classdict
521 # print "MetaHasTraitlets (classdict): ", classdict
522 for k,v in iteritems(classdict):
522 for k,v in iteritems(classdict):
523 if isinstance(v, TraitType):
523 if isinstance(v, TraitType):
524 v.name = k
524 v.name = k
525 elif inspect.isclass(v):
525 elif inspect.isclass(v):
526 if issubclass(v, TraitType):
526 if issubclass(v, TraitType):
527 vinst = v()
527 vinst = v()
528 vinst.name = k
528 vinst.name = k
529 classdict[k] = vinst
529 classdict[k] = vinst
530 return super(MetaHasTraits, mcls).__new__(mcls, name, bases, classdict)
530 return super(MetaHasTraits, mcls).__new__(mcls, name, bases, classdict)
531
531
532 def __init__(cls, name, bases, classdict):
532 def __init__(cls, name, bases, classdict):
533 """Finish initializing the HasTraits class.
533 """Finish initializing the HasTraits class.
534
534
535 This sets the :attr:`this_class` attribute of each TraitType in the
535 This sets the :attr:`this_class` attribute of each TraitType in the
536 class dict to the newly created class ``cls``.
536 class dict to the newly created class ``cls``.
537 """
537 """
538 for k, v in iteritems(classdict):
538 for k, v in iteritems(classdict):
539 if isinstance(v, TraitType):
539 if isinstance(v, TraitType):
540 v.this_class = cls
540 v.this_class = cls
541 super(MetaHasTraits, cls).__init__(name, bases, classdict)
541 super(MetaHasTraits, cls).__init__(name, bases, classdict)
542
542
543 class HasTraits(py3compat.with_metaclass(MetaHasTraits, object)):
543 class HasTraits(py3compat.with_metaclass(MetaHasTraits, object)):
544
544
545 def __new__(cls, *args, **kw):
545 def __new__(cls, *args, **kw):
546 # This is needed because object.__new__ only accepts
546 # This is needed because object.__new__ only accepts
547 # the cls argument.
547 # the cls argument.
548 new_meth = super(HasTraits, cls).__new__
548 new_meth = super(HasTraits, cls).__new__
549 if new_meth is object.__new__:
549 if new_meth is object.__new__:
550 inst = new_meth(cls)
550 inst = new_meth(cls)
551 else:
551 else:
552 inst = new_meth(cls, **kw)
552 inst = new_meth(cls, **kw)
553 inst._trait_values = {}
553 inst._trait_values = {}
554 inst._trait_notifiers = {}
554 inst._trait_notifiers = {}
555 inst._trait_dyn_inits = {}
555 inst._trait_dyn_inits = {}
556 # Here we tell all the TraitType instances to set their default
556 # Here we tell all the TraitType instances to set their default
557 # values on the instance.
557 # values on the instance.
558 for key in dir(cls):
558 for key in dir(cls):
559 # Some descriptors raise AttributeError like zope.interface's
559 # Some descriptors raise AttributeError like zope.interface's
560 # __provides__ attributes even though they exist. This causes
560 # __provides__ attributes even though they exist. This causes
561 # AttributeErrors even though they are listed in dir(cls).
561 # AttributeErrors even though they are listed in dir(cls).
562 try:
562 try:
563 value = getattr(cls, key)
563 value = getattr(cls, key)
564 except AttributeError:
564 except AttributeError:
565 pass
565 pass
566 else:
566 else:
567 if isinstance(value, TraitType):
567 if isinstance(value, TraitType):
568 value.instance_init()
568 value.instance_init()
569 if key not in kw:
569 if key not in kw:
570 value.set_default_value(inst)
570 value.set_default_value(inst)
571
571
572 return inst
572 return inst
573
573
574 def __init__(self, *args, **kw):
574 def __init__(self, *args, **kw):
575 # Allow trait values to be set using keyword arguments.
575 # Allow trait values to be set using keyword arguments.
576 # We need to use setattr for this to trigger validation and
576 # We need to use setattr for this to trigger validation and
577 # notifications.
577 # notifications.
578
579 with self.delay_trait_notifications():
578 for key, value in iteritems(kw):
580 for key, value in iteritems(kw):
579 setattr(self, key, value)
581 setattr(self, key, value)
580
582
583 @contextlib.contextmanager
584 def delay_trait_notifications(self):
585 """Context manager for bundling trait change notifications
586
587 Use this when doing multiple trait assignments (init, config),
588 to avoid race conditions in trait notifiers requesting other trait values.
589 All trait notifications will fire after all values have been assigned.
590 """
591 _notify_trait = self._notify_trait
592 notifications = []
593 self._notify_trait = lambda *a: notifications.append(a)
594
595 try:
596 yield
597 finally:
598 self._notify_trait = _notify_trait
599
600 # trigger delayed notifications
601 for args in notifications:
602 self._notify_trait(*args)
603
581 def _notify_trait(self, name, old_value, new_value):
604 def _notify_trait(self, name, old_value, new_value):
582
605
583 # First dynamic ones
606 # First dynamic ones
584 callables = []
607 callables = []
585 callables.extend(self._trait_notifiers.get(name,[]))
608 callables.extend(self._trait_notifiers.get(name,[]))
586 callables.extend(self._trait_notifiers.get('anytrait',[]))
609 callables.extend(self._trait_notifiers.get('anytrait',[]))
587
610
588 # Now static ones
611 # Now static ones
589 try:
612 try:
590 cb = getattr(self, '_%s_changed' % name)
613 cb = getattr(self, '_%s_changed' % name)
591 except:
614 except:
592 pass
615 pass
593 else:
616 else:
594 callables.append(cb)
617 callables.append(cb)
595
618
596 # Call them all now
619 # Call them all now
597 for c in callables:
620 for c in callables:
598 # Traits catches and logs errors here. I allow them to raise
621 # Traits catches and logs errors here. I allow them to raise
599 if callable(c):
622 if callable(c):
600 argspec = inspect.getargspec(c)
623 argspec = inspect.getargspec(c)
601 nargs = len(argspec[0])
624 nargs = len(argspec[0])
602 # Bound methods have an additional 'self' argument
625 # Bound methods have an additional 'self' argument
603 # I don't know how to treat unbound methods, but they
626 # I don't know how to treat unbound methods, but they
604 # can't really be used for callbacks.
627 # can't really be used for callbacks.
605 if isinstance(c, types.MethodType):
628 if isinstance(c, types.MethodType):
606 offset = -1
629 offset = -1
607 else:
630 else:
608 offset = 0
631 offset = 0
609 if nargs + offset == 0:
632 if nargs + offset == 0:
610 c()
633 c()
611 elif nargs + offset == 1:
634 elif nargs + offset == 1:
612 c(name)
635 c(name)
613 elif nargs + offset == 2:
636 elif nargs + offset == 2:
614 c(name, new_value)
637 c(name, new_value)
615 elif nargs + offset == 3:
638 elif nargs + offset == 3:
616 c(name, old_value, new_value)
639 c(name, old_value, new_value)
617 else:
640 else:
618 raise TraitError('a trait changed callback '
641 raise TraitError('a trait changed callback '
619 'must have 0-3 arguments.')
642 'must have 0-3 arguments.')
620 else:
643 else:
621 raise TraitError('a trait changed callback '
644 raise TraitError('a trait changed callback '
622 'must be callable.')
645 'must be callable.')
623
646
624
647
625 def _add_notifiers(self, handler, name):
648 def _add_notifiers(self, handler, name):
626 if name not in self._trait_notifiers:
649 if name not in self._trait_notifiers:
627 nlist = []
650 nlist = []
628 self._trait_notifiers[name] = nlist
651 self._trait_notifiers[name] = nlist
629 else:
652 else:
630 nlist = self._trait_notifiers[name]
653 nlist = self._trait_notifiers[name]
631 if handler not in nlist:
654 if handler not in nlist:
632 nlist.append(handler)
655 nlist.append(handler)
633
656
634 def _remove_notifiers(self, handler, name):
657 def _remove_notifiers(self, handler, name):
635 if name in self._trait_notifiers:
658 if name in self._trait_notifiers:
636 nlist = self._trait_notifiers[name]
659 nlist = self._trait_notifiers[name]
637 try:
660 try:
638 index = nlist.index(handler)
661 index = nlist.index(handler)
639 except ValueError:
662 except ValueError:
640 pass
663 pass
641 else:
664 else:
642 del nlist[index]
665 del nlist[index]
643
666
644 def on_trait_change(self, handler, name=None, remove=False):
667 def on_trait_change(self, handler, name=None, remove=False):
645 """Setup a handler to be called when a trait changes.
668 """Setup a handler to be called when a trait changes.
646
669
647 This is used to setup dynamic notifications of trait changes.
670 This is used to setup dynamic notifications of trait changes.
648
671
649 Static handlers can be created by creating methods on a HasTraits
672 Static handlers can be created by creating methods on a HasTraits
650 subclass with the naming convention '_[traitname]_changed'. Thus,
673 subclass with the naming convention '_[traitname]_changed'. Thus,
651 to create static handler for the trait 'a', create the method
674 to create static handler for the trait 'a', create the method
652 _a_changed(self, name, old, new) (fewer arguments can be used, see
675 _a_changed(self, name, old, new) (fewer arguments can be used, see
653 below).
676 below).
654
677
655 Parameters
678 Parameters
656 ----------
679 ----------
657 handler : callable
680 handler : callable
658 A callable that is called when a trait changes. Its
681 A callable that is called when a trait changes. Its
659 signature can be handler(), handler(name), handler(name, new)
682 signature can be handler(), handler(name), handler(name, new)
660 or handler(name, old, new).
683 or handler(name, old, new).
661 name : list, str, None
684 name : list, str, None
662 If None, the handler will apply to all traits. If a list
685 If None, the handler will apply to all traits. If a list
663 of str, handler will apply to all names in the list. If a
686 of str, handler will apply to all names in the list. If a
664 str, the handler will apply just to that name.
687 str, the handler will apply just to that name.
665 remove : bool
688 remove : bool
666 If False (the default), then install the handler. If True
689 If False (the default), then install the handler. If True
667 then unintall it.
690 then unintall it.
668 """
691 """
669 if remove:
692 if remove:
670 names = parse_notifier_name(name)
693 names = parse_notifier_name(name)
671 for n in names:
694 for n in names:
672 self._remove_notifiers(handler, n)
695 self._remove_notifiers(handler, n)
673 else:
696 else:
674 names = parse_notifier_name(name)
697 names = parse_notifier_name(name)
675 for n in names:
698 for n in names:
676 self._add_notifiers(handler, n)
699 self._add_notifiers(handler, n)
677
700
678 @classmethod
701 @classmethod
679 def class_trait_names(cls, **metadata):
702 def class_trait_names(cls, **metadata):
680 """Get a list of all the names of this class' traits.
703 """Get a list of all the names of this class' traits.
681
704
682 This method is just like the :meth:`trait_names` method,
705 This method is just like the :meth:`trait_names` method,
683 but is unbound.
706 but is unbound.
684 """
707 """
685 return cls.class_traits(**metadata).keys()
708 return cls.class_traits(**metadata).keys()
686
709
687 @classmethod
710 @classmethod
688 def class_traits(cls, **metadata):
711 def class_traits(cls, **metadata):
689 """Get a `dict` of all the traits of this class. The dictionary
712 """Get a `dict` of all the traits of this class. The dictionary
690 is keyed on the name and the values are the TraitType objects.
713 is keyed on the name and the values are the TraitType objects.
691
714
692 This method is just like the :meth:`traits` method, but is unbound.
715 This method is just like the :meth:`traits` method, but is unbound.
693
716
694 The TraitTypes returned don't know anything about the values
717 The TraitTypes returned don't know anything about the values
695 that the various HasTrait's instances are holding.
718 that the various HasTrait's instances are holding.
696
719
697 The metadata kwargs allow functions to be passed in which
720 The metadata kwargs allow functions to be passed in which
698 filter traits based on metadata values. The functions should
721 filter traits based on metadata values. The functions should
699 take a single value as an argument and return a boolean. If
722 take a single value as an argument and return a boolean. If
700 any function returns False, then the trait is not included in
723 any function returns False, then the trait is not included in
701 the output. This does not allow for any simple way of
724 the output. This does not allow for any simple way of
702 testing that a metadata name exists and has any
725 testing that a metadata name exists and has any
703 value because get_metadata returns None if a metadata key
726 value because get_metadata returns None if a metadata key
704 doesn't exist.
727 doesn't exist.
705 """
728 """
706 traits = dict([memb for memb in getmembers(cls) if
729 traits = dict([memb for memb in getmembers(cls) if
707 isinstance(memb[1], TraitType)])
730 isinstance(memb[1], TraitType)])
708
731
709 if len(metadata) == 0:
732 if len(metadata) == 0:
710 return traits
733 return traits
711
734
712 for meta_name, meta_eval in metadata.items():
735 for meta_name, meta_eval in metadata.items():
713 if type(meta_eval) is not FunctionType:
736 if type(meta_eval) is not FunctionType:
714 metadata[meta_name] = _SimpleTest(meta_eval)
737 metadata[meta_name] = _SimpleTest(meta_eval)
715
738
716 result = {}
739 result = {}
717 for name, trait in traits.items():
740 for name, trait in traits.items():
718 for meta_name, meta_eval in metadata.items():
741 for meta_name, meta_eval in metadata.items():
719 if not meta_eval(trait.get_metadata(meta_name)):
742 if not meta_eval(trait.get_metadata(meta_name)):
720 break
743 break
721 else:
744 else:
722 result[name] = trait
745 result[name] = trait
723
746
724 return result
747 return result
725
748
726 def trait_names(self, **metadata):
749 def trait_names(self, **metadata):
727 """Get a list of all the names of this class' traits."""
750 """Get a list of all the names of this class' traits."""
728 return self.traits(**metadata).keys()
751 return self.traits(**metadata).keys()
729
752
730 def traits(self, **metadata):
753 def traits(self, **metadata):
731 """Get a `dict` of all the traits of this class. The dictionary
754 """Get a `dict` of all the traits of this class. The dictionary
732 is keyed on the name and the values are the TraitType objects.
755 is keyed on the name and the values are the TraitType objects.
733
756
734 The TraitTypes returned don't know anything about the values
757 The TraitTypes returned don't know anything about the values
735 that the various HasTrait's instances are holding.
758 that the various HasTrait's instances are holding.
736
759
737 The metadata kwargs allow functions to be passed in which
760 The metadata kwargs allow functions to be passed in which
738 filter traits based on metadata values. The functions should
761 filter traits based on metadata values. The functions should
739 take a single value as an argument and return a boolean. If
762 take a single value as an argument and return a boolean. If
740 any function returns False, then the trait is not included in
763 any function returns False, then the trait is not included in
741 the output. This does not allow for any simple way of
764 the output. This does not allow for any simple way of
742 testing that a metadata name exists and has any
765 testing that a metadata name exists and has any
743 value because get_metadata returns None if a metadata key
766 value because get_metadata returns None if a metadata key
744 doesn't exist.
767 doesn't exist.
745 """
768 """
746 traits = dict([memb for memb in getmembers(self.__class__) if
769 traits = dict([memb for memb in getmembers(self.__class__) if
747 isinstance(memb[1], TraitType)])
770 isinstance(memb[1], TraitType)])
748
771
749 if len(metadata) == 0:
772 if len(metadata) == 0:
750 return traits
773 return traits
751
774
752 for meta_name, meta_eval in metadata.items():
775 for meta_name, meta_eval in metadata.items():
753 if type(meta_eval) is not FunctionType:
776 if type(meta_eval) is not FunctionType:
754 metadata[meta_name] = _SimpleTest(meta_eval)
777 metadata[meta_name] = _SimpleTest(meta_eval)
755
778
756 result = {}
779 result = {}
757 for name, trait in traits.items():
780 for name, trait in traits.items():
758 for meta_name, meta_eval in metadata.items():
781 for meta_name, meta_eval in metadata.items():
759 if not meta_eval(trait.get_metadata(meta_name)):
782 if not meta_eval(trait.get_metadata(meta_name)):
760 break
783 break
761 else:
784 else:
762 result[name] = trait
785 result[name] = trait
763
786
764 return result
787 return result
765
788
766 def trait_metadata(self, traitname, key, default=None):
789 def trait_metadata(self, traitname, key, default=None):
767 """Get metadata values for trait by key."""
790 """Get metadata values for trait by key."""
768 try:
791 try:
769 trait = getattr(self.__class__, traitname)
792 trait = getattr(self.__class__, traitname)
770 except AttributeError:
793 except AttributeError:
771 raise TraitError("Class %s does not have a trait named %s" %
794 raise TraitError("Class %s does not have a trait named %s" %
772 (self.__class__.__name__, traitname))
795 (self.__class__.__name__, traitname))
773 else:
796 else:
774 return trait.get_metadata(key, default)
797 return trait.get_metadata(key, default)
775
798
776 #-----------------------------------------------------------------------------
799 #-----------------------------------------------------------------------------
777 # Actual TraitTypes implementations/subclasses
800 # Actual TraitTypes implementations/subclasses
778 #-----------------------------------------------------------------------------
801 #-----------------------------------------------------------------------------
779
802
780 #-----------------------------------------------------------------------------
803 #-----------------------------------------------------------------------------
781 # TraitTypes subclasses for handling classes and instances of classes
804 # TraitTypes subclasses for handling classes and instances of classes
782 #-----------------------------------------------------------------------------
805 #-----------------------------------------------------------------------------
783
806
784
807
785 class ClassBasedTraitType(TraitType):
808 class ClassBasedTraitType(TraitType):
786 """
809 """
787 A trait with error reporting and string -> type resolution for Type,
810 A trait with error reporting and string -> type resolution for Type,
788 Instance and This.
811 Instance and This.
789 """
812 """
790
813
791 def _resolve_string(self, string):
814 def _resolve_string(self, string):
792 """
815 """
793 Resolve a string supplied for a type into an actual object.
816 Resolve a string supplied for a type into an actual object.
794 """
817 """
795 return import_item(string)
818 return import_item(string)
796
819
797 def error(self, obj, value):
820 def error(self, obj, value):
798 kind = type(value)
821 kind = type(value)
799 if (not py3compat.PY3) and kind is InstanceType:
822 if (not py3compat.PY3) and kind is InstanceType:
800 msg = 'class %s' % value.__class__.__name__
823 msg = 'class %s' % value.__class__.__name__
801 else:
824 else:
802 msg = '%s (i.e. %s)' % ( str( kind )[1:-1], repr( value ) )
825 msg = '%s (i.e. %s)' % ( str( kind )[1:-1], repr( value ) )
803
826
804 if obj is not None:
827 if obj is not None:
805 e = "The '%s' trait of %s instance must be %s, but a value of %s was specified." \
828 e = "The '%s' trait of %s instance must be %s, but a value of %s was specified." \
806 % (self.name, class_of(obj),
829 % (self.name, class_of(obj),
807 self.info(), msg)
830 self.info(), msg)
808 else:
831 else:
809 e = "The '%s' trait must be %s, but a value of %r was specified." \
832 e = "The '%s' trait must be %s, but a value of %r was specified." \
810 % (self.name, self.info(), msg)
833 % (self.name, self.info(), msg)
811
834
812 raise TraitError(e)
835 raise TraitError(e)
813
836
814
837
815 class Type(ClassBasedTraitType):
838 class Type(ClassBasedTraitType):
816 """A trait whose value must be a subclass of a specified class."""
839 """A trait whose value must be a subclass of a specified class."""
817
840
818 def __init__ (self, default_value=None, klass=None, allow_none=True, **metadata ):
841 def __init__ (self, default_value=None, klass=None, allow_none=True, **metadata ):
819 """Construct a Type trait
842 """Construct a Type trait
820
843
821 A Type trait specifies that its values must be subclasses of
844 A Type trait specifies that its values must be subclasses of
822 a particular class.
845 a particular class.
823
846
824 If only ``default_value`` is given, it is used for the ``klass`` as
847 If only ``default_value`` is given, it is used for the ``klass`` as
825 well.
848 well.
826
849
827 Parameters
850 Parameters
828 ----------
851 ----------
829 default_value : class, str or None
852 default_value : class, str or None
830 The default value must be a subclass of klass. If an str,
853 The default value must be a subclass of klass. If an str,
831 the str must be a fully specified class name, like 'foo.bar.Bah'.
854 the str must be a fully specified class name, like 'foo.bar.Bah'.
832 The string is resolved into real class, when the parent
855 The string is resolved into real class, when the parent
833 :class:`HasTraits` class is instantiated.
856 :class:`HasTraits` class is instantiated.
834 klass : class, str, None
857 klass : class, str, None
835 Values of this trait must be a subclass of klass. The klass
858 Values of this trait must be a subclass of klass. The klass
836 may be specified in a string like: 'foo.bar.MyClass'.
859 may be specified in a string like: 'foo.bar.MyClass'.
837 The string is resolved into real class, when the parent
860 The string is resolved into real class, when the parent
838 :class:`HasTraits` class is instantiated.
861 :class:`HasTraits` class is instantiated.
839 allow_none : bool [ default True ]
862 allow_none : bool [ default True ]
840 Indicates whether None is allowed as an assignable value. Even if
863 Indicates whether None is allowed as an assignable value. Even if
841 ``False``, the default value may be ``None``.
864 ``False``, the default value may be ``None``.
842 """
865 """
843 if default_value is None:
866 if default_value is None:
844 if klass is None:
867 if klass is None:
845 klass = object
868 klass = object
846 elif klass is None:
869 elif klass is None:
847 klass = default_value
870 klass = default_value
848
871
849 if not (inspect.isclass(klass) or isinstance(klass, py3compat.string_types)):
872 if not (inspect.isclass(klass) or isinstance(klass, py3compat.string_types)):
850 raise TraitError("A Type trait must specify a class.")
873 raise TraitError("A Type trait must specify a class.")
851
874
852 self.klass = klass
875 self.klass = klass
853
876
854 super(Type, self).__init__(default_value, allow_none=allow_none, **metadata)
877 super(Type, self).__init__(default_value, allow_none=allow_none, **metadata)
855
878
856 def validate(self, obj, value):
879 def validate(self, obj, value):
857 """Validates that the value is a valid object instance."""
880 """Validates that the value is a valid object instance."""
858 if isinstance(value, py3compat.string_types):
881 if isinstance(value, py3compat.string_types):
859 try:
882 try:
860 value = self._resolve_string(value)
883 value = self._resolve_string(value)
861 except ImportError:
884 except ImportError:
862 raise TraitError("The '%s' trait of %s instance must be a type, but "
885 raise TraitError("The '%s' trait of %s instance must be a type, but "
863 "%r could not be imported" % (self.name, obj, value))
886 "%r could not be imported" % (self.name, obj, value))
864 try:
887 try:
865 if issubclass(value, self.klass):
888 if issubclass(value, self.klass):
866 return value
889 return value
867 except:
890 except:
868 pass
891 pass
869
892
870 self.error(obj, value)
893 self.error(obj, value)
871
894
872 def info(self):
895 def info(self):
873 """ Returns a description of the trait."""
896 """ Returns a description of the trait."""
874 if isinstance(self.klass, py3compat.string_types):
897 if isinstance(self.klass, py3compat.string_types):
875 klass = self.klass
898 klass = self.klass
876 else:
899 else:
877 klass = self.klass.__name__
900 klass = self.klass.__name__
878 result = 'a subclass of ' + klass
901 result = 'a subclass of ' + klass
879 if self.allow_none:
902 if self.allow_none:
880 return result + ' or None'
903 return result + ' or None'
881 return result
904 return result
882
905
883 def instance_init(self):
906 def instance_init(self):
884 self._resolve_classes()
907 self._resolve_classes()
885 super(Type, self).instance_init()
908 super(Type, self).instance_init()
886
909
887 def _resolve_classes(self):
910 def _resolve_classes(self):
888 if isinstance(self.klass, py3compat.string_types):
911 if isinstance(self.klass, py3compat.string_types):
889 self.klass = self._resolve_string(self.klass)
912 self.klass = self._resolve_string(self.klass)
890 if isinstance(self.default_value, py3compat.string_types):
913 if isinstance(self.default_value, py3compat.string_types):
891 self.default_value = self._resolve_string(self.default_value)
914 self.default_value = self._resolve_string(self.default_value)
892
915
893 def get_default_value(self):
916 def get_default_value(self):
894 return self.default_value
917 return self.default_value
895
918
896
919
897 class DefaultValueGenerator(object):
920 class DefaultValueGenerator(object):
898 """A class for generating new default value instances."""
921 """A class for generating new default value instances."""
899
922
900 def __init__(self, *args, **kw):
923 def __init__(self, *args, **kw):
901 self.args = args
924 self.args = args
902 self.kw = kw
925 self.kw = kw
903
926
904 def generate(self, klass):
927 def generate(self, klass):
905 return klass(*self.args, **self.kw)
928 return klass(*self.args, **self.kw)
906
929
907
930
908 class Instance(ClassBasedTraitType):
931 class Instance(ClassBasedTraitType):
909 """A trait whose value must be an instance of a specified class.
932 """A trait whose value must be an instance of a specified class.
910
933
911 The value can also be an instance of a subclass of the specified class.
934 The value can also be an instance of a subclass of the specified class.
912
935
913 Subclasses can declare default classes by overriding the klass attribute
936 Subclasses can declare default classes by overriding the klass attribute
914 """
937 """
915
938
916 klass = None
939 klass = None
917
940
918 def __init__(self, klass=None, args=None, kw=None,
941 def __init__(self, klass=None, args=None, kw=None,
919 allow_none=True, **metadata ):
942 allow_none=True, **metadata ):
920 """Construct an Instance trait.
943 """Construct an Instance trait.
921
944
922 This trait allows values that are instances of a particular
945 This trait allows values that are instances of a particular
923 class or its subclasses. Our implementation is quite different
946 class or its subclasses. Our implementation is quite different
924 from that of enthough.traits as we don't allow instances to be used
947 from that of enthough.traits as we don't allow instances to be used
925 for klass and we handle the ``args`` and ``kw`` arguments differently.
948 for klass and we handle the ``args`` and ``kw`` arguments differently.
926
949
927 Parameters
950 Parameters
928 ----------
951 ----------
929 klass : class, str
952 klass : class, str
930 The class that forms the basis for the trait. Class names
953 The class that forms the basis for the trait. Class names
931 can also be specified as strings, like 'foo.bar.Bar'.
954 can also be specified as strings, like 'foo.bar.Bar'.
932 args : tuple
955 args : tuple
933 Positional arguments for generating the default value.
956 Positional arguments for generating the default value.
934 kw : dict
957 kw : dict
935 Keyword arguments for generating the default value.
958 Keyword arguments for generating the default value.
936 allow_none : bool [default True]
959 allow_none : bool [default True]
937 Indicates whether None is allowed as a value.
960 Indicates whether None is allowed as a value.
938
961
939 Notes
962 Notes
940 -----
963 -----
941 If both ``args`` and ``kw`` are None, then the default value is None.
964 If both ``args`` and ``kw`` are None, then the default value is None.
942 If ``args`` is a tuple and ``kw`` is a dict, then the default is
965 If ``args`` is a tuple and ``kw`` is a dict, then the default is
943 created as ``klass(*args, **kw)``. If exactly one of ``args`` or ``kw`` is
966 created as ``klass(*args, **kw)``. If exactly one of ``args`` or ``kw`` is
944 None, the None is replaced by ``()`` or ``{}``, respectively.
967 None, the None is replaced by ``()`` or ``{}``, respectively.
945 """
968 """
946 if klass is None:
969 if klass is None:
947 klass = self.klass
970 klass = self.klass
948
971
949 if (klass is not None) and (inspect.isclass(klass) or isinstance(klass, py3compat.string_types)):
972 if (klass is not None) and (inspect.isclass(klass) or isinstance(klass, py3compat.string_types)):
950 self.klass = klass
973 self.klass = klass
951 else:
974 else:
952 raise TraitError('The klass attribute must be a class'
975 raise TraitError('The klass attribute must be a class'
953 ' not: %r' % klass)
976 ' not: %r' % klass)
954
977
955 # self.klass is a class, so handle default_value
978 # self.klass is a class, so handle default_value
956 if args is None and kw is None:
979 if args is None and kw is None:
957 default_value = None
980 default_value = None
958 else:
981 else:
959 if args is None:
982 if args is None:
960 # kw is not None
983 # kw is not None
961 args = ()
984 args = ()
962 elif kw is None:
985 elif kw is None:
963 # args is not None
986 # args is not None
964 kw = {}
987 kw = {}
965
988
966 if not isinstance(kw, dict):
989 if not isinstance(kw, dict):
967 raise TraitError("The 'kw' argument must be a dict or None.")
990 raise TraitError("The 'kw' argument must be a dict or None.")
968 if not isinstance(args, tuple):
991 if not isinstance(args, tuple):
969 raise TraitError("The 'args' argument must be a tuple or None.")
992 raise TraitError("The 'args' argument must be a tuple or None.")
970
993
971 default_value = DefaultValueGenerator(*args, **kw)
994 default_value = DefaultValueGenerator(*args, **kw)
972
995
973 super(Instance, self).__init__(default_value, allow_none=allow_none, **metadata)
996 super(Instance, self).__init__(default_value, allow_none=allow_none, **metadata)
974
997
975 def validate(self, obj, value):
998 def validate(self, obj, value):
976 if isinstance(value, self.klass):
999 if isinstance(value, self.klass):
977 return value
1000 return value
978 else:
1001 else:
979 self.error(obj, value)
1002 self.error(obj, value)
980
1003
981 def info(self):
1004 def info(self):
982 if isinstance(self.klass, py3compat.string_types):
1005 if isinstance(self.klass, py3compat.string_types):
983 klass = self.klass
1006 klass = self.klass
984 else:
1007 else:
985 klass = self.klass.__name__
1008 klass = self.klass.__name__
986 result = class_of(klass)
1009 result = class_of(klass)
987 if self.allow_none:
1010 if self.allow_none:
988 return result + ' or None'
1011 return result + ' or None'
989
1012
990 return result
1013 return result
991
1014
992 def instance_init(self):
1015 def instance_init(self):
993 self._resolve_classes()
1016 self._resolve_classes()
994 super(Instance, self).instance_init()
1017 super(Instance, self).instance_init()
995
1018
996 def _resolve_classes(self):
1019 def _resolve_classes(self):
997 if isinstance(self.klass, py3compat.string_types):
1020 if isinstance(self.klass, py3compat.string_types):
998 self.klass = self._resolve_string(self.klass)
1021 self.klass = self._resolve_string(self.klass)
999
1022
1000 def get_default_value(self):
1023 def get_default_value(self):
1001 """Instantiate a default value instance.
1024 """Instantiate a default value instance.
1002
1025
1003 This is called when the containing HasTraits classes'
1026 This is called when the containing HasTraits classes'
1004 :meth:`__new__` method is called to ensure that a unique instance
1027 :meth:`__new__` method is called to ensure that a unique instance
1005 is created for each HasTraits instance.
1028 is created for each HasTraits instance.
1006 """
1029 """
1007 dv = self.default_value
1030 dv = self.default_value
1008 if isinstance(dv, DefaultValueGenerator):
1031 if isinstance(dv, DefaultValueGenerator):
1009 return dv.generate(self.klass)
1032 return dv.generate(self.klass)
1010 else:
1033 else:
1011 return dv
1034 return dv
1012
1035
1013
1036
1014 class ForwardDeclaredMixin(object):
1037 class ForwardDeclaredMixin(object):
1015 """
1038 """
1016 Mixin for forward-declared versions of Instance and Type.
1039 Mixin for forward-declared versions of Instance and Type.
1017 """
1040 """
1018 def _resolve_string(self, string):
1041 def _resolve_string(self, string):
1019 """
1042 """
1020 Find the specified class name by looking for it in the module in which
1043 Find the specified class name by looking for it in the module in which
1021 our this_class attribute was defined.
1044 our this_class attribute was defined.
1022 """
1045 """
1023 modname = self.this_class.__module__
1046 modname = self.this_class.__module__
1024 return import_item('.'.join([modname, string]))
1047 return import_item('.'.join([modname, string]))
1025
1048
1026
1049
1027 class ForwardDeclaredType(ForwardDeclaredMixin, Type):
1050 class ForwardDeclaredType(ForwardDeclaredMixin, Type):
1028 """
1051 """
1029 Forward-declared version of Type.
1052 Forward-declared version of Type.
1030 """
1053 """
1031 pass
1054 pass
1032
1055
1033
1056
1034 class ForwardDeclaredInstance(ForwardDeclaredMixin, Instance):
1057 class ForwardDeclaredInstance(ForwardDeclaredMixin, Instance):
1035 """
1058 """
1036 Forward-declared version of Instance.
1059 Forward-declared version of Instance.
1037 """
1060 """
1038 pass
1061 pass
1039
1062
1040
1063
1041 class This(ClassBasedTraitType):
1064 class This(ClassBasedTraitType):
1042 """A trait for instances of the class containing this trait.
1065 """A trait for instances of the class containing this trait.
1043
1066
1044 Because how how and when class bodies are executed, the ``This``
1067 Because how how and when class bodies are executed, the ``This``
1045 trait can only have a default value of None. This, and because we
1068 trait can only have a default value of None. This, and because we
1046 always validate default values, ``allow_none`` is *always* true.
1069 always validate default values, ``allow_none`` is *always* true.
1047 """
1070 """
1048
1071
1049 info_text = 'an instance of the same type as the receiver or None'
1072 info_text = 'an instance of the same type as the receiver or None'
1050
1073
1051 def __init__(self, **metadata):
1074 def __init__(self, **metadata):
1052 super(This, self).__init__(None, **metadata)
1075 super(This, self).__init__(None, **metadata)
1053
1076
1054 def validate(self, obj, value):
1077 def validate(self, obj, value):
1055 # What if value is a superclass of obj.__class__? This is
1078 # What if value is a superclass of obj.__class__? This is
1056 # complicated if it was the superclass that defined the This
1079 # complicated if it was the superclass that defined the This
1057 # trait.
1080 # trait.
1058 if isinstance(value, self.this_class) or (value is None):
1081 if isinstance(value, self.this_class) or (value is None):
1059 return value
1082 return value
1060 else:
1083 else:
1061 self.error(obj, value)
1084 self.error(obj, value)
1062
1085
1063
1086
1064 class Union(TraitType):
1087 class Union(TraitType):
1065 """A trait type representing a Union type."""
1088 """A trait type representing a Union type."""
1066
1089
1067 def __init__(self, trait_types, **metadata):
1090 def __init__(self, trait_types, **metadata):
1068 """Construct a Union trait.
1091 """Construct a Union trait.
1069
1092
1070 This trait allows values that are allowed by at least one of the
1093 This trait allows values that are allowed by at least one of the
1071 specified trait types. A Union traitlet cannot have metadata on
1094 specified trait types. A Union traitlet cannot have metadata on
1072 its own, besides the metadata of the listed types.
1095 its own, besides the metadata of the listed types.
1073
1096
1074 Parameters
1097 Parameters
1075 ----------
1098 ----------
1076 trait_types: sequence
1099 trait_types: sequence
1077 The list of trait types of length at least 1.
1100 The list of trait types of length at least 1.
1078
1101
1079 Notes
1102 Notes
1080 -----
1103 -----
1081 Union([Float(), Bool(), Int()]) attempts to validate the provided values
1104 Union([Float(), Bool(), Int()]) attempts to validate the provided values
1082 with the validation function of Float, then Bool, and finally Int.
1105 with the validation function of Float, then Bool, and finally Int.
1083 """
1106 """
1084 self.trait_types = trait_types
1107 self.trait_types = trait_types
1085 self.info_text = " or ".join([tt.info_text for tt in self.trait_types])
1108 self.info_text = " or ".join([tt.info_text for tt in self.trait_types])
1086 self.default_value = self.trait_types[0].get_default_value()
1109 self.default_value = self.trait_types[0].get_default_value()
1087 super(Union, self).__init__(**metadata)
1110 super(Union, self).__init__(**metadata)
1088
1111
1089 def instance_init(self):
1112 def instance_init(self):
1090 for trait_type in self.trait_types:
1113 for trait_type in self.trait_types:
1091 trait_type.name = self.name
1114 trait_type.name = self.name
1092 trait_type.this_class = self.this_class
1115 trait_type.this_class = self.this_class
1093 trait_type.instance_init()
1116 trait_type.instance_init()
1094 super(Union, self).instance_init()
1117 super(Union, self).instance_init()
1095
1118
1096 def validate(self, obj, value):
1119 def validate(self, obj, value):
1097 for trait_type in self.trait_types:
1120 for trait_type in self.trait_types:
1098 try:
1121 try:
1099 v = trait_type._validate(obj, value)
1122 v = trait_type._validate(obj, value)
1100 self._metadata = trait_type._metadata
1123 self._metadata = trait_type._metadata
1101 return v
1124 return v
1102 except TraitError:
1125 except TraitError:
1103 continue
1126 continue
1104 self.error(obj, value)
1127 self.error(obj, value)
1105
1128
1106 def __or__(self, other):
1129 def __or__(self, other):
1107 if isinstance(other, Union):
1130 if isinstance(other, Union):
1108 return Union(self.trait_types + other.trait_types)
1131 return Union(self.trait_types + other.trait_types)
1109 else:
1132 else:
1110 return Union(self.trait_types + [other])
1133 return Union(self.trait_types + [other])
1111
1134
1112 #-----------------------------------------------------------------------------
1135 #-----------------------------------------------------------------------------
1113 # Basic TraitTypes implementations/subclasses
1136 # Basic TraitTypes implementations/subclasses
1114 #-----------------------------------------------------------------------------
1137 #-----------------------------------------------------------------------------
1115
1138
1116
1139
1117 class Any(TraitType):
1140 class Any(TraitType):
1118 default_value = None
1141 default_value = None
1119 info_text = 'any value'
1142 info_text = 'any value'
1120
1143
1121
1144
1122 class Int(TraitType):
1145 class Int(TraitType):
1123 """An int trait."""
1146 """An int trait."""
1124
1147
1125 default_value = 0
1148 default_value = 0
1126 info_text = 'an int'
1149 info_text = 'an int'
1127
1150
1128 def validate(self, obj, value):
1151 def validate(self, obj, value):
1129 if isinstance(value, int):
1152 if isinstance(value, int):
1130 return value
1153 return value
1131 self.error(obj, value)
1154 self.error(obj, value)
1132
1155
1133 class CInt(Int):
1156 class CInt(Int):
1134 """A casting version of the int trait."""
1157 """A casting version of the int trait."""
1135
1158
1136 def validate(self, obj, value):
1159 def validate(self, obj, value):
1137 try:
1160 try:
1138 return int(value)
1161 return int(value)
1139 except:
1162 except:
1140 self.error(obj, value)
1163 self.error(obj, value)
1141
1164
1142 if py3compat.PY3:
1165 if py3compat.PY3:
1143 Long, CLong = Int, CInt
1166 Long, CLong = Int, CInt
1144 Integer = Int
1167 Integer = Int
1145 else:
1168 else:
1146 class Long(TraitType):
1169 class Long(TraitType):
1147 """A long integer trait."""
1170 """A long integer trait."""
1148
1171
1149 default_value = 0
1172 default_value = 0
1150 info_text = 'a long'
1173 info_text = 'a long'
1151
1174
1152 def validate(self, obj, value):
1175 def validate(self, obj, value):
1153 if isinstance(value, long):
1176 if isinstance(value, long):
1154 return value
1177 return value
1155 if isinstance(value, int):
1178 if isinstance(value, int):
1156 return long(value)
1179 return long(value)
1157 self.error(obj, value)
1180 self.error(obj, value)
1158
1181
1159
1182
1160 class CLong(Long):
1183 class CLong(Long):
1161 """A casting version of the long integer trait."""
1184 """A casting version of the long integer trait."""
1162
1185
1163 def validate(self, obj, value):
1186 def validate(self, obj, value):
1164 try:
1187 try:
1165 return long(value)
1188 return long(value)
1166 except:
1189 except:
1167 self.error(obj, value)
1190 self.error(obj, value)
1168
1191
1169 class Integer(TraitType):
1192 class Integer(TraitType):
1170 """An integer trait.
1193 """An integer trait.
1171
1194
1172 Longs that are unnecessary (<= sys.maxint) are cast to ints."""
1195 Longs that are unnecessary (<= sys.maxint) are cast to ints."""
1173
1196
1174 default_value = 0
1197 default_value = 0
1175 info_text = 'an integer'
1198 info_text = 'an integer'
1176
1199
1177 def validate(self, obj, value):
1200 def validate(self, obj, value):
1178 if isinstance(value, int):
1201 if isinstance(value, int):
1179 return value
1202 return value
1180 if isinstance(value, long):
1203 if isinstance(value, long):
1181 # downcast longs that fit in int:
1204 # downcast longs that fit in int:
1182 # note that int(n > sys.maxint) returns a long, so
1205 # note that int(n > sys.maxint) returns a long, so
1183 # we don't need a condition on this cast
1206 # we don't need a condition on this cast
1184 return int(value)
1207 return int(value)
1185 if sys.platform == "cli":
1208 if sys.platform == "cli":
1186 from System import Int64
1209 from System import Int64
1187 if isinstance(value, Int64):
1210 if isinstance(value, Int64):
1188 return int(value)
1211 return int(value)
1189 self.error(obj, value)
1212 self.error(obj, value)
1190
1213
1191
1214
1192 class Float(TraitType):
1215 class Float(TraitType):
1193 """A float trait."""
1216 """A float trait."""
1194
1217
1195 default_value = 0.0
1218 default_value = 0.0
1196 info_text = 'a float'
1219 info_text = 'a float'
1197
1220
1198 def validate(self, obj, value):
1221 def validate(self, obj, value):
1199 if isinstance(value, float):
1222 if isinstance(value, float):
1200 return value
1223 return value
1201 if isinstance(value, int):
1224 if isinstance(value, int):
1202 return float(value)
1225 return float(value)
1203 self.error(obj, value)
1226 self.error(obj, value)
1204
1227
1205
1228
1206 class CFloat(Float):
1229 class CFloat(Float):
1207 """A casting version of the float trait."""
1230 """A casting version of the float trait."""
1208
1231
1209 def validate(self, obj, value):
1232 def validate(self, obj, value):
1210 try:
1233 try:
1211 return float(value)
1234 return float(value)
1212 except:
1235 except:
1213 self.error(obj, value)
1236 self.error(obj, value)
1214
1237
1215 class Complex(TraitType):
1238 class Complex(TraitType):
1216 """A trait for complex numbers."""
1239 """A trait for complex numbers."""
1217
1240
1218 default_value = 0.0 + 0.0j
1241 default_value = 0.0 + 0.0j
1219 info_text = 'a complex number'
1242 info_text = 'a complex number'
1220
1243
1221 def validate(self, obj, value):
1244 def validate(self, obj, value):
1222 if isinstance(value, complex):
1245 if isinstance(value, complex):
1223 return value
1246 return value
1224 if isinstance(value, (float, int)):
1247 if isinstance(value, (float, int)):
1225 return complex(value)
1248 return complex(value)
1226 self.error(obj, value)
1249 self.error(obj, value)
1227
1250
1228
1251
1229 class CComplex(Complex):
1252 class CComplex(Complex):
1230 """A casting version of the complex number trait."""
1253 """A casting version of the complex number trait."""
1231
1254
1232 def validate (self, obj, value):
1255 def validate (self, obj, value):
1233 try:
1256 try:
1234 return complex(value)
1257 return complex(value)
1235 except:
1258 except:
1236 self.error(obj, value)
1259 self.error(obj, value)
1237
1260
1238 # We should always be explicit about whether we're using bytes or unicode, both
1261 # We should always be explicit about whether we're using bytes or unicode, both
1239 # for Python 3 conversion and for reliable unicode behaviour on Python 2. So
1262 # for Python 3 conversion and for reliable unicode behaviour on Python 2. So
1240 # we don't have a Str type.
1263 # we don't have a Str type.
1241 class Bytes(TraitType):
1264 class Bytes(TraitType):
1242 """A trait for byte strings."""
1265 """A trait for byte strings."""
1243
1266
1244 default_value = b''
1267 default_value = b''
1245 info_text = 'a bytes object'
1268 info_text = 'a bytes object'
1246
1269
1247 def validate(self, obj, value):
1270 def validate(self, obj, value):
1248 if isinstance(value, bytes):
1271 if isinstance(value, bytes):
1249 return value
1272 return value
1250 self.error(obj, value)
1273 self.error(obj, value)
1251
1274
1252
1275
1253 class CBytes(Bytes):
1276 class CBytes(Bytes):
1254 """A casting version of the byte string trait."""
1277 """A casting version of the byte string trait."""
1255
1278
1256 def validate(self, obj, value):
1279 def validate(self, obj, value):
1257 try:
1280 try:
1258 return bytes(value)
1281 return bytes(value)
1259 except:
1282 except:
1260 self.error(obj, value)
1283 self.error(obj, value)
1261
1284
1262
1285
1263 class Unicode(TraitType):
1286 class Unicode(TraitType):
1264 """A trait for unicode strings."""
1287 """A trait for unicode strings."""
1265
1288
1266 default_value = u''
1289 default_value = u''
1267 info_text = 'a unicode string'
1290 info_text = 'a unicode string'
1268
1291
1269 def validate(self, obj, value):
1292 def validate(self, obj, value):
1270 if isinstance(value, py3compat.unicode_type):
1293 if isinstance(value, py3compat.unicode_type):
1271 return value
1294 return value
1272 if isinstance(value, bytes):
1295 if isinstance(value, bytes):
1273 try:
1296 try:
1274 return value.decode('ascii', 'strict')
1297 return value.decode('ascii', 'strict')
1275 except UnicodeDecodeError:
1298 except UnicodeDecodeError:
1276 msg = "Could not decode {!r} for unicode trait '{}' of {} instance."
1299 msg = "Could not decode {!r} for unicode trait '{}' of {} instance."
1277 raise TraitError(msg.format(value, self.name, class_of(obj)))
1300 raise TraitError(msg.format(value, self.name, class_of(obj)))
1278 self.error(obj, value)
1301 self.error(obj, value)
1279
1302
1280
1303
1281 class CUnicode(Unicode):
1304 class CUnicode(Unicode):
1282 """A casting version of the unicode trait."""
1305 """A casting version of the unicode trait."""
1283
1306
1284 def validate(self, obj, value):
1307 def validate(self, obj, value):
1285 try:
1308 try:
1286 return py3compat.unicode_type(value)
1309 return py3compat.unicode_type(value)
1287 except:
1310 except:
1288 self.error(obj, value)
1311 self.error(obj, value)
1289
1312
1290
1313
1291 class ObjectName(TraitType):
1314 class ObjectName(TraitType):
1292 """A string holding a valid object name in this version of Python.
1315 """A string holding a valid object name in this version of Python.
1293
1316
1294 This does not check that the name exists in any scope."""
1317 This does not check that the name exists in any scope."""
1295 info_text = "a valid object identifier in Python"
1318 info_text = "a valid object identifier in Python"
1296
1319
1297 if py3compat.PY3:
1320 if py3compat.PY3:
1298 # Python 3:
1321 # Python 3:
1299 coerce_str = staticmethod(lambda _,s: s)
1322 coerce_str = staticmethod(lambda _,s: s)
1300
1323
1301 else:
1324 else:
1302 # Python 2:
1325 # Python 2:
1303 def coerce_str(self, obj, value):
1326 def coerce_str(self, obj, value):
1304 "In Python 2, coerce ascii-only unicode to str"
1327 "In Python 2, coerce ascii-only unicode to str"
1305 if isinstance(value, unicode):
1328 if isinstance(value, unicode):
1306 try:
1329 try:
1307 return str(value)
1330 return str(value)
1308 except UnicodeEncodeError:
1331 except UnicodeEncodeError:
1309 self.error(obj, value)
1332 self.error(obj, value)
1310 return value
1333 return value
1311
1334
1312 def validate(self, obj, value):
1335 def validate(self, obj, value):
1313 value = self.coerce_str(obj, value)
1336 value = self.coerce_str(obj, value)
1314
1337
1315 if isinstance(value, string_types) and py3compat.isidentifier(value):
1338 if isinstance(value, string_types) and py3compat.isidentifier(value):
1316 return value
1339 return value
1317 self.error(obj, value)
1340 self.error(obj, value)
1318
1341
1319 class DottedObjectName(ObjectName):
1342 class DottedObjectName(ObjectName):
1320 """A string holding a valid dotted object name in Python, such as A.b3._c"""
1343 """A string holding a valid dotted object name in Python, such as A.b3._c"""
1321 def validate(self, obj, value):
1344 def validate(self, obj, value):
1322 value = self.coerce_str(obj, value)
1345 value = self.coerce_str(obj, value)
1323
1346
1324 if isinstance(value, string_types) and py3compat.isidentifier(value, dotted=True):
1347 if isinstance(value, string_types) and py3compat.isidentifier(value, dotted=True):
1325 return value
1348 return value
1326 self.error(obj, value)
1349 self.error(obj, value)
1327
1350
1328
1351
1329 class Bool(TraitType):
1352 class Bool(TraitType):
1330 """A boolean (True, False) trait."""
1353 """A boolean (True, False) trait."""
1331
1354
1332 default_value = False
1355 default_value = False
1333 info_text = 'a boolean'
1356 info_text = 'a boolean'
1334
1357
1335 def validate(self, obj, value):
1358 def validate(self, obj, value):
1336 if isinstance(value, bool):
1359 if isinstance(value, bool):
1337 return value
1360 return value
1338 self.error(obj, value)
1361 self.error(obj, value)
1339
1362
1340
1363
1341 class CBool(Bool):
1364 class CBool(Bool):
1342 """A casting version of the boolean trait."""
1365 """A casting version of the boolean trait."""
1343
1366
1344 def validate(self, obj, value):
1367 def validate(self, obj, value):
1345 try:
1368 try:
1346 return bool(value)
1369 return bool(value)
1347 except:
1370 except:
1348 self.error(obj, value)
1371 self.error(obj, value)
1349
1372
1350
1373
1351 class Enum(TraitType):
1374 class Enum(TraitType):
1352 """An enum that whose value must be in a given sequence."""
1375 """An enum that whose value must be in a given sequence."""
1353
1376
1354 def __init__(self, values, default_value=None, **metadata):
1377 def __init__(self, values, default_value=None, **metadata):
1355 self.values = values
1378 self.values = values
1356 super(Enum, self).__init__(default_value, **metadata)
1379 super(Enum, self).__init__(default_value, **metadata)
1357
1380
1358 def validate(self, obj, value):
1381 def validate(self, obj, value):
1359 if value in self.values:
1382 if value in self.values:
1360 return value
1383 return value
1361 self.error(obj, value)
1384 self.error(obj, value)
1362
1385
1363 def info(self):
1386 def info(self):
1364 """ Returns a description of the trait."""
1387 """ Returns a description of the trait."""
1365 result = 'any of ' + repr(self.values)
1388 result = 'any of ' + repr(self.values)
1366 if self.allow_none:
1389 if self.allow_none:
1367 return result + ' or None'
1390 return result + ' or None'
1368 return result
1391 return result
1369
1392
1370 class CaselessStrEnum(Enum):
1393 class CaselessStrEnum(Enum):
1371 """An enum of strings that are caseless in validate."""
1394 """An enum of strings that are caseless in validate."""
1372
1395
1373 def validate(self, obj, value):
1396 def validate(self, obj, value):
1374 if not isinstance(value, py3compat.string_types):
1397 if not isinstance(value, py3compat.string_types):
1375 self.error(obj, value)
1398 self.error(obj, value)
1376
1399
1377 for v in self.values:
1400 for v in self.values:
1378 if v.lower() == value.lower():
1401 if v.lower() == value.lower():
1379 return v
1402 return v
1380 self.error(obj, value)
1403 self.error(obj, value)
1381
1404
1382 class Container(Instance):
1405 class Container(Instance):
1383 """An instance of a container (list, set, etc.)
1406 """An instance of a container (list, set, etc.)
1384
1407
1385 To be subclassed by overriding klass.
1408 To be subclassed by overriding klass.
1386 """
1409 """
1387 klass = None
1410 klass = None
1388 _cast_types = ()
1411 _cast_types = ()
1389 _valid_defaults = SequenceTypes
1412 _valid_defaults = SequenceTypes
1390 _trait = None
1413 _trait = None
1391
1414
1392 def __init__(self, trait=None, default_value=None, allow_none=False,
1415 def __init__(self, trait=None, default_value=None, allow_none=False,
1393 **metadata):
1416 **metadata):
1394 """Create a container trait type from a list, set, or tuple.
1417 """Create a container trait type from a list, set, or tuple.
1395
1418
1396 The default value is created by doing ``List(default_value)``,
1419 The default value is created by doing ``List(default_value)``,
1397 which creates a copy of the ``default_value``.
1420 which creates a copy of the ``default_value``.
1398
1421
1399 ``trait`` can be specified, which restricts the type of elements
1422 ``trait`` can be specified, which restricts the type of elements
1400 in the container to that TraitType.
1423 in the container to that TraitType.
1401
1424
1402 If only one arg is given and it is not a Trait, it is taken as
1425 If only one arg is given and it is not a Trait, it is taken as
1403 ``default_value``:
1426 ``default_value``:
1404
1427
1405 ``c = List([1,2,3])``
1428 ``c = List([1,2,3])``
1406
1429
1407 Parameters
1430 Parameters
1408 ----------
1431 ----------
1409
1432
1410 trait : TraitType [ optional ]
1433 trait : TraitType [ optional ]
1411 the type for restricting the contents of the Container. If unspecified,
1434 the type for restricting the contents of the Container. If unspecified,
1412 types are not checked.
1435 types are not checked.
1413
1436
1414 default_value : SequenceType [ optional ]
1437 default_value : SequenceType [ optional ]
1415 The default value for the Trait. Must be list/tuple/set, and
1438 The default value for the Trait. Must be list/tuple/set, and
1416 will be cast to the container type.
1439 will be cast to the container type.
1417
1440
1418 allow_none : bool [ default False ]
1441 allow_none : bool [ default False ]
1419 Whether to allow the value to be None
1442 Whether to allow the value to be None
1420
1443
1421 **metadata : any
1444 **metadata : any
1422 further keys for extensions to the Trait (e.g. config)
1445 further keys for extensions to the Trait (e.g. config)
1423
1446
1424 """
1447 """
1425 # allow List([values]):
1448 # allow List([values]):
1426 if default_value is None and not is_trait(trait):
1449 if default_value is None and not is_trait(trait):
1427 default_value = trait
1450 default_value = trait
1428 trait = None
1451 trait = None
1429
1452
1430 if default_value is None:
1453 if default_value is None:
1431 args = ()
1454 args = ()
1432 elif isinstance(default_value, self._valid_defaults):
1455 elif isinstance(default_value, self._valid_defaults):
1433 args = (default_value,)
1456 args = (default_value,)
1434 else:
1457 else:
1435 raise TypeError('default value of %s was %s' %(self.__class__.__name__, default_value))
1458 raise TypeError('default value of %s was %s' %(self.__class__.__name__, default_value))
1436
1459
1437 if is_trait(trait):
1460 if is_trait(trait):
1438 self._trait = trait() if isinstance(trait, type) else trait
1461 self._trait = trait() if isinstance(trait, type) else trait
1439 self._trait.name = 'element'
1462 self._trait.name = 'element'
1440 elif trait is not None:
1463 elif trait is not None:
1441 raise TypeError("`trait` must be a Trait or None, got %s"%repr_type(trait))
1464 raise TypeError("`trait` must be a Trait or None, got %s"%repr_type(trait))
1442
1465
1443 super(Container,self).__init__(klass=self.klass, args=args,
1466 super(Container,self).__init__(klass=self.klass, args=args,
1444 allow_none=allow_none, **metadata)
1467 allow_none=allow_none, **metadata)
1445
1468
1446 def element_error(self, obj, element, validator):
1469 def element_error(self, obj, element, validator):
1447 e = "Element of the '%s' trait of %s instance must be %s, but a value of %s was specified." \
1470 e = "Element of the '%s' trait of %s instance must be %s, but a value of %s was specified." \
1448 % (self.name, class_of(obj), validator.info(), repr_type(element))
1471 % (self.name, class_of(obj), validator.info(), repr_type(element))
1449 raise TraitError(e)
1472 raise TraitError(e)
1450
1473
1451 def validate(self, obj, value):
1474 def validate(self, obj, value):
1452 if isinstance(value, self._cast_types):
1475 if isinstance(value, self._cast_types):
1453 value = self.klass(value)
1476 value = self.klass(value)
1454 value = super(Container, self).validate(obj, value)
1477 value = super(Container, self).validate(obj, value)
1455 if value is None:
1478 if value is None:
1456 return value
1479 return value
1457
1480
1458 value = self.validate_elements(obj, value)
1481 value = self.validate_elements(obj, value)
1459
1482
1460 return value
1483 return value
1461
1484
1462 def validate_elements(self, obj, value):
1485 def validate_elements(self, obj, value):
1463 validated = []
1486 validated = []
1464 if self._trait is None or isinstance(self._trait, Any):
1487 if self._trait is None or isinstance(self._trait, Any):
1465 return value
1488 return value
1466 for v in value:
1489 for v in value:
1467 try:
1490 try:
1468 v = self._trait._validate(obj, v)
1491 v = self._trait._validate(obj, v)
1469 except TraitError:
1492 except TraitError:
1470 self.element_error(obj, v, self._trait)
1493 self.element_error(obj, v, self._trait)
1471 else:
1494 else:
1472 validated.append(v)
1495 validated.append(v)
1473 return self.klass(validated)
1496 return self.klass(validated)
1474
1497
1475 def instance_init(self):
1498 def instance_init(self):
1476 if isinstance(self._trait, TraitType):
1499 if isinstance(self._trait, TraitType):
1477 self._trait.this_class = self.this_class
1500 self._trait.this_class = self.this_class
1478 self._trait.instance_init()
1501 self._trait.instance_init()
1479 super(Container, self).instance_init()
1502 super(Container, self).instance_init()
1480
1503
1481
1504
1482 class List(Container):
1505 class List(Container):
1483 """An instance of a Python list."""
1506 """An instance of a Python list."""
1484 klass = list
1507 klass = list
1485 _cast_types = (tuple,)
1508 _cast_types = (tuple,)
1486
1509
1487 def __init__(self, trait=None, default_value=None, minlen=0, maxlen=sys.maxsize, **metadata):
1510 def __init__(self, trait=None, default_value=None, minlen=0, maxlen=sys.maxsize, **metadata):
1488 """Create a List trait type from a list, set, or tuple.
1511 """Create a List trait type from a list, set, or tuple.
1489
1512
1490 The default value is created by doing ``List(default_value)``,
1513 The default value is created by doing ``List(default_value)``,
1491 which creates a copy of the ``default_value``.
1514 which creates a copy of the ``default_value``.
1492
1515
1493 ``trait`` can be specified, which restricts the type of elements
1516 ``trait`` can be specified, which restricts the type of elements
1494 in the container to that TraitType.
1517 in the container to that TraitType.
1495
1518
1496 If only one arg is given and it is not a Trait, it is taken as
1519 If only one arg is given and it is not a Trait, it is taken as
1497 ``default_value``:
1520 ``default_value``:
1498
1521
1499 ``c = List([1,2,3])``
1522 ``c = List([1,2,3])``
1500
1523
1501 Parameters
1524 Parameters
1502 ----------
1525 ----------
1503
1526
1504 trait : TraitType [ optional ]
1527 trait : TraitType [ optional ]
1505 the type for restricting the contents of the Container. If unspecified,
1528 the type for restricting the contents of the Container. If unspecified,
1506 types are not checked.
1529 types are not checked.
1507
1530
1508 default_value : SequenceType [ optional ]
1531 default_value : SequenceType [ optional ]
1509 The default value for the Trait. Must be list/tuple/set, and
1532 The default value for the Trait. Must be list/tuple/set, and
1510 will be cast to the container type.
1533 will be cast to the container type.
1511
1534
1512 minlen : Int [ default 0 ]
1535 minlen : Int [ default 0 ]
1513 The minimum length of the input list
1536 The minimum length of the input list
1514
1537
1515 maxlen : Int [ default sys.maxsize ]
1538 maxlen : Int [ default sys.maxsize ]
1516 The maximum length of the input list
1539 The maximum length of the input list
1517
1540
1518 allow_none : bool [ default False ]
1541 allow_none : bool [ default False ]
1519 Whether to allow the value to be None
1542 Whether to allow the value to be None
1520
1543
1521 **metadata : any
1544 **metadata : any
1522 further keys for extensions to the Trait (e.g. config)
1545 further keys for extensions to the Trait (e.g. config)
1523
1546
1524 """
1547 """
1525 self._minlen = minlen
1548 self._minlen = minlen
1526 self._maxlen = maxlen
1549 self._maxlen = maxlen
1527 super(List, self).__init__(trait=trait, default_value=default_value,
1550 super(List, self).__init__(trait=trait, default_value=default_value,
1528 **metadata)
1551 **metadata)
1529
1552
1530 def length_error(self, obj, value):
1553 def length_error(self, obj, value):
1531 e = "The '%s' trait of %s instance must be of length %i <= L <= %i, but a value of %s was specified." \
1554 e = "The '%s' trait of %s instance must be of length %i <= L <= %i, but a value of %s was specified." \
1532 % (self.name, class_of(obj), self._minlen, self._maxlen, value)
1555 % (self.name, class_of(obj), self._minlen, self._maxlen, value)
1533 raise TraitError(e)
1556 raise TraitError(e)
1534
1557
1535 def validate_elements(self, obj, value):
1558 def validate_elements(self, obj, value):
1536 length = len(value)
1559 length = len(value)
1537 if length < self._minlen or length > self._maxlen:
1560 if length < self._minlen or length > self._maxlen:
1538 self.length_error(obj, value)
1561 self.length_error(obj, value)
1539
1562
1540 return super(List, self).validate_elements(obj, value)
1563 return super(List, self).validate_elements(obj, value)
1541
1564
1542 def validate(self, obj, value):
1565 def validate(self, obj, value):
1543 value = super(List, self).validate(obj, value)
1566 value = super(List, self).validate(obj, value)
1544 value = self.validate_elements(obj, value)
1567 value = self.validate_elements(obj, value)
1545 return value
1568 return value
1546
1569
1547
1570
1548 class Set(List):
1571 class Set(List):
1549 """An instance of a Python set."""
1572 """An instance of a Python set."""
1550 klass = set
1573 klass = set
1551 _cast_types = (tuple, list)
1574 _cast_types = (tuple, list)
1552
1575
1553
1576
1554 class Tuple(Container):
1577 class Tuple(Container):
1555 """An instance of a Python tuple."""
1578 """An instance of a Python tuple."""
1556 klass = tuple
1579 klass = tuple
1557 _cast_types = (list,)
1580 _cast_types = (list,)
1558
1581
1559 def __init__(self, *traits, **metadata):
1582 def __init__(self, *traits, **metadata):
1560 """Tuple(*traits, default_value=None, **medatata)
1583 """Tuple(*traits, default_value=None, **medatata)
1561
1584
1562 Create a tuple from a list, set, or tuple.
1585 Create a tuple from a list, set, or tuple.
1563
1586
1564 Create a fixed-type tuple with Traits:
1587 Create a fixed-type tuple with Traits:
1565
1588
1566 ``t = Tuple(Int, Str, CStr)``
1589 ``t = Tuple(Int, Str, CStr)``
1567
1590
1568 would be length 3, with Int,Str,CStr for each element.
1591 would be length 3, with Int,Str,CStr for each element.
1569
1592
1570 If only one arg is given and it is not a Trait, it is taken as
1593 If only one arg is given and it is not a Trait, it is taken as
1571 default_value:
1594 default_value:
1572
1595
1573 ``t = Tuple((1,2,3))``
1596 ``t = Tuple((1,2,3))``
1574
1597
1575 Otherwise, ``default_value`` *must* be specified by keyword.
1598 Otherwise, ``default_value`` *must* be specified by keyword.
1576
1599
1577 Parameters
1600 Parameters
1578 ----------
1601 ----------
1579
1602
1580 *traits : TraitTypes [ optional ]
1603 *traits : TraitTypes [ optional ]
1581 the tsype for restricting the contents of the Tuple. If unspecified,
1604 the tsype for restricting the contents of the Tuple. If unspecified,
1582 types are not checked. If specified, then each positional argument
1605 types are not checked. If specified, then each positional argument
1583 corresponds to an element of the tuple. Tuples defined with traits
1606 corresponds to an element of the tuple. Tuples defined with traits
1584 are of fixed length.
1607 are of fixed length.
1585
1608
1586 default_value : SequenceType [ optional ]
1609 default_value : SequenceType [ optional ]
1587 The default value for the Tuple. Must be list/tuple/set, and
1610 The default value for the Tuple. Must be list/tuple/set, and
1588 will be cast to a tuple. If `traits` are specified, the
1611 will be cast to a tuple. If `traits` are specified, the
1589 `default_value` must conform to the shape and type they specify.
1612 `default_value` must conform to the shape and type they specify.
1590
1613
1591 allow_none : bool [ default False ]
1614 allow_none : bool [ default False ]
1592 Whether to allow the value to be None
1615 Whether to allow the value to be None
1593
1616
1594 **metadata : any
1617 **metadata : any
1595 further keys for extensions to the Trait (e.g. config)
1618 further keys for extensions to the Trait (e.g. config)
1596
1619
1597 """
1620 """
1598 default_value = metadata.pop('default_value', None)
1621 default_value = metadata.pop('default_value', None)
1599 allow_none = metadata.pop('allow_none', True)
1622 allow_none = metadata.pop('allow_none', True)
1600
1623
1601 # allow Tuple((values,)):
1624 # allow Tuple((values,)):
1602 if len(traits) == 1 and default_value is None and not is_trait(traits[0]):
1625 if len(traits) == 1 and default_value is None and not is_trait(traits[0]):
1603 default_value = traits[0]
1626 default_value = traits[0]
1604 traits = ()
1627 traits = ()
1605
1628
1606 if default_value is None:
1629 if default_value is None:
1607 args = ()
1630 args = ()
1608 elif isinstance(default_value, self._valid_defaults):
1631 elif isinstance(default_value, self._valid_defaults):
1609 args = (default_value,)
1632 args = (default_value,)
1610 else:
1633 else:
1611 raise TypeError('default value of %s was %s' %(self.__class__.__name__, default_value))
1634 raise TypeError('default value of %s was %s' %(self.__class__.__name__, default_value))
1612
1635
1613 self._traits = []
1636 self._traits = []
1614 for trait in traits:
1637 for trait in traits:
1615 t = trait() if isinstance(trait, type) else trait
1638 t = trait() if isinstance(trait, type) else trait
1616 t.name = 'element'
1639 t.name = 'element'
1617 self._traits.append(t)
1640 self._traits.append(t)
1618
1641
1619 if self._traits and default_value is None:
1642 if self._traits and default_value is None:
1620 # don't allow default to be an empty container if length is specified
1643 # don't allow default to be an empty container if length is specified
1621 args = None
1644 args = None
1622 super(Container,self).__init__(klass=self.klass, args=args, **metadata)
1645 super(Container,self).__init__(klass=self.klass, args=args, **metadata)
1623
1646
1624 def validate_elements(self, obj, value):
1647 def validate_elements(self, obj, value):
1625 if not self._traits:
1648 if not self._traits:
1626 # nothing to validate
1649 # nothing to validate
1627 return value
1650 return value
1628 if len(value) != len(self._traits):
1651 if len(value) != len(self._traits):
1629 e = "The '%s' trait of %s instance requires %i elements, but a value of %s was specified." \
1652 e = "The '%s' trait of %s instance requires %i elements, but a value of %s was specified." \
1630 % (self.name, class_of(obj), len(self._traits), repr_type(value))
1653 % (self.name, class_of(obj), len(self._traits), repr_type(value))
1631 raise TraitError(e)
1654 raise TraitError(e)
1632
1655
1633 validated = []
1656 validated = []
1634 for t, v in zip(self._traits, value):
1657 for t, v in zip(self._traits, value):
1635 try:
1658 try:
1636 v = t._validate(obj, v)
1659 v = t._validate(obj, v)
1637 except TraitError:
1660 except TraitError:
1638 self.element_error(obj, v, t)
1661 self.element_error(obj, v, t)
1639 else:
1662 else:
1640 validated.append(v)
1663 validated.append(v)
1641 return tuple(validated)
1664 return tuple(validated)
1642
1665
1643 def instance_init(self):
1666 def instance_init(self):
1644 for trait in self._traits:
1667 for trait in self._traits:
1645 if isinstance(trait, TraitType):
1668 if isinstance(trait, TraitType):
1646 trait.this_class = self.this_class
1669 trait.this_class = self.this_class
1647 trait.instance_init()
1670 trait.instance_init()
1648 super(Container, self).instance_init()
1671 super(Container, self).instance_init()
1649
1672
1650
1673
1651 class Dict(Instance):
1674 class Dict(Instance):
1652 """An instance of a Python dict."""
1675 """An instance of a Python dict."""
1653 _trait = None
1676 _trait = None
1654
1677
1655 def __init__(self, trait=None, default_value=NoDefaultSpecified, allow_none=False, **metadata):
1678 def __init__(self, trait=None, default_value=NoDefaultSpecified, allow_none=False, **metadata):
1656 """Create a dict trait type from a dict.
1679 """Create a dict trait type from a dict.
1657
1680
1658 The default value is created by doing ``dict(default_value)``,
1681 The default value is created by doing ``dict(default_value)``,
1659 which creates a copy of the ``default_value``.
1682 which creates a copy of the ``default_value``.
1660
1683
1661 trait : TraitType [ optional ]
1684 trait : TraitType [ optional ]
1662 the type for restricting the contents of the Container. If unspecified,
1685 the type for restricting the contents of the Container. If unspecified,
1663 types are not checked.
1686 types are not checked.
1664
1687
1665 default_value : SequenceType [ optional ]
1688 default_value : SequenceType [ optional ]
1666 The default value for the Dict. Must be dict, tuple, or None, and
1689 The default value for the Dict. Must be dict, tuple, or None, and
1667 will be cast to a dict if not None. If `trait` is specified, the
1690 will be cast to a dict if not None. If `trait` is specified, the
1668 `default_value` must conform to the constraints it specifies.
1691 `default_value` must conform to the constraints it specifies.
1669
1692
1670 allow_none : bool [ default False ]
1693 allow_none : bool [ default False ]
1671 Whether to allow the value to be None
1694 Whether to allow the value to be None
1672
1695
1673 """
1696 """
1674 if default_value is NoDefaultSpecified and trait is not None:
1697 if default_value is NoDefaultSpecified and trait is not None:
1675 if not is_trait(trait):
1698 if not is_trait(trait):
1676 default_value = trait
1699 default_value = trait
1677 trait = None
1700 trait = None
1678 if default_value is NoDefaultSpecified:
1701 if default_value is NoDefaultSpecified:
1679 default_value = {}
1702 default_value = {}
1680 if default_value is None:
1703 if default_value is None:
1681 args = None
1704 args = None
1682 elif isinstance(default_value, dict):
1705 elif isinstance(default_value, dict):
1683 args = (default_value,)
1706 args = (default_value,)
1684 elif isinstance(default_value, SequenceTypes):
1707 elif isinstance(default_value, SequenceTypes):
1685 args = (default_value,)
1708 args = (default_value,)
1686 else:
1709 else:
1687 raise TypeError('default value of Dict was %s' % default_value)
1710 raise TypeError('default value of Dict was %s' % default_value)
1688
1711
1689 if is_trait(trait):
1712 if is_trait(trait):
1690 self._trait = trait() if isinstance(trait, type) else trait
1713 self._trait = trait() if isinstance(trait, type) else trait
1691 self._trait.name = 'element'
1714 self._trait.name = 'element'
1692 elif trait is not None:
1715 elif trait is not None:
1693 raise TypeError("`trait` must be a Trait or None, got %s"%repr_type(trait))
1716 raise TypeError("`trait` must be a Trait or None, got %s"%repr_type(trait))
1694
1717
1695 super(Dict,self).__init__(klass=dict, args=args,
1718 super(Dict,self).__init__(klass=dict, args=args,
1696 allow_none=allow_none, **metadata)
1719 allow_none=allow_none, **metadata)
1697
1720
1698 def element_error(self, obj, element, validator):
1721 def element_error(self, obj, element, validator):
1699 e = "Element of the '%s' trait of %s instance must be %s, but a value of %s was specified." \
1722 e = "Element of the '%s' trait of %s instance must be %s, but a value of %s was specified." \
1700 % (self.name, class_of(obj), validator.info(), repr_type(element))
1723 % (self.name, class_of(obj), validator.info(), repr_type(element))
1701 raise TraitError(e)
1724 raise TraitError(e)
1702
1725
1703 def validate(self, obj, value):
1726 def validate(self, obj, value):
1704 value = super(Dict, self).validate(obj, value)
1727 value = super(Dict, self).validate(obj, value)
1705 if value is None:
1728 if value is None:
1706 return value
1729 return value
1707 value = self.validate_elements(obj, value)
1730 value = self.validate_elements(obj, value)
1708 return value
1731 return value
1709
1732
1710 def validate_elements(self, obj, value):
1733 def validate_elements(self, obj, value):
1711 if self._trait is None or isinstance(self._trait, Any):
1734 if self._trait is None or isinstance(self._trait, Any):
1712 return value
1735 return value
1713 validated = {}
1736 validated = {}
1714 for key in value:
1737 for key in value:
1715 v = value[key]
1738 v = value[key]
1716 try:
1739 try:
1717 v = self._trait._validate(obj, v)
1740 v = self._trait._validate(obj, v)
1718 except TraitError:
1741 except TraitError:
1719 self.element_error(obj, v, self._trait)
1742 self.element_error(obj, v, self._trait)
1720 else:
1743 else:
1721 validated[key] = v
1744 validated[key] = v
1722 return self.klass(validated)
1745 return self.klass(validated)
1723
1746
1724 def instance_init(self):
1747 def instance_init(self):
1725 if isinstance(self._trait, TraitType):
1748 if isinstance(self._trait, TraitType):
1726 self._trait.this_class = self.this_class
1749 self._trait.this_class = self.this_class
1727 self._trait.instance_init()
1750 self._trait.instance_init()
1728 super(Dict, self).instance_init()
1751 super(Dict, self).instance_init()
1729
1752
1730
1753
1731 class EventfulDict(Instance):
1754 class EventfulDict(Instance):
1732 """An instance of an EventfulDict."""
1755 """An instance of an EventfulDict."""
1733
1756
1734 def __init__(self, default_value={}, allow_none=False, **metadata):
1757 def __init__(self, default_value={}, allow_none=False, **metadata):
1735 """Create a EventfulDict trait type from a dict.
1758 """Create a EventfulDict trait type from a dict.
1736
1759
1737 The default value is created by doing
1760 The default value is created by doing
1738 ``eventful.EvenfulDict(default_value)``, which creates a copy of the
1761 ``eventful.EvenfulDict(default_value)``, which creates a copy of the
1739 ``default_value``.
1762 ``default_value``.
1740 """
1763 """
1741 if default_value is None:
1764 if default_value is None:
1742 args = None
1765 args = None
1743 elif isinstance(default_value, dict):
1766 elif isinstance(default_value, dict):
1744 args = (default_value,)
1767 args = (default_value,)
1745 elif isinstance(default_value, SequenceTypes):
1768 elif isinstance(default_value, SequenceTypes):
1746 args = (default_value,)
1769 args = (default_value,)
1747 else:
1770 else:
1748 raise TypeError('default value of EventfulDict was %s' % default_value)
1771 raise TypeError('default value of EventfulDict was %s' % default_value)
1749
1772
1750 super(EventfulDict, self).__init__(klass=eventful.EventfulDict, args=args,
1773 super(EventfulDict, self).__init__(klass=eventful.EventfulDict, args=args,
1751 allow_none=allow_none, **metadata)
1774 allow_none=allow_none, **metadata)
1752
1775
1753
1776
1754 class EventfulList(Instance):
1777 class EventfulList(Instance):
1755 """An instance of an EventfulList."""
1778 """An instance of an EventfulList."""
1756
1779
1757 def __init__(self, default_value=None, allow_none=False, **metadata):
1780 def __init__(self, default_value=None, allow_none=False, **metadata):
1758 """Create a EventfulList trait type from a dict.
1781 """Create a EventfulList trait type from a dict.
1759
1782
1760 The default value is created by doing
1783 The default value is created by doing
1761 ``eventful.EvenfulList(default_value)``, which creates a copy of the
1784 ``eventful.EvenfulList(default_value)``, which creates a copy of the
1762 ``default_value``.
1785 ``default_value``.
1763 """
1786 """
1764 if default_value is None:
1787 if default_value is None:
1765 args = ((),)
1788 args = ((),)
1766 else:
1789 else:
1767 args = (default_value,)
1790 args = (default_value,)
1768
1791
1769 super(EventfulList, self).__init__(klass=eventful.EventfulList, args=args,
1792 super(EventfulList, self).__init__(klass=eventful.EventfulList, args=args,
1770 allow_none=allow_none, **metadata)
1793 allow_none=allow_none, **metadata)
1771
1794
1772
1795
1773 class TCPAddress(TraitType):
1796 class TCPAddress(TraitType):
1774 """A trait for an (ip, port) tuple.
1797 """A trait for an (ip, port) tuple.
1775
1798
1776 This allows for both IPv4 IP addresses as well as hostnames.
1799 This allows for both IPv4 IP addresses as well as hostnames.
1777 """
1800 """
1778
1801
1779 default_value = ('127.0.0.1', 0)
1802 default_value = ('127.0.0.1', 0)
1780 info_text = 'an (ip, port) tuple'
1803 info_text = 'an (ip, port) tuple'
1781
1804
1782 def validate(self, obj, value):
1805 def validate(self, obj, value):
1783 if isinstance(value, tuple):
1806 if isinstance(value, tuple):
1784 if len(value) == 2:
1807 if len(value) == 2:
1785 if isinstance(value[0], py3compat.string_types) and isinstance(value[1], int):
1808 if isinstance(value[0], py3compat.string_types) and isinstance(value[1], int):
1786 port = value[1]
1809 port = value[1]
1787 if port >= 0 and port <= 65535:
1810 if port >= 0 and port <= 65535:
1788 return value
1811 return value
1789 self.error(obj, value)
1812 self.error(obj, value)
1790
1813
1791 class CRegExp(TraitType):
1814 class CRegExp(TraitType):
1792 """A casting compiled regular expression trait.
1815 """A casting compiled regular expression trait.
1793
1816
1794 Accepts both strings and compiled regular expressions. The resulting
1817 Accepts both strings and compiled regular expressions. The resulting
1795 attribute will be a compiled regular expression."""
1818 attribute will be a compiled regular expression."""
1796
1819
1797 info_text = 'a regular expression'
1820 info_text = 'a regular expression'
1798
1821
1799 def validate(self, obj, value):
1822 def validate(self, obj, value):
1800 try:
1823 try:
1801 return re.compile(value)
1824 return re.compile(value)
1802 except:
1825 except:
1803 self.error(obj, value)
1826 self.error(obj, value)
General Comments 0
You need to be logged in to leave comments. Login now