Class: QgsExpression

Handles parsing and evaluation of expressions (formerly called “search strings”).

The expressions try to follow both syntax and semantics of SQL expressions.

Usage:

exp = QgsExpression("gid*2 > 10 and type not in ('D','F')")
if exp.hasParserError():
    # show error message with parserErrorString() and exit

result = exp.evaluate(feature, fields)
if exp.hasEvalError():
    # show error message with evalErrorString()
else:
    # examine the result

Three Value Logic

Similarly to SQL, this class supports three-value logic: true/false/unknown. Unknown value may be a result of operations with missing data (NULL). Please note that NULL is different value than zero or an empty string. For example 3 > NULL returns unknown.

There is no special (three-value) ‘boolean’ type: true/false is represented as 1/0 integer, unknown value is represented the same way as NULL values: NULL QVariant.

Performance

For better performance with many evaluations you may first call prepare(fields) function to find out indices of columns and then repeatedly call evaluate(feature).

Type conversion

Operators and functions that expect arguments to be of a particular type automatically convert the arguments to that type, e.g. sin(‘2.1’) will convert the argument to a double, length(123) will first convert the number to a string. Explicit conversion can be achieved with to_int, to_real, to_string functions. If implicit or explicit conversion is invalid, the evaluation returns an error. Comparison operators do numeric comparison in case both operators are numeric (int/double) or they can be converted to numeric types.

Implicit sharing

This class is implicitly shared, copying has a very low overhead. It is normally preferable to call QgsExpression( otherExpression ) instead of QgsExpression( otherExpression.expression() ). A deep copy will only be made when prepare() is called. For usage this means mainly, that you should normally keep an unprepared master copy of a QgsExpression and whenever using it with a particular QgsFeatureIterator copy it just before and prepare it using the same context as the iterator.

Implicit sharing was added in 2.14

Methods

BuiltinFunctions

Functions

areaUnits

Returns the desired areal units for calculations involving geomCalculator(), e.g., "$area".

distanceUnits

Returns the desired distance units for calculations involving geomCalculator(), e.g., "$length" and "$perimeter".

dump

Returns an expression string, constructed from the internal abstract syntax tree.

evalErrorString

Returns evaluation error

evaluate

Evaluate the feature and return the result.

expression

Returns the original, unmodified expression string.

geomCalculator

Returns calculator used for distance and area calculations (used by $length, $area and $perimeter functions only)

hasEvalError

Returns True if an error occurred when evaluating last input

hasParserError

Returns True if an error occurred when parsing the input expression

isField

Checks whether an expression consists only of a single field reference

isValid

Checks if this expression is valid.

needsGeometry

Returns True if the expression uses feature geometry for some computation

parserErrorString

Returns parser error

parserErrors

Returns parser error details including location of error.

prepare

Gets the expression ready for evaluation - find out column indexes.

referencedAttributeIndexes

Returns a list of field name indexes obtained from the provided fields.

referencedColumns

Gets list of columns referenced by the expression.

referencedFunctions

Returns a list of the names of all functions which are used in this expression.

referencedVariables

Returns a list of all variables which are used in this expression.

rootNode

Returns the root node of the expression.

setAreaUnits

Sets the desired areal units for calculations involving geomCalculator(), e.g., "$area".

setDistanceUnits

Sets the desired distance units for calculations involving geomCalculator(), e.g., "$length" and "$perimeter".

setEvalErrorString

Sets evaluation error (used internally by evaluation functions)

setExpression

Set the expression string, will reset the whole internal structure.

setGeomCalculator

Sets the geometry calculator used for distance and area calculations in expressions.

Static Methods

addVariableHelpText

Adds a help string for a custom variable.

attemptReduceToInClause

Attempts to reduce a list of expressions to a single "field IN (val1, val2, .

checkExpression

Tests whether a string is a valid expression.

cleanRegisteredFunctions

Deletes all registered functions whose ownership have been transferred to the expression engine.

createFieldEqualityExpression

Create an expression allowing to evaluate if a field is equal to a value.

evaluateToDouble

Attempts to evaluate a text string as an expression to a resultant double value.

expressionToLayerFieldIndex

Attempts to resolve an expression to a field index from the given layer.

formatPreviewString

Formats an expression result for friendly display to the user.

formatVariableHelp

Returns formatted help text for a variable.

functionCount

Returns the number of functions defined in the parser

functionIndex

Returns index of the function in Functions array

