blpapi.Element
- class blpapi.Element(handle, dataHolder)
Represents an item in a message.
An
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
Element
can be queried in a number of ways. For anElement
which represents a single value or an array of values use thegetValueAsBool()
etc. functions. For anElement
which represents a sequence or choice usegetElementAsBool()
etc. functions. In addition, for choices and sequences,hasElement()
andgetElement()
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
numValues()
to determine the number of values available. For single values, it will return either0
or1
. 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 elementcity
in the sequence elementaddress
:name_city = Name("city") # Ideally defined once (globally or class level) city = address.getElementAsString(name_city)
Note
getElementAsXYZ(name)
method is a shortcut togetElement(name).getValueAsXYZ()
.The value(s) of an
Element
can be set in a number of ways. For anElement
which represents a single value or an array of values use thesetValue()
orappendValue()
functions. For an element which represents a sequence or a choice use thesetElement()
functions.This example shows how to set the value of an
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
setElement()
family of functions. This example shows how to set the value of the elementcity
in the sequence elementaddress
to a string:name_city = Name("city") # Ideally defined once (globally or class level) address.setElement(name_city, "New York")
Methods which specify an
Element
name accept name in two forms:Name
or a string. PassingName
is more efficient. However, it requires theName
to have been created in the global name table.The form which takes a string is less efficient but will not cause a new
Name
to be created in the global name table. Because all validElement
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.
Element
objects are always created by the API, never directly by the application.- __contains__(item)
- Parameters:
item (
Union
[Name
,str
,bytes
,bool
,int
,float
,datetime
,date
,time
,None
]) – item to check for existence in thisElement
.- Return type:
- Returns:
If this
Element
is a complex type, return whether thisElement
contains anElement
with the specifiedName
item
. Otherwise, return whetheritem
is a value in thisElement
.
- __getitem__(nameOrIndex)
- Parameters:
nameOrIndex (
Union
[Name
,int
]) – TheName
identifying theElement
to retrieve from thisElement
, or the index to retrieve the value from thisElement
.- Return type:
Union
[Name
,str
,bytes
,bool
,int
,float
,datetime
,date
,time
,None
,Element
]- Returns:
If a
Name
orstr
is used, and theElement
whose name isnameOrIndex
is a sequence, choice, array, or is null, thatElement
is returned. Otherwise, if aName
orstr
is used, return the value of theElement
. IfnameOrIndex
is anint
, return the value at indexnameOrIndex
in thisElement
.- Raises:
KeyError – If
nameOrIndex
is aName
orstr
and thisElement
does not contain a sub-Element
with namenameOrIndex
.InvalidConversionException – If
nameOrIndex
is anint
and the data type of thisElement
is either a sequence or a choice.IndexOutOfRangeException – If
nameOrIndex
is anint
andnameOrIndex
>=numValues()
.
- __iter__()
- __len__()
- __setitem__(name, value)
- Parameters:
- Raises:
Format this
Element
‘s sub-Element
identified byname
withvalue
. SeefromPy()
for more details.- Return type:
Note
Element
s that have been previously formatted in any way cannot be formatted further with this method. To further format anElement
, use the get/set/append Element/Value methods.Note
Element
s cannot be modified by index.
- appendValue(value)
Append the specified
value
to thisElement
s entries at the end.- Parameters:
value (
Union
[Name
,str
,bytes
,bool
,int
,float
,datetime
,date
,time
,None
]) – Value to append- Raises:
Exception – If this
Element
‘s datatype can’t be initialized from the type of the specifiedvalue
, or if the current size of thisElement
(numValues()
) is equal to the maximum defined byelementDefinition().maxValues()
.
This method can process the following types of
value
without conversion:boolean
integers
float
string
datetypes (
datetime.time
,datetime.date
ordatetime.datetime
)
Any other
value
will be converted to a string withstr
function and then processed in the same way as stringvalue
.Arrays of bytes are not supported.
- Return type:
- elementDefinition()
- Returns:
Reference to the read-only element definition object that defines the properties of this elements value.
- elements()
Note: prefer to iterate over this
Element
directly instead of calling this method. E.g.`for e in element`
rather than`for e in element.elements()`
- Return type:
- Returns:
Iterator over elements contained in this
Element
.- Raises:
UnsupportedOperationException – If this
Element
is not a sequence.
- fromPy(value)
Format this
Element
with the provided native Python value.- Parameters:
value (
Union
[Mapping
,Sequence
,Name
,str
,bytes
,bool
,int
,float
,datetime
,date
,time
,None
]) – Used to format thisElement
- Raises:
If the
Element
isa complex type, it is formatted using a
collections.abc.Mapping
(e.g.dict
) whose keys are thestr
names of its sub-Element
s.an array, it is formatted using a
collections.abc.Sequence
(e.g.list
) of theElement
‘s values (see note below for more detais).null, it is formatted using an empty
collections.abc.Mapping
.
Otherwise, the
Element
is formatted using its associated value (e.gstr
orint
).- Return type:
Note
Although
str
,bytearray
, andmemoryview
are sub-types ofcollections.abc.Sequence
,fromPy()
treats them as scalars of type string and will use them to format scalarElement
s. If you wish to format an arrayElement
with instances of the aforementioned types, put them in a differentcollections.abc.Sequence
, likelist
.Note
Although
bytes
is sub-type ofcollections.abc.Sequence
,fromPy()
treats it as a scalar of typebytes
and will use it to format scalarElement
. Arrays ofbytes
are not supported.Note
Using
fromPy()
to format anElement
or one of its sub-Element
s that has already been formatted is not supported. To further format anElement
, use the get/set/append Element/Value methods.For example, the following
exampleElement
has the following BLPAPI representation:exampleElement = { complexElement = { nullElement = { } } arrayElement[] = { arrayElement = { id = 2 endpoint = { address = "127.0.0.1:8000" } } } valueElement = "Sample value" nullValueElement = }
exampleElement
can be created with the following code:exampleRequest = service.createRequest("ExampleRequest") exampleElement = exampleRequest.asElement() complexElement = exampleElement.getElement("complexElement") complexElement.getElement("nullElement") arrayElement = exampleElement.getElement("arrayElement") array = arrayElement.appendElement() arrayValue.setElement("id", 2) endpointElement = arrayValue.getElement("endpoint") endpointElement.setElement("address", "127.0.0.1:8000") exampleElement.setElement("valueElement", "Sample value")
fromPy()
can be used to formatexampleElement
the same way:exampleRequest = service.createRequest("ExampleRequest") exampleElement = exampleRequest.asElement() exampleElementAsDict = { "complexElement": { "nullElement": {} }, "arrayElement": [ { "id": 2, "endpoint": { "address": "127.0.0.1:8000" } } ], "valueElement": "Sample value", "nullValueElement": None } exampleElement.fromPy(exampleElementAsDict)
fromPy()
can also be called withcollections.abc.Sequence
s and scalar values to format arrayElement
s and scalarElement
s, respectively.arrayElementAsList = [{ "id": 2, "endpoint": { "address": "127.0.0.1:8000" } }] arrayElement = exampleElement.getElement("arrayElement") arrayElement.fromPy(arrayElementAsList) exampleElement.getElement("valueElement").fromPy("Sample value")
Calling
toPy()
on anElement
formatted byfromPy()
with a given value will return an equal value. Continuing from the preceding example:exampleElement.fromPy(exampleElementAsDict) print(exampleElementAsDict == exampleElement.toPy()) # True
- getChoice()
- getElement(nameOrIndex)
- getElementAsBool(name)
- Parameters:
name (
Name
) – Sub-element identifier- Returns:
This element’s sub-element with
name
as a boolean- Raises:
Exception – If
name
is neither aName
nor a string, or if thisElement
is neither a sequence nor a choice, or in case it has no sub-element with the specifiedname
, or in case the element’s value can’t be returned as a boolean.- Return type:
- getElementAsBytes(name)
- Parameters:
name (
Name
) – Sub-element identifier- Returns:
This element’s sub-element with
name
as bytes- Raises:
Exception – If
name
is neither aName
nor a string, or if thisElement
is neither a sequence nor a choice, or in case it has no sub-element with the specifiedname
, or in case the element’s value can’t be returned as bytes.- Return type:
- getElementAsDatetime(name)
- Parameters:
name (
Name
) – Sub-element identifier- Returns:
This element’s sub-element with
name
as one of the datetime types- Return type:
- Raises:
Exception – If
name
is neither aName
nor a string, or if thisElement
is neither a sequence nor a choice, or in case it has no sub-element with the specifiedname
, or in case the element’s value can’t be returned as a datetime.
- getElementAsFloat(name)
- Parameters:
name (
Name
) – Sub-element identifier- Returns:
This element’s sub-element with
name
as a float- Raises:
Exception – If
name
is neither aName
nor a string, or if thisElement
is neither a sequence nor a choice, or in case it has no sub-element with the specifiedname
, or in case the element’s value can’t be returned as a float.- Return type:
- getElementAsInteger(name)
- Parameters:
name (
Name
) – Sub-element identifier- Returns:
This element’s sub-element with
name
as an integer- Raises:
Exception – If
name
is neither aName
nor a string, or if thisElement
is neither a sequence nor a choice, or in case it has no sub-element with the specifiedname
, or in case the element’s value can’t be returned as an integer.- Return type:
- getElementAsName(name)
- Parameters:
name (
Name
) – Sub-element identifier- Returns:
This element’s sub-element with
name
as aName
- Raises:
Exception – If
name
is neither aName
nor a string, or if thisElement
is neither a sequence nor a choice, or in case it has no sub-element with the specifiedname
, or in case the element’s value can’t be returned as aName
.- Return type:
- getElementAsString(name)
- Parameters:
name (
Name
) – Sub-element identifier- Returns:
This element’s sub-element with
name
as a string- Raises:
Exception – If
name
is neither aName
nor a string, or if thisElement
is neither a sequence nor a choice, or in case it has no sub-element with the specifiedname
, or in case the element’s value can’t be returned as a string.- Return type:
- getElementValue(name)
- Parameters:
name (
Name
) – Sub-element identifier- Returns:
This element’s sub-element with
name
defined by its datatype- Raises:
Exception – If
name
is neither aName
nor a string, or if thisElement
is neither a sequence nor a choice, or in case it has no sub-element with the specifiedname
.- Return type:
Union
[Name
,str
,bytes
,bool
,int
,float
,datetime
,date
,time
,None
,Element
]
- getValue(index=0)
- Parameters:
index (
int
) – Index of the value in the element- Return type:
Union
[Name
,str
,bytes
,bool
,int
,float
,datetime
,date
,time
,None
,Element
]- Returns:
index
th entry in theElement
defined by this element’s datatype.- Raises:
InvalidConversionException – If the data type of this
Element
is either a sequence or a choice.IndexOutOfRangeException – If
index >= numValues()
.
- getValueAsBool(index=0)
- Parameters:
index (
int
) – Index of the value in the element- Return type:
- Returns:
index
th entry in theElement
as a boolean.- Raises:
InvalidConversionException – If the data type of this
Element
cannot be converted to a boolean.IndexOutOfRangeException – If
index >= numValues()
.
- getValueAsBytes(index=0)
- Parameters:
index (
int
) – Index of the value in the element- Return type:
- Returns:
index
th entry in theElement
as bytes.- Raises:
InvalidConversionException – If the data type of this
Element
cannot be converted to bytes.IndexOutOfRangeException – If
index >= numValues()
.
- getValueAsDatetime(index=0)
- Parameters:
index (
int
) – Index of the value in the element- Returns:
index
th entry in theElement
as one of the datetime types.- Return type:
- Raises:
InvalidConversionException – If the data type of this
Element
cannot be converted to a datetime.IndexOutOfRangeException – If
index >= numValues()
.
- getValueAsElement(index=0)
- Parameters:
index (
int
) – Index of the value in the element- Return type:
- Returns:
index
th entry in theElement
as a Element.- Raises:
InvalidConversionException – If the data type of this
Element
cannot be converted to anElement
.IndexOutOfRangeException – If
index >= numValues()
.
- getValueAsFloat(index=0)
- Parameters:
index (
int
) – Index of the value in the element- Return type:
- Returns:
index
th entry in theElement
as a float.- Raises:
InvalidConversionException – If the data type of this
Element
cannot be converted to an float.IndexOutOfRangeException – If
index >= numValues()
.
- getValueAsInteger(index=0)
- Parameters:
index (
int
) – Index of the value in the element- Return type:
- Returns:
index
th entry in theElement
as a integer- Raises:
InvalidConversionException – If the data type of this
Element
cannot be converted to an integer.IndexOutOfRangeException – If
index >= numValues()
.
- getValueAsName(index=0)
- Parameters:
index (
int
) – Index of the value in the element- Return type:
- Returns:
index
th entry in theElement
as a Name.- Raises:
InvalidConversionException – If the data type of this
Element
cannot be converted to aName
.IndexOutOfRangeException – If
index >= numValues()
.
- getValueAsString(index=0)
- Parameters:
index (
int
) – Index of the value in the element- Return type:
- Returns:
index
th entry in theElement
as a string.- Raises:
InvalidConversionException – If the data type of this
Element
cannot be converted to a string.IndexOutOfRangeException – If
index >= numValues()
.
- hasElement(name, excludeNullElements=False)
- isArray()
- Return type:
- Returns:
True
if this element is an array.
This element is an array if
elementDefinition().maxValues()>1
or ifelementDefinition().maxValues()==UNBOUNDED
.
- isComplexType()
- Return type:
- Returns:
True
ifdatatype()==DataType.SEQUENCE
ordatatype()==DataType.CHOICE
andFalse
otherwise.
- isNullValue(position=0)
- name()
- Return type:
- Returns:
If this
Element
is part of a sequence or choiceElement
, then return theName
of thisElement
within the sequence or choiceElement
that owns it. If thisElement
is not part of a sequenceElement
(that is it is an entireRequest
orMessage
) then return theName
of theRequest
orMessage
.
- numElements()
- Return type:
- Returns:
Number of elements in this element.
The number of elements is
0
ifisComplexType()
returnsFalse
, and no greater than1
if theDataType
isCHOICE
; if theDataType
isSEQUENCE
this may return any number (including0
).
- numValues()
- Return type:
- Returns:
Number of values contained by this element.
The number of values is
0
ifisNull()
returnsTrue
, and no greater than1
ifisComplexType()
returnsTrue
. The value returned will always be in the range defined byelementDefinition().minValues()
andelementDefinition().maxValues()
.
- setElement(name, value)
Set this Element’s sub-element with ‘name’ to the specified ‘value’.
- Parameters:
- Raises:
Exception – If
name
is neither aName
nor a string, or if this element has no sub-element with the specifiedname
, or if theElement
identified by the specifiedname
cannot be initialized from the type of the specifiedvalue
.
This method can process the following types of
value
without conversion:boolean
integers
float
string
bytes
datetypes (
datetime.time
,datetime.date
ordatetime.datetime
)
Any other
value
will be converted to a string withstr
function and then processed in the same way as stringvalue
.- Return type:
- setValue(value, index=0)
Set the specified
index
th entry in thisElement
to thevalue
.- Parameters:
- Raises:
Exception – If this
Element
‘s datatype can’t be initialized with the type of the specifiedvalue
, or ifindex >= numValues()
.
This method can process the following types of
value
without conversion:boolean
integers
float
string
bytes
datetypes (
datetime.time
,datetime.date
ordatetime.datetime
)
Any other
value
will be converted to a string withstr
function and then processed in the same way as stringvalue
.- Return type:
- toPy()
- Returns:
A
dict
,list
, or value representation of thisElement
. This is a deep copy containing only native python datatypes, likelist
,dict
,str
, andint
.
If an
Element
isa complex type, it is converted to a
dict
whose keys are thestr
names of its sub-Element
s.an array, it is converted to a
list
of theElement
’s values.null, it is converted an empty
dict
.
Otherwise, the
Element
is converted to its associated value. If that value was aName
, it will be converted to astr
.For example, the following
exampleElement
has the following BLPAPI representation:>>> exampleElement
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()
{ "complexElement": { "nullElement": {} }, "arrayElement": [ { "id": 2 "endpoint": { "address": "127.0.0.1:8000" } } ], "valueElement": "Sample value", "nullValueElement": None }
- toString(level=0, spacesPerLevel=4)
Format this
Element
to the string at the specified indentation level.- Parameters:
- Return type:
- Returns:
This element formatted as a string
If
level
is negative, suppress indentation of the first line. IfspacesPerLevel
is negative, format the entire output on one line, suppressing all but the initial indentation (as governed bylevel
).
- values()
Note: prefer to iterate over this
Element
directly instead of calling this method. E.g.`for e in element`
rather than`for e in element.values()`
If
isComplexType()
returnsTrue
for thisElement
, the empty iterator is returned.