Implement __repr__ instead of __str__ for python Value
[babeltrace.git] / bindings / python / bt2 / bt2 / values.py
CommitLineData
81447b5b
PP
1# The MIT License (MIT)
2#
811644b8 3# Copyright (c) 2017 Philippe Proulx <pproulx@efficios.com>
81447b5b
PP
4#
5# Permission is hereby granted, free of charge, to any person obtaining a copy
6# of this software and associated documentation files (the "Software"), to deal
7# in the Software without restriction, including without limitation the rights
8# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9# copies of the Software, and to permit persons to whom the Software is
10# furnished to do so, subject to the following conditions:
11#
12# The above copyright notice and this permission notice shall be included in
13# all copies or substantial portions of the Software.
14#
15# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21# THE SOFTWARE.
22
23from bt2 import native_bt, object, utils
24import collections.abc
25import functools
26import numbers
27import math
28import abc
29import bt2
30
31
32def _handle_status(status, obj_name):
33 if status >= 0:
34 return
35
36 if status == native_bt.VALUE_STATUS_FROZEN:
811644b8 37 raise bt2.Frozen('{} value object is frozen'.format(obj_name))
81447b5b
PP
38 elif status == native_bt.VALUE_STATUS_INVAL:
39 # In practice, this should never happen, because arguments
40 # should always be validated in this Python module before
41 # calling the native functions.
42 raise ValueError('unexpected invalid argument')
43 else:
44 # In practice, this should never happen, because arguments
45 # should always be validated in this Python module before
46 # calling the native functions.
47 raise RuntimeError('unexpected error')
48
49
50def _create_from_ptr(ptr):
51 if ptr is None or ptr == native_bt.value_null:
52 return
53
54 typeid = native_bt.value_get_type(ptr)
55 return _TYPE_TO_OBJ[typeid]._create_from_ptr(ptr)
56
57
58def create_value(value):
59 if value is None:
60 # null value object
61 return
62
63 if isinstance(value, _Value):
64 return value
65
66 if isinstance(value, bool):
67 return BoolValue(value)
68
69 if isinstance(value, int):
70 return IntegerValue(value)
71
72 if isinstance(value, float):
73 return FloatValue(value)
74
75 if isinstance(value, str):
76 return StringValue(value)
77
78 try:
79 return MapValue(value)
80 except:
81 pass
82
83 try:
84 return ArrayValue(value)
85 except:
86 pass
87
88 raise TypeError("cannot create value object from '{}' object".format(value.__class__.__name__))
89
90
91class _Value(object._Object, object._Freezable, metaclass=abc.ABCMeta):
81447b5b
PP
92 def __eq__(self, other):
93 if other is None:
94 # self is never the null value object
95 return False
96
97 # try type-specific comparison first
98 spec_eq = self._spec_eq(other)
99
100 if spec_eq is not None:
101 return spec_eq
102
103 if not isinstance(other, _Value):
104 # not comparing apples to apples
105 return False
106
107 # fall back to native comparison function
108 return native_bt.value_compare(self._ptr, other._ptr)
109
110 def __ne__(self, other):
111 return not (self == other)
112
113 @abc.abstractmethod
114 def _spec_eq(self, other):
115 pass
116
117 def _handle_status(self, status):
118 _handle_status(status, self._NAME)
119
120 def _check_create_status(self, ptr):
121 if ptr is None:
122 raise bt2.CreationError('cannot create {} value object'.format(self._NAME.lower()))
123
124 def _is_frozen(self):
125 return native_bt.value_is_frozen(self._ptr)
126
127 def _freeze(self):
128 status = native_bt.value_freeze(self._ptr)
129 self._handle_status(status)
130
131
132class _BasicCopy:
133 def __copy__(self):
9b6cd4a7 134 return self.__class__(self._value)
81447b5b
PP
135
136 def __deepcopy__(self, memo):
137 copy = self.__copy__()
138 memo[id(self)] = copy
139 return copy
140
141
142@functools.total_ordering
143class _NumericValue(_Value, _BasicCopy):
144 @staticmethod
145 def _extract_value(other):
146 if isinstance(other, _NumericValue):
9b6cd4a7 147 return other._value
81447b5b
PP
148
149 if other is True or other is False:
150 return other
151
152 if isinstance(other, numbers.Integral):
153 return int(other)
154
155 if isinstance(other, numbers.Real):
156 return float(other)
157
158 if isinstance(other, numbers.Complex):
159 return complex(other)
160
161 raise TypeError("'{}' object is not a number object".format(other.__class__.__name__))
162
163 def __int__(self):
9b6cd4a7 164 return int(self._value)
81447b5b
PP
165
166 def __float__(self):
9b6cd4a7 167 return float(self._value)
81447b5b 168
83656269
JG
169 def __repr__(self):
170 return repr(self._value)
81447b5b
PP
171
172 def __lt__(self, other):
173 if not isinstance(other, numbers.Number):
174 raise TypeError('unorderable types: {}() < {}()'.format(self.__class__.__name__,
175 other.__class__.__name__))
176
9b6cd4a7 177 return self._value < float(other)
81447b5b
PP
178
179 def __le__(self, other):
180 if not isinstance(other, numbers.Number):
181 raise TypeError('unorderable types: {}() <= {}()'.format(self.__class__.__name__,
182 other.__class__.__name__))
183
9b6cd4a7 184 return self._value <= float(other)
81447b5b
PP
185
186 def _spec_eq(self, other):
811644b8 187 pass
81447b5b
PP
188
189 def __eq__(self, other):
190 if not isinstance(other, numbers.Number):
191 return False
192
9b6cd4a7 193 return self._value == complex(other)
81447b5b
PP
194
195 def __rmod__(self, other):
9b6cd4a7 196 return self._extract_value(other) % self._value
81447b5b
PP
197
198 def __mod__(self, other):
9b6cd4a7 199 return self._value % self._extract_value(other)
81447b5b
PP
200
201 def __rfloordiv__(self, other):
9b6cd4a7 202 return self._extract_value(other) // self._value
81447b5b
PP
203
204 def __floordiv__(self, other):
9b6cd4a7 205 return self._value // self._extract_value(other)
81447b5b
PP
206
207 def __round__(self, ndigits=None):
208 if ndigits is None:
9b6cd4a7 209 return round(self._value)
81447b5b 210 else:
9b6cd4a7 211 return round(self._value, ndigits)
81447b5b
PP
212
213 def __ceil__(self):
9b6cd4a7 214 return math.ceil(self._value)
81447b5b
PP
215
216 def __floor__(self):
9b6cd4a7 217 return math.floor(self._value)
81447b5b
PP
218
219 def __trunc__(self):
9b6cd4a7 220 return int(self._value)
81447b5b
PP
221
222 def __abs__(self):
9b6cd4a7 223 return abs(self._value)
81447b5b
PP
224
225 def __add__(self, other):
9b6cd4a7 226 return self._value + self._extract_value(other)
81447b5b
PP
227
228 def __radd__(self, other):
229 return self.__add__(other)
230
231 def __neg__(self):
9b6cd4a7 232 return -self._value
81447b5b
PP
233
234 def __pos__(self):
9b6cd4a7 235 return +self._value
81447b5b
PP
236
237 def __mul__(self, other):
9b6cd4a7 238 return self._value * self._extract_value(other)
81447b5b
PP
239
240 def __rmul__(self, other):
241 return self.__mul__(other)
242
243 def __truediv__(self, other):
9b6cd4a7 244 return self._value / self._extract_value(other)
81447b5b
PP
245
246 def __rtruediv__(self, other):
9b6cd4a7 247 return self._extract_value(other) / self._value
81447b5b
PP
248
249 def __pow__(self, exponent):
9b6cd4a7 250 return self._value ** self._extract_value(exponent)
81447b5b
PP
251
252 def __rpow__(self, base):
9b6cd4a7 253 return self._extract_value(base) ** self._value
81447b5b
PP
254
255 def __iadd__(self, other):
256 self.value = self + other
257 return self
258
259 def __isub__(self, other):
260 self.value = self - other
261 return self
262
263 def __imul__(self, other):
264 self.value = self * other
265 return self
266
267 def __itruediv__(self, other):
268 self.value = self / other
269 return self
270
271 def __ifloordiv__(self, other):
272 self.value = self // other
273 return self
274
275 def __imod__(self, other):
276 self.value = self % other
277 return self
278
279 def __ipow__(self, other):
280 self.value = self ** other
281 return self
282
283
284class _IntegralValue(_NumericValue, numbers.Integral):
285 def __lshift__(self, other):
9b6cd4a7 286 return self._value << self._extract_value(other)
81447b5b
PP
287
288 def __rlshift__(self, other):
9b6cd4a7 289 return self._extract_value(other) << self._value
81447b5b
PP
290
291 def __rshift__(self, other):
9b6cd4a7 292 return self._value >> self._extract_value(other)
81447b5b
PP
293
294 def __rrshift__(self, other):
9b6cd4a7 295 return self._extract_value(other) >> self._value
81447b5b
PP
296
297 def __and__(self, other):
9b6cd4a7 298 return self._value & self._extract_value(other)
81447b5b
PP
299
300 def __rand__(self, other):
9b6cd4a7 301 return self._extract_value(other) & self._value
81447b5b
PP
302
303 def __xor__(self, other):
9b6cd4a7 304 return self._value ^ self._extract_value(other)
81447b5b
PP
305
306 def __rxor__(self, other):
9b6cd4a7 307 return self._extract_value(other) ^ self._value
81447b5b
PP
308
309 def __or__(self, other):
9b6cd4a7 310 return self._value | self._extract_value(other)
81447b5b
PP
311
312 def __ror__(self, other):
9b6cd4a7 313 return self._extract_value(other) | self._value
81447b5b
PP
314
315 def __invert__(self):
9b6cd4a7 316 return ~self._value
81447b5b
PP
317
318 def __ilshift__(self, other):
319 self.value = self << other
320 return self
321
322 def __irshift__(self, other):
323 self.value = self >> other
324 return self
325
326 def __iand__(self, other):
327 self.value = self & other
328 return self
329
330 def __ixor__(self, other):
331 self.value = self ^ other
332 return self
333
334 def __ior__(self, other):
335 self.value = self | other
336 return self
337
338
339class _RealValue(_NumericValue, numbers.Real):
340 pass
341
342
343class BoolValue(_Value, _BasicCopy):
344 _NAME = 'Boolean'
345
346 def __init__(self, value=None):
347 if value is None:
348 ptr = native_bt.value_bool_create()
349 else:
350 ptr = native_bt.value_bool_create_init(self._value_to_bool(value))
351
352 self._check_create_status(ptr)
353 super().__init__(ptr)
354
355 def _spec_eq(self, other):
356 if isinstance(other, numbers.Number):
9b6cd4a7 357 return self._value == bool(other)
81447b5b
PP
358
359 def __bool__(self):
9b6cd4a7 360 return self._value
81447b5b 361
83656269
JG
362 def __repr__(self):
363 return repr(self._value)
81447b5b
PP
364
365 def _value_to_bool(self, value):
366 if isinstance(value, BoolValue):
9b6cd4a7 367 value = value._value
81447b5b
PP
368
369 if not isinstance(value, bool):
370 raise TypeError("'{}' object is not a 'bool' or 'BoolValue' object".format(value.__class__))
371
811644b8 372 return int(value)
81447b5b
PP
373
374 @property
9b6cd4a7 375 def _value(self):
81447b5b 376 status, value = native_bt.value_bool_get(self._ptr)
811644b8
PP
377 assert(status == native_bt.VALUE_STATUS_OK)
378 return value > 0
81447b5b 379
9b6cd4a7 380 def _set_value(self, value):
81447b5b
PP
381 status = native_bt.value_bool_set(self._ptr, self._value_to_bool(value))
382 self._handle_status(status)
383
9b6cd4a7
PP
384 value = property(fset=_set_value)
385
81447b5b
PP
386
387class IntegerValue(_IntegralValue):
388 _NAME = 'Integer'
389
390 def __init__(self, value=None):
391 if value is None:
392 ptr = native_bt.value_integer_create()
393 else:
394 ptr = native_bt.value_integer_create_init(self._value_to_int(value))
395
396 self._check_create_status(ptr)
397 super().__init__(ptr)
398
399 def _value_to_int(self, value):
400 if not isinstance(value, numbers.Real):
401 raise TypeError('expecting a number object')
402
403 value = int(value)
404 utils._check_int64(value)
405 return value
406
407 @property
9b6cd4a7 408 def _value(self):
81447b5b 409 status, value = native_bt.value_integer_get(self._ptr)
811644b8 410 assert(status == native_bt.VALUE_STATUS_OK)
81447b5b
PP
411 return value
412
9b6cd4a7 413 def _set_value(self, value):
81447b5b
PP
414 status = native_bt.value_integer_set(self._ptr, self._value_to_int(value))
415 self._handle_status(status)
416
9b6cd4a7
PP
417 value = property(fset=_set_value)
418
81447b5b
PP
419
420class FloatValue(_RealValue):
421 _NAME = 'Floating point number'
422
423 def __init__(self, value=None):
424 if value is None:
425 ptr = native_bt.value_float_create()
426 else:
427 value = self._value_to_float(value)
428 ptr = native_bt.value_float_create_init(value)
429
430 self._check_create_status(ptr)
431 super().__init__(ptr)
432
433 def _value_to_float(self, value):
434 if not isinstance(value, numbers.Real):
435 raise TypeError("expecting a real number object")
436
437 return float(value)
438
439 @property
9b6cd4a7 440 def _value(self):
81447b5b 441 status, value = native_bt.value_float_get(self._ptr)
811644b8 442 assert(status == native_bt.VALUE_STATUS_OK)
81447b5b
PP
443 return value
444
9b6cd4a7 445 def _set_value(self, value):
81447b5b
PP
446 value = self._value_to_float(value)
447 status = native_bt.value_float_set(self._ptr, value)
448 self._handle_status(status)
449
9b6cd4a7
PP
450 value = property(fset=_set_value)
451
81447b5b
PP
452
453@functools.total_ordering
454class StringValue(_BasicCopy, collections.abc.Sequence, _Value):
455 _NAME = 'String'
456
457 def __init__(self, value=None):
458 if value is None:
459 ptr = native_bt.value_string_create()
460 else:
461 ptr = native_bt.value_string_create_init(self._value_to_str(value))
462
463 self._check_create_status(ptr)
464 super().__init__(ptr)
465
466 def _value_to_str(self, value):
467 if isinstance(value, self.__class__):
9b6cd4a7 468 value = value._value
81447b5b
PP
469
470 utils._check_str(value)
471 return value
472
473 @property
9b6cd4a7 474 def _value(self):
81447b5b 475 status, value = native_bt.value_string_get(self._ptr)
811644b8 476 assert(status == native_bt.VALUE_STATUS_OK)
81447b5b
PP
477 return value
478
9b6cd4a7 479 def _set_value(self, value):
81447b5b
PP
480 status = native_bt.value_string_set(self._ptr, self._value_to_str(value))
481 self._handle_status(status)
482
9b6cd4a7
PP
483 value = property(fset=_set_value)
484
81447b5b
PP
485 def _spec_eq(self, other):
486 try:
9b6cd4a7 487 return self._value == self._value_to_str(other)
81447b5b
PP
488 except:
489 return
490
491 def __le__(self, other):
9b6cd4a7 492 return self._value <= self._value_to_str(other)
81447b5b
PP
493
494 def __lt__(self, other):
9b6cd4a7 495 return self._value < self._value_to_str(other)
81447b5b
PP
496
497 def __bool__(self):
9b6cd4a7 498 return bool(self._value)
81447b5b 499
83656269
JG
500 def __repr__(self):
501 repr(self._value)
502
81447b5b 503 def __str__(self):
9b6cd4a7 504 return self._value
81447b5b
PP
505
506 def __getitem__(self, index):
9b6cd4a7 507 return self._value[index]
81447b5b
PP
508
509 def __len__(self):
9b6cd4a7 510 return len(self._value)
81447b5b
PP
511
512 def __iadd__(self, value):
9b6cd4a7 513 curvalue = self._value
81447b5b
PP
514 curvalue += self._value_to_str(value)
515 self.value = curvalue
516 return self
517
518
519class _Container:
520 def __bool__(self):
521 return len(self) != 0
522
523 def __copy__(self):
524 return self.__class__(self)
525
526 def __deepcopy__(self, memo):
527 ptr = native_bt.value_copy(self._ptr)
528
529 if ptr is None:
811644b8 530 raise RuntimeError('unexpected error: cannot deep-copy {} value object'.format(self._NAME))
81447b5b
PP
531
532 copy = self.__class__._create_from_ptr(ptr)
533 memo[id(self)] = copy
534 return copy
535
536 def __delitem__(self, index):
537 raise NotImplementedError
538
539
540class ArrayValue(_Container, collections.abc.MutableSequence, _Value):
541 _NAME = 'Array'
542
543 def __init__(self, value=None):
544 ptr = native_bt.value_array_create()
545 self._check_create_status(ptr)
546 super().__init__(ptr)
547
548 # Python will raise a TypeError if there's anything wrong with
549 # the iterable protocol.
550 if value is not None:
551 for elem in value:
552 self.append(elem)
553
554 def _spec_eq(self, other):
555 try:
556 if len(self) != len(other):
557 # early mismatch
558 return False
559
560 for self_elem, other_elem in zip(self, other):
561 if self_elem != other_elem:
562 return False
563
564 return True
565 except:
566 return
567
568 def __len__(self):
569 size = native_bt.value_array_size(self._ptr)
811644b8 570 assert(size >= 0)
81447b5b
PP
571 return size
572
573 def _check_index(self, index):
574 # TODO: support slices also
575 if not isinstance(index, numbers.Integral):
576 raise TypeError("'{}' object is not an integral number object: invalid index".format(index.__class__.__name__))
577
578 index = int(index)
579
580 if index < 0 or index >= len(self):
581 raise IndexError('array value object index is out of range')
582
583 def __getitem__(self, index):
584 self._check_index(index)
585 ptr = native_bt.value_array_get(self._ptr, index)
811644b8 586 assert(ptr)
81447b5b
PP
587 return _create_from_ptr(ptr)
588
589 def __setitem__(self, index, value):
590 self._check_index(index)
591 value = create_value(value)
592
593 if value is None:
594 ptr = native_bt.value_null
595 else:
596 ptr = value._ptr
597
598 status = native_bt.value_array_set(self._ptr, index, ptr)
599 self._handle_status(status)
600
601 def append(self, value):
602 value = create_value(value)
603
604 if value is None:
605 ptr = native_bt.value_null
606 else:
607 ptr = value._ptr
608
609 status = native_bt.value_array_append(self._ptr, ptr)
610 self._handle_status(status)
611
612 def __iadd__(self, iterable):
613 # Python will raise a TypeError if there's anything wrong with
614 # the iterable protocol.
615 for elem in iterable:
616 self.append(elem)
617
618 return self
619
83656269
JG
620 def __repr__(self):
621 return '[{}]'.format(', '.join([repr(v) for v in self]))
81447b5b
PP
622
623 def insert(self, value):
624 raise NotImplementedError
625
626
627class _MapValueKeyIterator(collections.abc.Iterator):
628 def __init__(self, map_obj):
629 self._map_obj = map_obj
630 self._at = 0
631 keys_ptr = native_bt.value_map_get_keys_private(map_obj._ptr)
632
633 if keys_ptr is None:
634 raise RuntimeError('unexpected error: cannot get map value object keys')
635
636 self._keys = _create_from_ptr(keys_ptr)
637
638 def __next__(self):
639 if self._at == len(self._map_obj):
640 raise StopIteration
641
642 key = self._keys[self._at]
643 self._at += 1
644 return str(key)
645
646
647class MapValue(_Container, collections.abc.MutableMapping, _Value):
648 _NAME = 'Map'
649
650 def __init__(self, value=None):
651 ptr = native_bt.value_map_create()
652 self._check_create_status(ptr)
653 super().__init__(ptr)
654
655 # Python will raise a TypeError if there's anything wrong with
656 # the iterable/mapping protocol.
657 if value is not None:
658 for key, elem in value.items():
659 self[key] = elem
660
661 def __eq__(self, other):
662 return _Value.__eq__(self, other)
663
664 def __ne__(self, other):
665 return _Value.__ne__(self, other)
666
667 def _spec_eq(self, other):
668 try:
669 if len(self) != len(other):
670 # early mismatch
671 return False
672
673 for self_key in self:
674 if self_key not in other:
675 return False
676
677 self_value = self[self_key]
678 other_value = other[self_key]
679
680 if self_value != other_value:
681 return False
682
683 return True
684 except:
685 return
686
687 def __len__(self):
688 size = native_bt.value_map_size(self._ptr)
811644b8 689 assert(size >= 0)
81447b5b
PP
690 return size
691
692 def __contains__(self, key):
693 self._check_key_type(key)
694 return native_bt.value_map_has_key(self._ptr, key)
695
696 def _check_key_type(self, key):
697 utils._check_str(key)
698
699 def _check_key(self, key):
700 if key not in self:
701 raise KeyError(key)
702
703 def __getitem__(self, key):
704 self._check_key(key)
705 ptr = native_bt.value_map_get(self._ptr, key)
811644b8 706 assert(ptr)
81447b5b
PP
707 return _create_from_ptr(ptr)
708
709 def __iter__(self):
710 return _MapValueKeyIterator(self)
711
712 def __setitem__(self, key, value):
713 self._check_key_type(key)
714 value = create_value(value)
715
716 if value is None:
717 ptr = native_bt.value_null
718 else:
719 ptr = value._ptr
720
721 status = native_bt.value_map_insert(self._ptr, key, ptr)
722 self._handle_status(status)
723
83656269
JG
724 def __repr__(self):
725 items = ['{}: {}'.format(repr(k), repr(v)) for k, v in self.items()]
726 return '{{{}}}'.format(', '.join(items))
81447b5b
PP
727
728
729_TYPE_TO_OBJ = {
730 native_bt.VALUE_TYPE_BOOL: BoolValue,
731 native_bt.VALUE_TYPE_INTEGER: IntegerValue,
732 native_bt.VALUE_TYPE_FLOAT: FloatValue,
733 native_bt.VALUE_TYPE_STRING: StringValue,
734 native_bt.VALUE_TYPE_ARRAY: ArrayValue,
735 native_bt.VALUE_TYPE_MAP: MapValue,
736}
This page took 0.060253 seconds and 4 git commands to generate.