Class: QgsExpressionContext

Expression contexts are used to encapsulate the parameters around which a QgsExpression should be evaluated.

QgsExpressions can then utilize the information stored within a context to contextualise their evaluated result. A QgsExpressionContext consists of a stack of QgsExpressionContextScope objects, where scopes added later to the stack will override conflicting variables and functions from scopes lower in the stack.

See QgsExpressionContextUtils for helper methods for working with QgsExpressionContext objects.

class qgis.core.QgsExpressionContext[source]

Bases: object

__init__()
__init__(scopes: Iterable[QgsExpressionContextScope])

Initializes the context with given list of scopes. Ownership of the scopes is transferred to the stack.

Parameters:

scopes (Iterable[QgsExpressionContextScope])

__init__(other: QgsExpressionContext)
Parameters:

other (QgsExpressionContext)

EXPR_CLUSTER_COLOR: str = 'cluster_color'
EXPR_CLUSTER_SIZE: str = 'cluster_size'
EXPR_FIELDS: str = '_fields_'
EXPR_GEOMETRY_PART_COUNT: str = 'geometry_part_count'
EXPR_GEOMETRY_PART_NUM: str = 'geometry_part_num'
EXPR_GEOMETRY_POINT_COUNT: str = 'geometry_point_count'
EXPR_GEOMETRY_POINT_NUM: str = 'geometry_point_num'
EXPR_GEOMETRY_RING_NUM: str = 'geometry_ring_num'
EXPR_ORIGINAL_VALUE: str = 'value'
EXPR_SYMBOL_ANGLE: str = 'symbol_angle'
EXPR_SYMBOL_COLOR: str = 'symbol_color'
activeScopeForVariable(self, name: str | None) QgsExpressionContextScope | None[source]

Returns the currently active scope from the context for a specified variable name. As scopes later in the stack override earlier contexts, this will be the last matching scope which contains a matching variable.

Parameters:

name (Optional[str]) – variable name

Return type:

Optional[QgsExpressionContextScope]

Returns:

matching scope containing variable, or None if none found

appendScope(self, scope: QgsExpressionContextScope | None)[source]

Appends a scope to the end of the context. This scope will override any matching variables or functions provided by existing scopes within the context. Ownership of the scope is transferred to the stack.

Parameters:

scope (Optional[QgsExpressionContextScope]) – expression context to append to context

appendScopes(self, scopes: Iterable[QgsExpressionContextScope])[source]

Appends a list of scopes to the end of the context. This scopes will override any matching variables or functions provided by existing scopes within the context. Ownership of the scopes is transferred to the stack.

Parameters:

scopes (Iterable[QgsExpressionContextScope]) – scopes to append to context

cachedValue(self, key: str | None) Any[source]

Returns the matching cached value, if set. This can be used to retrieve the previously stored results of an expensive expression sub-calculation.

Parameters:

key (Optional[str]) – unique key used to store cached value

Return type:

Any

Returns:

matching cached value, or invalid QVariant if not set

See also

setCachedValue()

See also

hasCachedValue()

clearCachedValues(self)[source]

Clears all cached values from the context.

See also

setCachedValue()

See also

hasCachedValue()

See also

cachedValue()

description(self, name: str | None) str[source]

Returns a translated description string for the variable with specified name.

If no specific description has been provided for the variable, the value from QgsExpression.variableHelpText() will be returned.

Parameters:

name (Optional[str])

Return type:

str

feature(self) QgsFeature[source]

Convenience function for retrieving the feature for the context, if set.

See also

setFeature()

Return type:

QgsFeature

feedback(self) QgsFeedback | None[source]

Returns the feedback object that can be queried regularly by the expression to check if evaluation should be canceled, if set.

See also

setFeedback()

Added in version 3.20.

Return type:

Optional[QgsFeedback]

fields(self) QgsFields[source]

Convenience function for retrieving the fields for the context, if set.

See also

setFields()

Return type:

QgsFields

filteredVariableNames(self) List[str][source]

Returns a filtered list of variables names set by all scopes in the context. The included variables are those which should be seen by users.

