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 an Element which represents a single value or an array of values use the getValueAsBool() etc. functions. For an Element which represents a sequence or choice use getElementAsBool() etc. functions. In addition, for choices and sequences, hasElement() and 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 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:

city = address.getElementAsString("city")

Note

getElementAsXYZ(name) method is a shortcut to getElement(name).getValueAsXYZ().

The value(s) of an Element can be set in a number of ways. For an Element which represents a single value or an array of values use the setValue() or appendValue() functions. For an element which represents a sequence or a choice use the setElement() 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 element city in the sequence element address to a string:

address.setElement("city", "New York")

Methods which specify an Element name accept name in two forms: Name or a string. Passing Name is more efficient. However, it requires the 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 Name to be created in the global name table. Because all valid 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.

Element objects are always created by the API, never directly by the application.

__contains__(item)
Parameters

item (Union[str, Name, bytes, bool, int, float, datetime, date, time, None]) – item to check for existence in this Element.

Return type

bool

Returns

If this Element is a complex type, return whether this Element contains an Element with the specified Name item. Otherwise, return whether item is a value in this Element.

__getitem__(nameOrIndex)
Parameters

nameOrIndex (Union[str, Name, bytes, int]) – The Name identifying the Element to retrieve from this Element, or the index to retrieve the value from this Element.

Return type

Union[str, Name, bytes, bool, int, float, datetime, date, time, None, Element]

Returns

If a Name or str is used, and the Element whose name is nameOrIndex is a sequence, choice, array, or is null, that Element is returned. Otherwise, if a Name or str is used, return the value of the Element. If nameOrIndex is an int, return the value at index nameOrIndex in this Element.

Raises
__iter__()
Return type

Iterator

Returns

An iterator over the contents of this Element. If this Element is a complex type (see isComplexType()), return an iterator over the Elements in this Element. Otherwise, return an iterator over this Element‘s value(s).

__len__()
Return type

int

Returns

If this Element is a complex type (see isComplexType()), return the number of Elements in this Element. Otherwise, return the number of values in this Element.

__setitem__(name, value)
Parameters
Raises

Format this Element‘s sub-Element identified by name with value. See fromPy() for more details.

Note

Elements that have been previously formatted in any way cannot be formatted further with this method. To further format an Element, use the get/set/append Element/Value methods.

Note

Elements cannot be modified by index.

Return type

None

appendElement()

Append a new element to this array Element.

Return type

Element

Returns

The newly appended element

Raises

Exception – If this Element is not an array of sequence or choice Elements.

appendValue(value)

Append the specified value to this Elements entries at the end.

Parameters

value (Union[str, Name, 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 specified value, or if the current size of this Element (numValues()) is equal to the maximum defined by elementDefinition().maxValues().

This method can process the following types of value without conversion:

  • boolean

  • integers

  • float

  • string

  • datetypes (datetime.time, datetime.date or datetime.datetime)

  • Name

Any other value will be converted to a string with str function and then processed in the same way as string value.

Return type

None

datatype()
Return type

int

Returns

Basic data type used to represent a value in this Element.

The possible types are enumerated in DataType.

destroy()

Destroy the handle using stored dtor

Return type

None

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

Iterator

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, str, Name, bytes, bool, int, float, datetime, date, time, None]) – Used to format this Element

Raises
  • Exception – If the provided value does not properly represent the structure of this Element.

  • Exception – If this method is used to format an Element that has already been formatted.

If the Element is

Otherwise, the Element is formatted using its associated value (e.g str or int).

Note

Although str, bytes, bytearray, and memoryview are sub-types of collections.abc.Sequence, fromPy() treats them as scalars of type string and will use them to format scalar Elements. If you wish to format an array Element with instances of the aforementioned types, put them in a different collections.abc.Sequence, like list.

Note

Using fromPy() to format an Element or one of its sub-Elements that has already been formatted is not supported. To further format an Element, 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 format exampleElement 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 with collections.abc.Sequences and scalar values to format array Elements and scalar Elements, 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 an Element formatted by fromPy() with a given value will return an equal value. Continuing from the preceding example:

exampleElement.fromPy(exampleElementAsDict)
print(exampleElementAsDict == exampleElement.toPy()) # True
Return type

None

getChoice()
Return type

Element

Returns

The selection name of this element as Element.

Raises

Exception – If datatype() != DataType.CHOICE

getElement(nameOrIndex)
Parameters

nameOrIndex (Union[str, Name, bytes, int]) – Sub-element identifier

Return type

Element

Returns

Sub-element identified by nameOrIndex

Raises

Exception – If nameOrIndex is a string or a Name and hasElement(nameOrIndex) != True, or if nameOrIndex is an integer and nameOrIndex >= numElements(). Also if this Element is neither a sequence nor a choice.

getElementAsBool(name)
Parameters

name (Union[str, Name, bytes]) – Sub-element identifier

Return type

bool

Returns

This element’s sub-element with name as a boolean

Raises

Exception – If name is neither a Name nor a string, or if this 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.

getElementAsDatetime(name)
Parameters

name (Union[str, Name, bytes]) – Sub-element identifier

Returns

This element’s sub-element with name as one of the datetime types

Return type

datetime.time or datetime.date or datetime.datetime

Raises

Exception – If name is neither a Name nor a string, or if this 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 datetime.

getElementAsFloat(name)
Parameters

name (Union[str, Name, bytes]) – Sub-element identifier

Return type

float

Returns

This element’s sub-element with name as a float

Raises

Exception – If name is neither a Name nor a string, or if this 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 float.

getElementAsInteger(name)
Parameters

name (Union[str, Name, bytes]) – Sub-element identifier

Return type

int

Returns

This element’s sub-element with name as an integer

Raises

Exception – If name is neither a Name nor a string, or if this 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 an integer.

getElementAsName(name)
Parameters

name (Union[str, Name, bytes]) – Sub-element identifier

Return type

Name

Returns

This element’s sub-element with name as a Name

Raises

Exception – If name is neither a Name nor a string, or if this 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 Name.

getElementAsString(name)
Parameters

name (Union[str, Name, bytes]) – Sub-element identifier

Return type

str

Returns

This element’s sub-element with name as a string

Raises

Exception – If name is neither a Name nor a string, or if this 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.

getElementValue(name)
Parameters

name (Union[str, Name, bytes]) – Sub-element identifier

Return type

Union[str, Name, bytes, bool, int, float, datetime, date, time, None, Element]

Returns

This element’s sub-element with name defined by its datatype

Raises

Exception – If name is neither a Name nor a string, or if this Element is neither a sequence nor a choice, or in case it has no sub-element with the specified name.

getValue(index=0)
Parameters

index (int) – Index of the value in the element

Return type

Union[str, Name, bytes, bool, int, float, datetime, date, time, None, Element]

Returns

indexth entry in the Element defined by this element’s datatype.

Raises
getValueAsBool(index=0)
Parameters

index (int) – Index of the value in the element

Return type

bool

Returns

indexth entry in the Element as a boolean.

Raises
getValueAsDatetime(index=0)
Parameters

index (int) – Index of the value in the element

Returns

indexth entry in the Element as one of the datetime types.

Return type

datetime.time or datetime.date or datetime.datetime

Raises
getValueAsElement(index=0)
Parameters

index (int) – Index of the value in the element

Return type

Element

Returns

indexth entry in the Element as a Element.

Raises
getValueAsFloat(index=0)
Parameters

index (int) – Index of the value in the element

Return type

float

Returns

indexth entry in the Element as a float.

Raises
getValueAsInteger(index=0)
Parameters

index (int) – Index of the value in the element

Return type

int

Returns

indexth entry in the Element as a integer

Raises
getValueAsName(index=0)
Parameters

index (int) – Index of the value in the element

Return type

Name

Returns

indexth entry in the Element as a Name.

Raises
getValueAsString(index=0)
Parameters