group

Returns the translated name for a function group.

helpText

Returns the help text for a specified function.

isFieldEqualityExpression

Returns True if the given expression is a simple "field=value" type expression.

isFunctionName

tells whether the identifier is a name of existing function

quoteFieldExpression

Validate if the expression is a field in the layer and ensure it is quoted.

quotedColumnRef

Returns a quoted column reference (in double quotes)

quotedString

Returns a quoted version of a string (in single quotes)

quotedValue

Returns a string representation of a literal value, including appropriate quotations where required.

registerFunction

Registers a function to the expression engine.

replaceExpressionText

This function replaces each expression between [% and %] in the string with the result of its evaluation with the specified context

tags

Returns a string list of search tags for a specified function.

unregisterFunction

Unregisters a function from the expression engine.

variableHelpText

Returns the help text for a specified variable.

Attributes

soBbox

soContains

soCrosses

soDisjoint

soEquals

soIntersects

soOverlaps

soTouches

soWithin

class qgis.core.QgsExpression[source]

Bases: object

__init__(expr: str | None)

Creates a new expression based on the provided string. The string will immediately be parsed. For optimization prepare() should always be called before every loop in which this expression is used.

Parameters:

expr (Optional[str])

__init__(other: QgsExpression)

Create a copy of this expression. This is preferred over recreating an expression from a string since it does not need to be re-parsed.

Parameters:

other (QgsExpression)

__init__()

Create an empty expression.

BuiltinFunctions() List[str]
Return type:

List[str]

Functions() List[QgsExpressionFunction]
Return type:

List[QgsExpressionFunction]

class ParserError

Bases: object

Details about any parser errors that were found when parsing the expression.

FunctionInvalidParams = 3
FunctionNamedArgsError = 4
FunctionUnknown = 1
FunctionWrongArgs = 2
class ParserErrorType

Bases: int

Unknown = 0
errorMsg: str

The message for the error at this location.

errorType
firstColumn: int

The first column that contained the error in the parser. Depending on the error sometimes this doesn’t mean anything.

firstLine: int

The first line that contained the error in the parser. Depending on the error sometimes this doesn’t mean anything.

lastColumn: int

The last column that contained the error in the parser.

lastLine: int

The last line that contained the error in the parser.

class SpatialOperator

Bases: int

static addVariableHelpText(name: str | None, description: str | None) bool[source]

Adds a help string for a custom variable.

The specified variable name should not have an existing help string set. If a help string is already present then False will be returned and no changes will occur.

Parameters:
  • name (Optional[str]) – variable name

  • description (Optional[str]) – the help string to add. This is user visible, and should be a translated string.

Return type:

bool

Returns:

True if the help string was successfully added

Added in version 3.22.

areaUnits(self) Qgis.AreaUnit[source]

Returns the desired areal units for calculations involving geomCalculator(), e.g., “$area”.

Note

areas are only converted when a geomCalculator() has been set

See also

setAreaUnits()

See also

distanceUnits()

Return type:

Qgis.AreaUnit

static attemptReduceToInClause(expressions: Iterable[str | None])[source]

Attempts to reduce a list of expressions to a single “field IN (val1, val2, … )” type expression.

This will only be possible if all the input expressions form simple “field=value” OR “field IN (value1, value2)” expressions, and all reference the same field name.

Returns True if the given expressions could be converted to an IN type expression.

Parameters:

expressions (Iterable[Optional[str]]) -> (bool) – expressions to test

Returns:

  • True if the expression was converted to a field IN type expression

  • result: the calculated “field IN (…)” expression, wherever possible

Added in version 3.18.

static checkExpression(text: str | None, context: QgsExpressionContext | None)[source]

Tests whether a string is a valid expression.

Parameters:
  • text (Optional[str]) – string to test

  • context (Optional[QgsExpressionContext]) -> (bool) – optional expression context

Returns:

  • True if string is a valid expression

  • errorMessage: will be filled with any error message from the validation

static cleanRegisteredFunctions()[source]

Deletes all registered functions whose ownership have been transferred to the expression engine.

static createFieldEqualityExpression(fieldName: str | None, value: Any, fieldType: QMetaType.Type = QMetaType.Type.UnknownType) str[source]

Create an expression allowing to evaluate if a field is equal to a value. The value may be null.