Return type:

List[str]

Returns:

filtered list of unique variable names

See also

variableNames()

function(self, name: str | None) QgsExpressionFunction | None[source]

Fetches a matching function from the context. The function will be fetched from the last scope contained within the context which has a matching function set.

Parameters:

name (Optional[str]) – function name

Return type:

Optional[QgsExpressionFunction]

Returns:

function if contained by the context, otherwise None.

See also

hasFunction()

functionNames(self) List[str][source]

Retrieves a list of function names contained in the context.

See also

function()

See also

variableNames()

Return type:

List[str]

geometry(self) QgsGeometry[source]

Convenience function for retrieving the geometry for the context, if set.

See also

setGeometry()

Added in version 3.24.

Return type:

QgsGeometry

hasCachedValue(self, key: str | None) bool[source]

Returns True if the expression context contains a cached value with a matching key.

Parameters:

key (Optional[str]) – unique key used to store cached value

See also

setCachedValue()

See also

cachedValue()

Return type:

bool

hasFeature(self) bool[source]

Returns True if the context has a feature associated with it.

See also

feature()

Return type:

bool

hasFunction(self, name: str | None) bool[source]

Checks whether a specified function is contained in the context.

Parameters:

name (Optional[str]) – function name

Return type:

bool

Returns:

True if context provides a matching function

See also

function()

hasGeometry(self) bool[source]

Returns True if the context has a geometry associated with it.

See also

geometry()

Added in version 3.24.

Return type:

bool

hasVariable(self, name: str | None) bool[source]

Check whether a variable is specified by any scope within the context.

Parameters:

name (Optional[str]) – variable name

Return type:

bool

Returns:

True if variable is set

See also

variable()

See also

variableNames()

highlightedVariables(self) List[str][source]

Returns the current list of variables highlighted within the context.

Added in version 3.8.

Return type:

List[str]

indexOfScope(self, scope: QgsExpressionContextScope | None) int[source]

Returns the index of the specified scope if it exists within the context.

Parameters:

scope (Optional[QgsExpressionContextScope]) – scope to find

Returns:

index of scope, or -1 if scope was not found within the context.

indexOfScope(self, scopeName: Optional[str]) -> int Returns the index of the first scope with a matching name within the context.

Parameters:

scopeName – name of scope to find

Return type:

int

Returns:

index of scope, or -1 if scope was not found within the context.

isHighlightedFunction(self, name: str | None) bool[source]

Returns True if the specified function name is intended to be highlighted to the user. This is used by the expression builder to more prominently display the function.

Added in version 3.4.

Parameters:

name (Optional[str])

Return type:

bool

isHighlightedVariable(self, name: str | None) bool[source]

Returns True if the specified variable name is intended to be highlighted to the user. This is used by the expression builder to more prominently display the variable.

Parameters:

name (Optional[str])

Return type:

bool

isReadOnly(self, name: str | None) bool[source]

Returns whether a variable is read only, and should not be modifiable by users.

Parameters:

name (Optional[str]) – variable name

Return type:

bool

Returns:

True if variable is read only. Read only status will be taken from last matching scope which contains a matching variable.

lastScope(self) QgsExpressionContextScope | None[source]

Returns the last scope added to the context.

See also

scope()

Return type:

Optional[QgsExpressionContextScope]

layerStores(self) List[QgsMapLayerStore]

Returns the list of layer stores associated with the context.

Added in version 3.30.

Return type:

List[QgsMapLayerStore]

loadedLayerStore(self) QgsMapLayerStore | None[source]

Returns the destination layer store for any layers loaded during expression evaluation.

Added in version 3.30.

Return type:

Optional[QgsMapLayerStore]

popScope(self) QgsExpressionContextScope | None[source]

Removes the last scope from the expression context and return it.

Return type:

Optional[QgsExpressionContextScope]

scope(self, index: int) QgsExpressionContextScope | None[source]

Returns the scope at the specified index within the context.

Parameters:

index (int) – index of scope

Return type:

Optional[QgsExpressionContextScope]

Returns:

matching scope, or None if none found

