VariableCollection class

VariableCollection class

A collection of document variables. To learn more, visit the Work with Document Properties documentation article.


Variable names and values are strings.

Variable names are case-insensitive.


__getitem__(index)Gets or sets a document variable at the specified index. None values are not allowed as a right hand side of the assignment and will be replaced by empty string.


countGets the number of elements contained in the collection.


add(name, value)Adds a document variable to the collection.
clear()Removes all elements from the collection.
contains(name)Determines whether the collection contains a document variable with the given name.
get_by_name(name)Gets or a sets a document variable by the case-insensitive name. None values are not allowed as a right hand side of the assignment and will be replaced by empty string.
index_of_key(name)Returns the zero-based index of the specified document variable in the collection.
remove(name)Removes a document variable with the specified name from the collection.
remove_at(index)Removes a document variable at the specified index.


Shows how to work with a document’s variable collection.

doc = aw.Document()
variables = doc.variables

# Every document has a collection of key/value pair variables, which we can add items to.
variables.add("Home address", "123 Main St.")
variables.add("City", "London")
variables.add("Bedrooms", "3")

self.assertEqual(3, variables.count)

# We can display the values of variables in the document body using DOCVARIABLE fields.
builder = aw.DocumentBuilder(doc)
field = builder.insert_field(aw.fields.FieldType.FIELD_DOC_VARIABLE, True)
field = field.as_field_doc_variable()
field.variable_name = "Home address"

self.assertEqual("123 Main St.", field.result)

# Assigning values to existing keys will update them.
variables.add("Home address", "456 Queen St.")

# We will then have to update DOCVARIABLE fields to ensure they display an up-to-date value.
self.assertEqual("123 Main St.", field.result)


self.assertEqual("456 Queen St.", field.result)

# Verify that the document variables with a certain name or value exist.
self.assertTrue(any(str(var) == "London" for var in variables))

# The collection of variables automatically sorts variables alphabetically by name.
self.assertEqual(0, variables.index_of_key("Bedrooms"))
self.assertEqual(1, variables.index_of_key("City"))
self.assertEqual(2, variables.index_of_key("Home address"))

# Enumerate over the collection of variables.
for entry in doc.variables:
    print(f"Name: {entry.key}, Value: {entry.value}")

# Below are three ways of removing document variables from a collection.
# 1 -  By name:


# 2 -  By index:

self.assertFalse(variables.contains("Home address"))

# 3 -  Clear the whole collection at once:

self.assertEqual(0, variables.count)

See Also