index (int) – Index of the value in the element

Return type

str

Returns

indexth entry in the Element as a string.

Raises
hasElement(name, excludeNullElements=False)
Parameters
  • name (Union[str, Name, bytes]) – Name of the element

  • excludeNullElements (bool) – Whether to exclude null elements

Return type

bool

Returns

True if this Element is a choice or sequence (isComplexType() == True) and it contains an Element with the specified name.

Raises

Exception – If name is neither a Name nor a string.

isArray()
Return type

bool

Returns

True if this element is an array.

This element is an array if elementDefinition().maxValues()>1 or if elementDefinition().maxValues()==UNBOUNDED.

isComplexType()
Return type

bool

Returns

True if datatype()==DataType.SEQUENCE or datatype()==DataType.CHOICE and False otherwise.

isNull()
Return type

bool

Returns

True if this Element has a null value.

isNullValue(position=0)
Parameters

position (int) – Position of the sub-element

Return type

bool

Returns

True if the value of the sub-element at the position is a null value.

Raises

Exception – If position >= numElements().

isReadOnly()
Return type

bool

Returns

True if this Element cannot be modified.

isValid()
Return type

bool

Returns

True if this Element is valid.

name()
Return type

Name

Returns

If this Element is part of a sequence or choice Element, then return the Name of this Element within the sequence or choice Element that owns it. If this Element is not part of a sequence Element (that is it is an entire Request or Message) then return the Name of the Request or Message.

numElements()
Return type

int

Returns

Number of elements in this element.

The number of elements is 0 if isComplexType() returns False, and no greater than 1 if the DataType is CHOICE; if the DataType is SEQUENCE this may return any number (including 0).

numValues()
Return type

int

Returns

Number of values contained by this element.

The number of values is 0 if isNull() returns True, and no greater than 1 if isComplexType() returns True. The value returned will always be in the range defined by elementDefinition().minValues() and elementDefinition().maxValues().

setChoice(selectionName)

Set this Element‘s active element to selectionName.

Parameters

selectionName (Union[str, Name, bytes]) – Name of the element to set the active choice

Return type

Element

Returns

The newly active element

Raises

Exception – If selectionName is neither a Name nor a string, or if this Element is not a choice.

setElement(name, value)

Set this Element’s sub-element with ‘name’ to the specified ‘value’.

Parameters
Raises

Exception – If name is neither a Name nor a string, or if this element has no sub-element with the specified name, or if the Element identified by the specified name cannot be initialized from the type of the specified value.

This method can process the following types of value without conversion:

  • boolean

  • integers

  • float

  • string

  • datetypes (datetime.time, datetime.date or datetime.datetime)

  • Name

Any other value will be converted to a string with str function and then processed in the same way as string value.

Return type

None

setValue(value, index=0)

Set the specified indexth entry in this Element to the value.

Parameters
Raises

Exception – If this Element‘s datatype can’t be initialized with the type of the specified value, or if index >= numValues().

This method can process the following types of value without conversion:

  • boolean

  • integers

  • float

  • string

  • datetypes (datetime.time, datetime.date or datetime.datetime)

  • Name

Any other value will be converted to a string with str function and then processed in the same way as string value.

Return type

None

toPy()
Return type

Union[Dict, List, str, Name, bytes, bool, int, float, datetime, date, time, None]

Returns

A dict, list, or value representation of this Element. This is a deep copy containing only native python datatypes, like list, dict, str, and int.

If an Element is

  • a complex type, it is converted to a dict whose keys are the str names of its sub-Elements.

  • an array, it is converted to a list of the Element’s values.

  • null, it is converted an empty dict.

Otherwise, the Element is converted to its associated value. If that value was a Name, it will be converted to a str.

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
  • level (int) – Indentation level

  • spacesPerLevel (int) – Number of spaces per indentation level for this and all nested objects

Return type

str

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).

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()`

Return type

Iterator

Returns

Iterator over values contained in this Element.

If isComplexType() returns True for this Element, the empty iterator is returned.