-
Notifications
You must be signed in to change notification settings - Fork 0
/
element.py
1573 lines (1278 loc) · 55 KB
/
element.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# element.py
"""Provide a representation of an item in a message or request.
This file defines these classes:
'Element' - represents an item in a message.
"""
from .exception import _ExceptionUtil
from .exception import UnsupportedOperationException
from .datetime import _DatetimeUtil
from .datatype import DataType
from .name import Name, getNamePair
from .schema import SchemaElementDefinition
from .utils import Iterator, isNonScalarSequence
from .chandle import CHandle
from . import internals
from .typehints import (
BlpapiNameOrIndex,
AnyPythonDatetime,
SupportedElementTypes,
)
from . import typehints # pylint: disable=unused-import
from collections.abc import Iterator as IteratorABC, Mapping
from typing import (
Any,
Callable,
Dict,
Iterator as IteratorType,
List,
Optional,
Sequence,
Set,
Tuple,
Union,
)
# pylint: disable=protected-access,too-many-return-statements,too-many-public-methods
class ElementIterator(IteratorABC):
"""An iterator over the objects within an :class:`Element`.
If the :class:`Element` is a sequence or choice, this iterates over its
sub-:class:`Element`\ s. Otherwise, iterate over the :class:`Element`\ 's
value(s).
"""
def __init__(self, element: "Element") -> None:
self._element = element
self._index = 0
def __next__(self) -> Union[SupportedElementTypes, "Element"]:
i = self._index
self._index += 1
if self._element.isComplexType():
if self._element.numElements() > i:
return self._element.getElement(i)
# for array and scalar elements
elif self._element.numValues() > i:
return self._element.getValue(i)
raise StopIteration()
class Element(CHandle):
"""Represents an item in a message.
An :class:`Element` can represent:
- A single value of any data type supported by the Bloomberg API
- An array of values
- A sequence or a choice
The value(s) in an :class:`Element` can be queried in a number of ways. For
an :class:`Element` which represents a single value or an array of values
use the :meth:`getValueAsBool()` etc. functions. For an :class:`Element`
which represents a sequence or choice use :meth:`getElementAsBool()` etc.
functions. In addition, for choices and sequences, :meth:`hasElement()` and
:meth:`getElement()` are useful.
This example shows how to access the value of a scalar element ``s`` as a
floating point number::
f = s.getValueAsFloat()
Similarly, this example shows how to retrieve the third value in an array
element ``a``, as a floating point number::
f = a.getValueAsFloat(2)
Use :meth:`numValues()` to determine the number of values available. For
single values, it will return either ``0`` or ``1``. For arrays it will
return the actual number of values in the array.
To retrieve values from a complex element types (sequences and choices) use
the ``getElementAs...()`` family of methods. This example shows how to get
the value of the element ``city`` in the sequence element ``address``::
name_city = Name("city") # Ideally defined once (globally or class level)
city = address.getElementAsString(name_city)
Note:
``getElementAsXYZ(name)`` method is a shortcut to
``getElement(name).getValueAsXYZ()``.
The value(s) of an :class:`Element` can be set in a number of ways. For an
:class:`Element` which represents a single value or an array of values use
the :meth:`setValue()` or :meth:`appendValue()` functions. For an element
which represents a sequence or a choice use the :meth:`setElement()`
functions.
This example shows how to set the value of an :class:`Element` ``s``::
value=5
s.setValue(value)
This example shows how to append a value to an array element ``a``::
value=5
a.appendValue(value)
To set values in a complex element (a sequence or a choice) use the
:meth:`setElement()` family of functions. This example shows how to set the
value of the element ``city`` in the sequence element ``address`` to a
string::
name_city = Name("city") # Ideally defined once (globally or class level)
address.setElement(name_city, "New York")
Methods which specify an :class:`Element` name accept name in two forms:
:class:`Name` or a string. Passing :class:`Name` is more efficient.
However, it requires the :class:`Name` to have been created in the global
name table.
The form which takes a string is less efficient but will not cause a new
:class:`Name` to be created in the global name table. Because all valid
:class:`Element` names will have already been placed in the global name
table by the API if the supplied string cannot be found in the global name
table the appropriate error or exception can be returned.
The API will convert data types as long as there is no loss of precision
involved.
:class:`Element` objects are always created by the API, never directly by
the application.
"""
__boolTraits = (
internals.blpapi_Element_setElementBool,
internals.blpapi_Element_setValueBool,
None,
)
__datetimeTraits = (
internals.blpapi_Element_setElementHighPrecisionDatetime,
internals.blpapi_Element_setValueHighPrecisionDatetime,
_DatetimeUtil.convertToBlpapi,
)
__int32Traits = (
internals.blpapi_Element_setElementInt32,
internals.blpapi_Element_setValueInt32,
None,
)
__int64Traits = (
internals.blpapi_Element_setElementInt64,
internals.blpapi_Element_setValueInt64,
None,
)
__floatTraits = (
internals.blpapi_Element_setElementFloat,
internals.blpapi_Element_setValueFloat,
None,
)
__nameTraits = (
internals.blpapi_Element_setElementFromName,
internals.blpapi_Element_setValueFromName,
Name._handle,
)
__stringTraits = (
internals.blpapi_Element_setElementString,
internals.blpapi_Element_setValueString,
None,
)
__bytesTraits = (
internals.blpapi_Element_setElementBytes,
internals.blpapi_Element_setValueBytes,
None,
)
__defaultTraits = (
internals.blpapi_Element_setElementString,
internals.blpapi_Element_setValueString,
str,
)
@staticmethod
def __getTraits(
value: SupportedElementTypes,
) -> Tuple[Callable, Callable, Optional[Any]]:
"""traits dispatcher"""
if isinstance(value, str):
return Element.__stringTraits
if isinstance(value, bytes):
return Element.__bytesTraits
if isinstance(value, bool):
return Element.__boolTraits
if isinstance(value, int):
if -(2**31) <= value <= (2**31 - 1):
return Element.__int32Traits
if -(2**63) <= value <= (2**63 - 1):
return Element.__int64Traits
raise ValueError("value is out of element's supported range")
if isinstance(value, float):
return Element.__floatTraits
if _DatetimeUtil.isDatetime(value):
return Element.__datetimeTraits
if isinstance(value, Name):
return Element.__nameTraits
return Element.__defaultTraits
def __assertIsValid(self) -> None:
if not self.isValid():
raise RuntimeError("Element is not valid")
def __init__(
self,
handle: "typehints.BlpapiElementHandle",
dataHolder: Optional[
Union["Element", "typehints.Message", "typehints.Request"]
],
) -> None:
noop = lambda *args: None
super(Element, self).__init__(handle, noop)
self.__handle = handle
self.__dataHolder = dataHolder
def _getDataHolder(
self,
) -> Optional[Union["Element", "typehints.Message", "typehints.Request"]]:
"""Return the owner of underlying data. For internal use."""
return self if self.__dataHolder is None else self.__dataHolder
def _sessions(self) -> Set["typehints.AbstractSession"]:
"""Return session(s) that this 'Element' is related to.
For internal use."""
if self.__dataHolder is None:
return set()
return self.__dataHolder._sessions()
def __str__(self) -> str:
"""x.__str__() <==> str(x)
Return a string representation of this Element. Call of 'str(element)'
is equivalent to 'element.toString()' called with default parameters.
"""
return self.toString()
def __getitem__(
self, nameOrIndex: BlpapiNameOrIndex
) -> Union[SupportedElementTypes, "Element"]:
"""
Args:
nameOrIndex: The :class:`Name` identifying the
:class:`Element` to retrieve from this :class:`Element`\ , or
the index to retrieve the value from this :class:`Element`\ .
Returns:
If a :class:`Name` or :py:class:`str` is used, and the
:class:`Element` whose name is ``nameOrIndex`` is a sequence,
choice, array, or is null, that :class:`Element` is returned.
Otherwise, if a :class:`Name` or :py:class:`str` is used, return
the value of the :class:`Element`. If ``nameOrIndex`` is an
:py:class:`int`, return the value at index ``nameOrIndex`` in this
:class:`Element`.
Raises:
KeyError:
If ``nameOrIndex`` is a :class:`Name` or :py:class:`str` and
this :class:`Element` does not contain a sub-:class:`Element`
with name ``nameOrIndex``.
InvalidConversionException:
If ``nameOrIndex`` is an :py:class:`int` and the data type of
this :class:`Element` is either a sequence or a choice.
IndexOutOfRangeException:
If ``nameOrIndex`` is an :py:class:`int` and
``nameOrIndex`` >= :meth:`numValues`.
"""
# is index
if isinstance(nameOrIndex, int):
return self.getValue(nameOrIndex)
# is name
if not self.hasElement(nameOrIndex):
raise KeyError(
f"Element {self.name()} "
f"does not contain element"
f" {nameOrIndex}"
)
element = self.getElement(nameOrIndex)
if element.isComplexType() or element.isArray():
return element
elif element.isNull():
# Scalar element with a null value
return None
return element.getValue()
def __setitem__(
self,
name: Name,
value: Union[Mapping, Sequence, SupportedElementTypes],
) -> None:
"""
Args:
name: The :class:`Name` identifying one of this
:class:`Element`\ 's sub-:class:`Element`\ s.
value: Used to format the :class:`Element`. See :meth:`fromPy` for
more details.
Raises:
Exception:
If ``name`` does not identify one of this :class:`Element`\ 's
sub-:class:`Element`\ s.
Exception:
If the :class:`Element` identified by ``name`` is has been
previously formatted.
Exception:
If the :class:`Element` identified by ``name`` cannot be
formatted by ``value`` (See :meth:`fromPy` for more details).
Format this :class:`Element`\ 's sub-:class:`Element` identified by
``name`` with ``value``. See :meth:`fromPy` for more details.
Note:
:class:`Element`\ s that have been previously formatted in any way
cannot be formatted further with this method. To further format an
:class:`Element`\ , use the get/set/append Element/Value methods.
Note:
:class:`Element`\ s cannot be modified by index.
"""
if isinstance(name, int):
raise Exception("Elements cannot be formatted by index")
self.getElement(name).fromPy(value)
def __iter__(self) -> IteratorType:
"""
Returns:
An iterator over the contents of this :class:`Element`. If this
:class:`Element` is a complex type (see :meth:`isComplexType`),
return an iterator over the :class:`Element`\ s in this
:class:`Element`. Otherwise, return an iterator over this
:class:`Element`\ 's value(s).
"""
return ElementIterator(self)
def __len__(self) -> int:
"""
Returns:
If this :class:`Element` is a complex type
(see :meth:`isComplexType`), return the number of
:class:`Element`\ s in this :class:`Element`. Otherwise, return the
number of values in this :class:`Element`.
"""
if self.isComplexType():
return self.numElements()
return self.numValues()
def __contains__(self, item: SupportedElementTypes) -> bool:
"""
Args:
item: item to check for existence in this :class:`Element`.
Returns:
If this :class:`Element` is a complex type, return whether
this :class:`Element` contains an :class:`Element` with the
specified :class:`Name` ``item``. Otherwise, return whether
``item`` is a value in this :class:`Element`.
"""
if self.isComplexType():
return self.hasElement(item) # type: ignore
return item in self.values()
def name(self) -> Name:
"""
Returns:
If this :class:`Element` is part of a sequence or choice
:class:`Element`, then return the :class:`Name` of this
:class:`Element` within the sequence or choice :class:`Element`
that owns it. If this :class:`Element` is not part of a sequence
:class:`Element` (that is it is an entire :class:`Request` or
:class:`Message`) then return the :class:`Name` of the
:class:`Request` or :class:`Message`.
"""
self.__assertIsValid()
return Name._createInternally(
internals.blpapi_Element_name(self.__handle)
)
def datatype(self) -> int:
"""
Returns:
Basic data type used to represent a value in this
:class:`Element`.
The possible types are enumerated in :class:`DataType`.
"""
self.__assertIsValid()
return internals.blpapi_Element_datatype(self.__handle)
def isComplexType(self) -> bool:
"""
Returns:
``True`` if ``datatype()==DataType.SEQUENCE`` or
``datatype()==DataType.CHOICE`` and ``False`` otherwise.
"""
self.__assertIsValid()
return bool(internals.blpapi_Element_isComplexType(self.__handle))
def isArray(self) -> bool:
"""
Returns:
``True`` if this element is an array.
This element is an array if ``elementDefinition().maxValues()>1`` or if
``elementDefinition().maxValues()==UNBOUNDED``.
"""
self.__assertIsValid()
return bool(internals.blpapi_Element_isArray(self.__handle))
def isValid(self) -> bool:
"""
Returns:
``True`` if this :class:`Element` is valid.
"""
return self.__handle is not None
def isNull(self) -> bool:
"""
Returns:
``True`` if this :class:`Element` has a null value.
"""
self.__assertIsValid()
return bool(internals.blpapi_Element_isNull(self.__handle))
def isReadOnly(self) -> bool:
"""
Returns:
``True`` if this :class:`Element` cannot be modified.
"""
self.__assertIsValid()
return bool(internals.blpapi_Element_isReadOnly(self.__handle))
def elementDefinition(self) -> "typehints.SchemaElementDefinition":
"""
Return:
Reference to the read-only element
definition object that defines the properties of this elements
value.
"""
self.__assertIsValid()
return SchemaElementDefinition(
internals.blpapi_Element_definition(self.__handle),
self._sessions(),
)
def numValues(self) -> int:
"""
Returns:
Number of values contained by this element.
The number of values is ``0`` if :meth:`isNull()` returns ``True``, and
no greater than ``1`` if :meth:`isComplexType()` returns ``True``. The
value returned will always be in the range defined by
``elementDefinition().minValues()`` and
``elementDefinition().maxValues()``.
"""
self.__assertIsValid()
return internals.blpapi_Element_numValues(self.__handle)
def numElements(self) -> int:
"""
Returns:
Number of elements in this element.
The number of elements is ``0`` if :meth:`isComplexType()` returns
``False``, and no greater than ``1`` if the :class:`DataType` is
:attr:`~DataType.CHOICE`; if the :class:`DataType` is
:attr:`~DataType.SEQUENCE` this may return any number (including
``0``).
"""
self.__assertIsValid()
return internals.blpapi_Element_numElements(self.__handle)
def isNullValue(self, position: int = 0) -> bool:
"""
Args:
position: Position of the sub-element
Returns:
``True`` if the value of the sub-element at the ``position``
is a null value.
Raises:
Exception: If ``position >= numElements()``.
"""
self.__assertIsValid()
res = internals.blpapi_Element_isNullValue(self.__handle, position)
if res in (0, 1):
return bool(res)
_ExceptionUtil.raiseOnError(res)
return False # unreachable
def toPy(self) -> Union[Dict, List, SupportedElementTypes]:
"""
Returns:
A :py:class:`dict`, :py:class:`list`, or value representation of
this :class:`Element`. This is a deep copy containing only native
python datatypes, like :py:class:`list`, :py:class:`dict`,
:py:class:`str`, and :py:class:`int`.
If an :class:`Element` is
* a complex type, it is converted to a :py:class:`dict` whose keys are
the :py:class:`str` names of its sub-:class:`Element`\ s.
* an array, it is converted to a :py:class:`list` of the
:class:`Element`'s values.
* null, it is converted an empty :py:class:`dict`.
Otherwise, the :class:`Element` is converted to its associated value.
If that value was a :class:`Name`, it will be converted to a
:py:class:`str`.
For example, the following ``exampleElement`` has the following BLPAPI
representation:
>>> exampleElement
.. code-block:: none
exampleElement = {
complexElement = {
nullElement = {
}
}
arrayElement[] = {
arrayElement = {
id = 2
endpoint = {
address = "127.0.0.1:8000"
}
}
}
valueElement = "Sample value"
nullValueElement =
}
``exampleElement`` produces the following Python representation:
>>> exampleElement.toPy()
.. code-block:: python
{
"complexElement": {
"nullElement": {}
},
"arrayElement": [
{
"id": 2
"endpoint": {
"address": "127.0.0.1:8000"
}
}
],
"valueElement": "Sample value",
"nullValueElement": None
}
"""
return internals.blpapi_Element_toPy(self.__handle)
def toString(self, level: int = 0, spacesPerLevel: int = 4) -> str:
"""Format this :class:`Element` to the string at the specified
indentation level.
Args:
level: Indentation level
spacesPerLevel: Number of spaces per indentation level for
this and all nested objects
Returns:
This element formatted as a string
If ``level`` is negative, suppress indentation of the first line. If
``spacesPerLevel`` is negative, format the entire output on one line,
suppressing all but the initial indentation (as governed by ``level``).
"""
self.__assertIsValid()
return internals.blpapi_Element_printHelper(
self.__handle, level, spacesPerLevel
)
def getElement(self, nameOrIndex: BlpapiNameOrIndex) -> "Element":
"""
Args:
nameOrIndex: Sub-element identifier
Returns:
Sub-element identified by ``nameOrIndex``
Raises:
Exception: If ``nameOrIndex`` is a string or a :class:`Name` and
``hasElement(nameOrIndex) != True``, or if ``nameOrIndex`` is an
integer and ``nameOrIndex >= numElements()``. Also if this
:class:`Element` is neither a sequence nor a choice.
Note:
**Please use** :class:`Name` **over** :class:`str` **where possible for**
``BlpapiNameOrStrOrIndex``. :class:`Name` **objects should be initialized
once and then reused** in order to minimize lookup cost.
"""
if not isinstance(nameOrIndex, int):
self.__assertIsValid()
name = getNamePair(nameOrIndex)
res = internals.blpapi_Element_getElement(
self.__handle, name[0], name[1]
)
_ExceptionUtil.raiseOnError(res[0])
return Element(res[1], self._getDataHolder())
self.__assertIsValid()
res = internals.blpapi_Element_getElementAt(self.__handle, nameOrIndex)
_ExceptionUtil.raiseOnError(res[0])
return Element(res[1], self._getDataHolder())
def elements(self) -> IteratorType:
"""
Note: prefer to iterate over this :class:`Element` directly instead
of calling this method. E.g.
```for e in element``` rather than ```for e in element.elements()```
Returns:
Iterator over elements contained in this :class:`Element`.
Raises:
UnsupportedOperationException: If this :class:`Element` is not a
sequence.
"""
if self.datatype() != DataType.SEQUENCE:
raise UnsupportedOperationException(
description="Only sequences are supported", errorCode=None
)
return Iterator(self, Element.numElements, Element.getElement)
def hasElement(
self, name: Name, excludeNullElements: bool = False
) -> bool:
"""
Args:
name: Name of the element
excludeNullElements: Whether to exclude null elements
Returns:
``True`` if this :class:`Element` is a choice or sequence
(``isComplexType() == True``) and it contains an :class:`Element`
with the specified ``name``.
Raises:
Exception: If ``name`` is neither a :class:`Name` nor a string.
Note:
**Please use** :class:`Name` **over** :class:`str` **where possible for**
``name``. :class:`Name` **objects should be initialized
once and then reused** in order to minimize lookup cost.
"""
self.__assertIsValid()
namepair = getNamePair(name)
res = internals.blpapi_Element_hasElementEx(
self.__handle,
namepair[0],
namepair[1],
1 if excludeNullElements else 0,
0,
)
return bool(res)
def getChoice(self) -> "Element":
"""
Returns:
The selection name of this element as :class:`Element`.
Raises:
Exception: If ``datatype() != DataType.CHOICE``
"""
self.__assertIsValid()
res = internals.blpapi_Element_getChoice(self.__handle)
_ExceptionUtil.raiseOnError(res[0])
return Element(res[1], self._getDataHolder())
def getValueAsBool(self, index: int = 0) -> bool:
"""
Args:
index: Index of the value in the element
Returns:
``index``\ th entry in the :class:`Element` as a boolean.
Raises:
InvalidConversionException: If the data type of this
:class:`Element` cannot be converted to a boolean.
IndexOutOfRangeException: If ``index >= numValues()``.
"""
self.__assertIsValid()
res = internals.blpapi_Element_getValueAsBool(self.__handle, index)
_ExceptionUtil.raiseOnError(res[0])
return bool(res[1])
def getValueAsString(self, index: int = 0) -> str:
"""
Args:
index: Index of the value in the element
Returns:
``index``\ th entry in the :class:`Element` as a string.
Raises:
InvalidConversionException: If the data type of this
:class:`Element` cannot be converted to a string.
IndexOutOfRangeException: If ``index >= numValues()``.
"""
self.__assertIsValid()
res = internals.blpapi_Element_getValueAsString(self.__handle, index)
_ExceptionUtil.raiseOnError(res[0])
return res[1]
def getValueAsBytes(self, index: int = 0) -> bytes:
"""
Args:
index: Index of the value in the element
Returns:
``index``\ th entry in the :class:`Element` as bytes.
Raises:
InvalidConversionException: If the data type of this
:class:`Element` cannot be converted to bytes.
IndexOutOfRangeException: If ``index >= numValues()``.
"""
self.__assertIsValid()
res = internals.blpapi_Element_getValueAsBytes(self.__handle, index)
_ExceptionUtil.raiseOnError(res[0])
return res[1]
def getValueAsDatetime(self, index: int = 0) -> AnyPythonDatetime:
"""
Args:
index: Index of the value in the element
Returns:
datetime.time or datetime.date or datetime.datetime: ``index``\ th
entry in the :class:`Element` as one of the datetime types.
Raises:
InvalidConversionException: If the data type of this
:class:`Element` cannot be converted to a datetime.
IndexOutOfRangeException: If ``index >= numValues()``.
"""
self.__assertIsValid()
res = internals.blpapi_Element_getValueAsHighPrecisionDatetime(
self.__handle, index
)
_ExceptionUtil.raiseOnError(res[0])
return _DatetimeUtil.convertToNative(res[1])
def getValueAsInteger(self, index: int = 0) -> int:
"""
Args:
index: Index of the value in the element
Returns:
``index``\ th entry in the :class:`Element` as a integer
Raises:
InvalidConversionException: If the data type of this
:class:`Element` cannot be converted to an integer.
IndexOutOfRangeException: If ``index >= numValues()``.
"""
self.__assertIsValid()
res = internals.blpapi_Element_getValueAsInt64(self.__handle, index)
_ExceptionUtil.raiseOnError(res[0])
return res[1]
def getValueAsFloat(self, index: int = 0) -> float:
"""
Args:
index: Index of the value in the element
Returns:
``index``\ th entry in the :class:`Element` as a float.
Raises:
InvalidConversionException: If the data type of this
:class:`Element` cannot be converted to an float.
IndexOutOfRangeException: If ``index >= numValues()``.
"""
self.__assertIsValid()
res = internals.blpapi_Element_getValueAsFloat64(self.__handle, index)
_ExceptionUtil.raiseOnError(res[0])
return res[1]
def getValueAsName(self, index: int = 0) -> Name:
"""
Args:
index: Index of the value in the element
Returns:
``index``\ th entry in the :class:`Element` as a Name.
Raises:
InvalidConversionException: If the data type of this
:class:`Element` cannot be converted to a :class:`Name`.
IndexOutOfRangeException: If ``index >= numValues()``.
"""
self.__assertIsValid()
res = internals.blpapi_Element_getValueAsName(self.__handle, index)
_ExceptionUtil.raiseOnError(res[0])
return Name._createInternally(res[1])
def getValueAsElement(self, index: int = 0) -> "Element":
"""
Args:
index: Index of the value in the element
Returns:
``index``\ th entry in the :class:`Element` as a Element.
Raises:
InvalidConversionException: If the data type of this
:class:`Element` cannot be converted to an :class:`Element`.
IndexOutOfRangeException: If ``index >= numValues()``.
"""
self.__assertIsValid()
res = internals.blpapi_Element_getValueAsElement(self.__handle, index)
_ExceptionUtil.raiseOnError(res[0])
return Element(res[1], self._getDataHolder())
def getValue(
self, index: int = 0
) -> Union[SupportedElementTypes, "Element"]:
"""
Args:
index: Index of the value in the element
Returns:
``index``\ th entry in the :class:`Element` defined by this
element's datatype.
Raises:
InvalidConversionException: If the data type of this
:class:`Element` is either a sequence or a choice.
IndexOutOfRangeException: If ``index >= numValues()``.
"""
datatype = self.datatype()
valueGetter = _ELEMENT_VALUE_GETTER.get(
datatype, Element.getValueAsString
)
return valueGetter(self, index) # type: ignore
def values(self) -> IteratorType:
"""
Note: prefer to iterate over this :class:`Element` directly instead
of calling this method. E.g.
```for e in element``` rather than ```for e in element.values()```
Returns:
Iterator over values contained in this :class:`Element`.
If :meth:`isComplexType()` returns ``True`` for this :class:`Element`,
the empty iterator is returned.
"""
if self.isComplexType():
return iter(()) # empty tuple
datatype = self.datatype()
valueGetter = _ELEMENT_VALUE_GETTER.get(
datatype, Element.getValueAsString
)
return Iterator(self, Element.numValues, valueGetter)
def getElementAsBool(self, name: Name) -> bool:
"""
Args:
name: Sub-element identifier
Returns:
This element's sub-element with ``name`` as a boolean
Raises:
Exception: If ``name`` is neither a :class:`Name` nor a string, or
if this :class:`Element` is neither a sequence nor a choice, or
in case it has no sub-element with the specified ``name``, or
in case the element's value can't be returned as a boolean.
Note:
**Please use** :class:`Name` **over** :class:`str` **where possible for**
``name``. :class:`Name` **objects should be initialized
once and then reused** in order to minimize lookup cost.
"""
return self.getElement(name).getValueAsBool()
def getElementAsString(self, name: Name) -> str:
"""
Args:
name: Sub-element identifier
Returns:
This element's sub-element with ``name`` as a string
Raises:
Exception: If ``name`` is neither a :class:`Name` nor a string, or
if this :class:`Element` is neither a sequence nor a choice, or
in case it has no sub-element with the specified ``name``, or
in case the element's value can't be returned as a string.
Note:
**Please use** :class:`Name` **over** :class:`str` **where possible for**
``name``. :class:`Name` **objects should be initialized
once and then reused** in order to minimize lookup cost.
"""
return self.getElement(name).getValueAsString()
def getElementAsBytes(self, name: Name) -> bytes:
"""
Args:
name: Sub-element identifier
Returns:
This element's sub-element with ``name`` as bytes
Raises:
Exception: If ``name`` is neither a :class:`Name` nor a string, or
if this :class:`Element` is neither a sequence nor a choice, or
in case it has no sub-element with the specified ``name``, or
in case the element's value can't be returned as bytes.
Note:
**Please use** :class:`Name` **over** :class:`str` **where possible for**
``name``. :class:`Name` **objects should be initialized
once and then reused** in order to minimize lookup cost.
"""
return self.getElement(name).getValueAsBytes()
def getElementAsDatetime(self, name: Name) -> AnyPythonDatetime:
"""
Args:
name: Sub-element identifier
Returns:
datetime.time or datetime.date or datetime.datetime: This element's
sub-element with ``name`` as one of the datetime types