Parameters:
  • fieldName (Optional[str]) – the name of the field

  • value (Any) – the value of the field

  • fieldType (QMetaType.Type = QMetaType.Type.UnknownType) – the type of the field on the left side used to quote the value. If not given, the value type is used instead

Return type:

str

Returns:

the expression to evaluate field equality

static createFieldEqualityExpression(fieldName: str | None, value: Any, fieldType: QVariant.Type) str[source]

Create an expression allowing to evaluate if a field is equal to a value. The value may be null.

Parameters:
  • fieldName (Optional[str]) – the name of the field

  • value (Any) – the value of the field

  • fieldType (QVariant.Type) – the type of the field on the left side used to quote the value. If not given, the value type is used instead

Return type:

str

Returns:

the expression to evaluate field equality

Deprecated since version 3.38: Use the method with a QMetaType.Type argument instead.

distanceUnits(self) Qgis.DistanceUnit[source]

Returns the desired distance units for calculations involving geomCalculator(), e.g., “$length” and “$perimeter”.

Note

distances are only converted when a geomCalculator() has been set

See also

areaUnits()

Return type:

Qgis.DistanceUnit

dump(self) str[source]

Returns an expression string, constructed from the internal abstract syntax tree. This does not contain any nice whitespace formatting or comments. In general it is preferable to use expression() instead.

Return type:

str

evalErrorString(self) str[source]

Returns evaluation error

Return type:

str

evaluate(self) Any[source]

Evaluate the feature and return the result.

Note

this method does not expect that prepare() has been called on this instance

Return type:

Any

evaluate(self, context: QgsExpressionContext | None) Any[source]

Evaluate the expression against the specified context and return the result.

Parameters:

context (Optional[QgsExpressionContext]) – context for evaluating expression

Note

prepare() should be called before calling this method.

Return type:

Any

static evaluateToDouble(text: str | None, fallbackValue: float) float[source]

Attempts to evaluate a text string as an expression to a resultant double value.

Parameters:
  • text (Optional[str]) – text to evaluate as expression

  • fallbackValue (float) – value to return if text can not be evaluated as a double

Return type:

float

Returns:

evaluated double value, or fallback value

Note

this method is inefficient for bulk evaluation of expressions, it is intended for one-off evaluations only.

expression(self) str[source]

Returns the original, unmodified expression string. If there was none supplied because it was constructed by sole API calls, dump() will be used to create one instead.

Return type:

str

static expressionToLayerFieldIndex(expression: str | None, layer: QgsVectorLayer | None) int[source]

Attempts to resolve an expression to a field index from the given layer.

Given a string which may either directly match a field name from a layer, OR may be an expression which consists only of a single field reference for that layer, this method will return the corresponding field index.

Return type:

int

Returns:

field index if found, or -1 if expression does not represent a field from the layer.

See also

isField()

Added in version 3.22.

Parameters:
static formatPreviewString(value: Any, htmlOutput: bool = True, maximumPreviewLength: int = 60) str[source]

Formats an expression result for friendly display to the user. Truncates the result to a sensible length, and presents text representations of non numeric/text types (e.g., geometries and features).

Parameters:
  • value (Any) – expression result to format

  • htmlOutput (bool = True) – set to True to allow HTML formatting, or False for plain text output

  • maximumPreviewLength (int = 60) – define the maximum character length of the preview

Return type:

str

Returns:

formatted string, may contain HTML formatting characters if htmlOutput is True

static formatVariableHelp(description: str | None, showValue: bool = True, value: Any = None) str[source]

Returns formatted help text for a variable.

Parameters:
  • description (Optional[str]) – translated description of variable

  • showValue (bool = True) – set to True to include current value of variable in help text

  • value (Any = None) – current value of variable to show in help text

See also

helpText()

Return type:

str

static functionCount() int[source]

Returns the number of functions defined in the parser

Return type:

int

Returns:

The number of function defined in the parser.

static functionIndex(name: str | None) int[source]

Returns index of the function in Functions array

Parameters:

name (Optional[str])

Return type:

int

geomCalculator(self) QgsDistanceArea | None[source]

Returns calculator used for distance and area calculations (used by $length, $area and $perimeter functions only)

See also

distanceUnits()

See also

areaUnits()

Return type:

Optional[QgsDistanceArea]

static group(group: str | None) str[source]

Returns the translated name for a function group.

Parameters:

group (Optional[str]) – untranslated group name

Return type:

str

hasEvalError(self) bool[source]

Returns True if an error occurred when evaluating last input

Return type:

bool

hasParserError(self) bool[source]

Returns True if an error occurred when parsing the input expression

Return type:

bool

static helpText(name: str | None) str[source]

Returns the help text for a specified function.

Parameters:

name (Optional[str]) – function name

Return type:

str

isField(self) bool[source]

Checks whether an expression consists only of a single field reference

Return type:

bool

static isFieldEqualityExpression(expression: str | None)[source]

Returns True if the given expression is a simple “field=value” type expression.

Parameters:

expression (Optional[str]) -> (bool) – expression to test

Returns:

  • True if the expression is a field equality expression

  • field: the field name if the expression is a field equality expression

  • value: the value if the expression is a field equality expression

Added in version 3.18.

static isFunctionName(name: str | None) bool[source]

tells whether the identifier is a name of existing function

Parameters:

name (Optional[str])

Return type:

bool

isValid(self) bool[source]

Checks if this expression is valid. A valid expression could be parsed but does not necessarily evaluate properly.

Return type:

bool

needsGeometry(self) bool[source]

Returns True if the expression uses feature geometry for some computation

Return type:

bool

parserErrorString(self) str[source]

Returns parser error

Return type:

str

parserErrors(self) List[QgsExpression.ParserError]

Returns parser error details including location of error.

Return type:

List[QgsExpression.ParserError]

prepare(self, context: QgsExpressionContext | None) bool[source]

Gets the expression ready for evaluation - find out column indexes.

Parameters:

context (Optional[QgsExpressionContext]) – context for preparing expression

Return type:

bool

static quoteFieldExpression(expression: str | None, layer: QgsVectorLayer | None) str[source]

Validate if the expression is a field in the layer and ensure it is quoted.

Given a string which may either directly match a field name from a layer, OR may be an expression which consists only of a single field reference for that layer, this method will return the quoted field.

Return type:

str

Returns:

the expression if not a field or quotes are not required, otherwise returns a quoted field.

Added in version 3.24.

Parameters:
static quotedColumnRef(name: str | None) str[source]

Returns a quoted column reference (in double quotes)

See also

quotedString()

See also

quotedValue()

Parameters:

name (Optional[str])

Return type:

str

static quotedString(text: str | None) str[source]

Returns a quoted version of a string (in single quotes)

See also

quotedValue()

Parameters:

text (Optional[str])

Return type:

str

static quotedValue(value: Any) str[source]

Returns a string representation of a literal value, including appropriate quotations where required.

Parameters:

value (Any) – value to convert to a string representation

See also

quotedString()

Return type:

str

static quotedValue(value: Any, type: QMetaType.Type) str[source]

Returns a string representation of a literal value, including appropriate quotations where required.

Parameters:
  • value (Any) – value to convert to a string representation

  • type (QMetaType.Type) – value type

See also

quotedString()

Return type:

str

static quotedValue(value: Any, type: QVariant.Type) str[source]

Returns a string representation of a literal value, including appropriate quotations where required.

Parameters:
  • value (Any) – value to convert to a string representation

  • type (QVariant.Type) – value type

See also

quotedString()

Deprecated since version 3.38: Use the method with a QMetaType.Type argument instead.

Return type:

str

referencedAttributeIndexes(self, fields: QgsFields) Any

Returns a list of field name indexes obtained from the provided fields.

Warning

If the expression has been prepared via a call to QgsExpression.prepare(), or a call to QgsExpressionNode.prepare() for a node has been made, then parts of the expression may have been determined to evaluate to a static pre-calculatable value. In this case the results will omit attribute indices which are used by these pre-calculated nodes, regardless of their actual referenced columns. If you are seeking to use these functions to introspect an expression you must take care to do this with an unprepared expression.

Parameters:

fields (QgsFields)

Return type:

Any

referencedColumns(self) Set[str]

Gets list of columns referenced by the expression.

Note

If the returned list contains the QgsFeatureRequest.AllAttributes constant then all attributes from the layer are required for evaluation of the expression. QgsFeatureRequest.setSubsetOfAttributes automatically handles this case.

Warning

If the expression has been prepared via a call to QgsExpression.prepare(), or a call to QgsExpressionNode.prepare() for a node has been made, then parts of the expression may have been determined to evaluate to a static pre-calculatable value. In this case the results will omit attribute indices which are used by these pre-calculated nodes, regardless of their actual referenced columns. If you are seeking to use these functions to introspect an expression you must take care to do this with an unprepared expression.

