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.

Methods

activeScopeForVariable

Returns the currently active scope from the context for a specified variable name.

appendScope

Appends a scope to the end of the context.

appendScopes

Appends a list of scopes to the end of the context.

cachedValue

Returns the matching cached value, if set.

clearCachedValues

Clears all cached values from the context.

description

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

feature

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

feedback

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

fields

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

filteredVariableNames

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

function

Fetches a matching function from the context.

functionNames

Retrieves a list of function names contained in the context.

geometry

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

hasCachedValue

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

hasFeature

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

hasFunction

Checks whether a specified function is contained in the context.

hasGeometry

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

hasVariable

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

highlightedVariables

Returns the current list of variables highlighted within the context.

indexOfScope

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

isHighlightedFunction

Returns True if the specified function name is intended to be highlighted to the user.

isHighlightedVariable

Returns True if the specified variable name is intended to be highlighted to the user.

isReadOnly

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

lastScope

Returns the last scope added to the context.

layerStores

Returns the list of layer stores associated with the context.

loadedLayerStore

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

popScope

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

scope

Returns the scope at the specified index within the context.

scopeCount

Returns the number of scopes contained in the context.

scopes

Returns a list of scopes contained within the stack.

setCachedValue

Sets a value to cache within the expression context.

setFeature

Convenience function for setting a feature for the context.

setFeedback

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

setFields

Convenience function for setting a fields for the context.

setGeometry

Convenience function for setting a geometry for the context.

setHighlightedFunctions

Sets the list of function names intended to be highlighted to the user.

setHighlightedVariables

Sets the list of variable names within the context intended to be highlighted to the user.

setLoadedLayerStore

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

setOriginalValueVariable

Sets the original value variable value for the context.

uniqueHash

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

variable

Fetches a matching variable from the context.

variableNames

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

variablesToMap

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

Attributes

EXPR_CLUSTER_COLOR

Inbuilt variable name for cluster color variable

EXPR_CLUSTER_SIZE

Inbuilt variable name for cluster size variable

EXPR_FIELDS

Inbuilt variable name for fields storage

EXPR_GEOMETRY_PART_COUNT

Inbuilt variable name for geometry part count variable

EXPR_GEOMETRY_PART_NUM

Inbuilt variable name for geometry part number variable

EXPR_GEOMETRY_POINT_COUNT

Inbuilt variable name for point count variable

EXPR_GEOMETRY_POINT_NUM

Inbuilt variable name for point number variable

EXPR_GEOMETRY_RING_NUM

Inbuilt variable name for geometry ring number variable.

EXPR_ORIGINAL_VALUE

Inbuilt variable name for value original value variable

EXPR_SYMBOL_ANGLE

Inbuilt variable name for symbol angle variable

EXPR_SYMBOL_COLOR

Inbuilt variable name for symbol color variable

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'

Inbuilt variable name for cluster color variable

EXPR_CLUSTER_SIZE: str = 'cluster_size'

Inbuilt variable name for cluster size variable

EXPR_FIELDS: str = '_fields_'

Inbuilt variable name for fields storage

EXPR_GEOMETRY_PART_COUNT: str = 'geometry_part_count'

Inbuilt variable name for geometry part count variable

EXPR_GEOMETRY_PART_NUM: str = 'geometry_part_num'

Inbuilt variable name for geometry part number variable

EXPR_GEOMETRY_POINT_COUNT: str = 'geometry_point_count'

Inbuilt variable name for point count variable

EXPR_GEOMETRY_POINT_NUM: str = 'geometry_point_num'

Inbuilt variable name for point number variable

EXPR_GEOMETRY_RING_NUM: str = 'geometry_ring_num'

Inbuilt variable name for geometry ring number variable.

Added in version 3.20.

EXPR_ORIGINAL_VALUE: str = 'value'

Inbuilt variable name for value original value variable

EXPR_SYMBOL_ANGLE: str = 'symbol_angle'

Inbuilt variable name for symbol angle variable

EXPR_SYMBOL_COLOR: str = 'symbol_color'

Inbuilt variable name for symbol color variable

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

Return type:

int

Returns:

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

indexOfScope(self, scopeName: str | None) int[source]

Returns the index of the first scope with a matching name within the context.

Parameters:

scopeName (Optional[str]) – 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]