See also

lastScope()

scopeCount(self) int[source]

Returns the number of scopes contained in the context.

Return type:

int

scopes(self) List[QgsExpressionContextScope]

Returns a list of scopes contained within the stack.

Return type:

List[QgsExpressionContextScope]

Returns:

list of pointers to scopes

setCachedValue(self, key: str | None, value: Any)[source]

Sets a value to cache within the expression context. This can be used to cache the results of expensive expression sub-calculations, to speed up future evaluations using the same expression context.

Parameters:
  • key (Optional[str]) – unique key for retrieving cached value

  • value (Any) – value to cache

See also

hasCachedValue()

See also

cachedValue()

setFeature(self, feature: QgsFeature)[source]

Convenience function for setting a feature for the context. The feature will be set within the last scope of the context, so will override any existing features within the context.

Parameters:

feature (QgsFeature) – feature for context

See also

feature()

setFeedback(self, feedback: QgsFeedback | None)[source]

Attach a feedback object that can be queried regularly by the expression engine to check if expression evaluation should be canceled.

Ownership of feedback is NOT transferred, and the caller must take care that it exists for the lifetime of the expression context.

See also

feedback()

Added in version 3.20.

Parameters:

feedback (Optional[QgsFeedback])

setFields(self, fields: QgsFields)[source]

Convenience function for setting a fields for the context. The fields will be set within the last scope of the context, so will override any existing fields within the context.

Parameters:

fields (QgsFields) – fields for context

See also

fields()

setGeometry(self, geometry: QgsGeometry)[source]

Convenience function for setting a geometry for the context. The geometry will be set within the last scope of the context, so will override any existing geometries within the context.

See also

geometry()

Added in version 3.24.

Parameters:

geometry (QgsGeometry)

setHighlightedFunctions(self, names: Iterable[str | None])[source]

Sets the list of function names intended to be highlighted to the user. This is used by the expression builder to more prominently display these functions.

Note that these function names may include standard functions which are not functions specific to this context, and these standard functions will also be highlighted to users.

Added in version 3.4.

Parameters:

names (Iterable[Optional[str]])

setHighlightedVariables(self, variableNames: Iterable[str | None])[source]

Sets the list of variable names within the context intended to be highlighted to the user. This is used by the expression builder to more prominently display these variables.

Parameters:

variableNames (Iterable[Optional[str]]) – variable names to highlight

setLoadedLayerStore(self, store: QgsMapLayerStore | None)[source]

Sets the destination layer store for any layers loaded during expression evaluation.

Ownership of the store is not transferred to the context, it is the caller’s responsibility to ensure that the store remains alive for the duration of the expression context.

Added in version 3.30.

Parameters:

store (Optional[QgsMapLayerStore])

setOriginalValueVariable(self, value: Any)[source]

Sets the original value variable value for the context.

Parameters:

value (Any) – value for original value variable. This usually represents an original widget value before any data defined overrides have been applied.

uniqueHash(self, variables: Iterable[str | None] = set())[source]

Returns a unique hash representing the current state of the context.

Parameters:

variables (Iterable[Optional[str]] = set()) -> (str) – optional names of a subset of variables to include in the hash. If not specified, all variables will be considered.

Returns:

  • calculated hash

  • ok: True if the hash could be generated, or false if e.g. a variable value is of a type which cannot be hashed

Added in version 3.40.

variable(self, name: str | None) Any[source]

Fetches a matching variable from the context. The variable will be fetched from the last scope contained within the context which has a matching variable set.

Parameters:

name (Optional[str]) – variable name

Return type:

Any

Returns:

variable value if matching variable exists in the context, otherwise an invalid QVariant

See also

hasVariable()

See also

variableNames()

variableNames(self) List[str][source]

Returns a list of variables names set by all scopes in the context.

Return type:

List[str]

Returns:

list of unique variable names

See also

functionNames()

See also

hasVariable()

See also

variable()

variablesToMap(self) Dict[str, Any][source]

Returns a map of variable name to value representing all the expression variables contained by the context.

Return type:

Dict[str, Any]