Return type:

Set[str]

referencedFunctions(self) Set[str]

Returns a list of the names of all functions which are used in this expression.

Note

In contrast to the referencedColumns() function this method is not affected by any previous calls to QgsExpression.prepare(), or QgsExpressionNode.prepare().

Added in version 3.2.

Return type:

Set[str]

referencedVariables(self) Set[str]

Returns a list of all variables which are used in this expression. If the list contains an empty string, there is a variable name used which is determined at runtime.

Note

In contrast to the referencedColumns() function this method is not affected by any previous calls to QgsExpression.prepare(), or QgsExpressionNode.prepare().

Return type:

Set[str]

referencedVariables(text: str | None) Set[str]

This function returns variables in each expression between [% and %].

Parameters:

text (Optional[str]) – The source string in which variables should be searched.

Added in version 3.2.

Return type:

Set[str]

static registerFunction(function: QgsExpressionFunction | None, transferOwnership: bool = False) bool[source]

Registers a function to the expression engine. This is required to allow expressions to utilize the function.

Parameters:
  • function (Optional[QgsExpressionFunction]) – function to register

  • transferOwnership (bool = False) – set to True to transfer ownership of function to expression engine

Return type:

bool

Returns:

True on successful registration

static replaceExpressionText(action: str | None, context: QgsExpressionContext | None, distanceArea: QgsDistanceArea | None = None) str[source]

This function replaces each expression between [% and %] in the string with the result of its evaluation with the specified context

Additional substitutions can be passed through the substitutionMap parameter

Parameters:
Return type:

str

rootNode(self) QgsExpressionNode | None[source]

Returns the root node of the expression.

The root node is None if parsing has failed.

Return type:

Optional[QgsExpressionNode]

setAreaUnits(self, unit: Qgis.AreaUnit)[source]

Sets the desired areal units for calculations involving geomCalculator(), e.g., “$area”. If distance units are set to QgsUnitTypes.AreaUnknownUnit (default), prepare() will read variables from the expression context (“project_distance_units”) to determine distance units.

Note

areas are only converted when a geomCalculator() has been set

See also

areaUnits()

Parameters:

unit (Qgis.AreaUnit)

setDistanceUnits(self, unit: Qgis.DistanceUnit)[source]

Sets the desired distance units for calculations involving geomCalculator(), e.g., “$length” and “$perimeter”. If distance units are set to QgsUnitTypes.DistanceUnknownUnit (default), prepare() will read variables from the expression context (“project_distance_units”) to determine distance units.

Note

distances are only converted when a geomCalculator() has been set

See also

distanceUnits()

See also

setAreaUnits()

Parameters:

unit (Qgis.DistanceUnit)

setEvalErrorString(self, str: str | None)[source]

Sets evaluation error (used internally by evaluation functions)

Parameters:

str (Optional[str])

setExpression(self, expression: str | None)[source]

Set the expression string, will reset the whole internal structure.

Parameters:

expression (Optional[str])

setGeomCalculator(self, calc: QgsDistanceArea | None)[source]

Sets the geometry calculator used for distance and area calculations in expressions. (used by $length, $area and $perimeter functions only). If the geometry calculator is set to None (default), prepare() will read variables from the expression context (“project_ellipsoid”, “_project_transform_context” and “_layer_crs”) to build a geometry calculator. If these variables does not exist and if setGeomCalculator() is not called, all distance and area calculations are performed using simple Cartesian methods (ie no ellipsoidal calculations).

Parameters:

calc (Optional[QgsDistanceArea]) – geometry calculator. Ownership is not transferred. Set to None to force Cartesian calculations.

See also

geomCalculator()

soBbox = 0
soContains = 2
soCrosses = 3
soDisjoint = 5
soEquals = 4
soIntersects = 1
soOverlaps = 6
soTouches = 7
soWithin = 8
static tags(name: str | None) List[str][source]

Returns a string list of search tags for a specified function.

Parameters:

name (Optional[str]) – function name

Added in version 3.12.

Return type:

List[str]

static unregisterFunction(name: str | None) bool[source]

Unregisters a function from the expression engine. The function will no longer be usable in expressions.

Parameters:

name (Optional[str]) – function name

Return type:

bool

static variableHelpText(variableName: str | None) str[source]

Returns the help text for a specified variable.

Parameters:

variableName (Optional[str]) – name of variable

See also

helpText()

Return type:

str