Class: QgsExpression

class qgis.core.QgsExpression(expr: str)

Bases: sip.wrapper

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.

QgsExpression(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.

QgsExpression() Create an empty expression.

New in version 3.0.

Class for parsing and evaluation of expressions (formerly called “search strings”). The expressions try to follow both syntax and semantics of SQL expressions.

Usage: .. code-block:: python

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

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.

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

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.

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

rtype

List[str]

Functions

rtype

List[QgsExpressionFunction]

areaUnits

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

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.

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.

evaluateToDouble

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

expression

Returns the original, unmodified expression string.

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

geomCalculator

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

group

Returns the translated name for a function group.

hasEvalError

Returns True if an error occurred when evaluating last input

hasParserError

Returns True if an error occurred when parsing the input expression

helpText

Returns the help text for a specified function.

isField

Checks whether an expression consists only of a single field reference

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

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.

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.

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.

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

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.

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

BuiltinFunctions()List[str]
Return type

List[str]

Functions()List[QgsExpressionFunction]
Return type

List[QgsExpressionFunction]

class ParserError
class ParserError(QgsExpression.ParserError)None

Bases: sip.wrapper

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

Bases: int

Unknown = 0
errorMsg
errorType
firstColumn
firstLine
lastColumn
lastLine
class SpatialOperator

Bases: int

areaUnits(self)QgsUnitTypes.AreaUnit

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

New in version 2.14.

Return type

QgsUnitTypes.AreaUnit

attemptReduceToInClause(expressions: Iterable[str])Tuple[bool, str]

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[str]) – expressions to test

Return type

Tuple[bool, str]

Returns

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

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

New in version 3.18.

checkExpression(text: str, context: QgsExpressionContext)Tuple[bool, str]

Tests whether a string is a valid expression.

Parameters
Return type

Tuple[bool, str]

Returns

  • True if string is a valid expression

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

New in version 2.12.

cleanRegisteredFunctions()

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

New in version 2.12.

createFieldEqualityExpression(fieldName: str, value: Any)str

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

Parameters
  • fieldName (str) – the name of the field

  • value (Any) – the value of the field

Return type

str

Returns

the expression to evaluate field equality

New in version 3.0.

distanceUnits(self)QgsUnitTypes.DistanceUnit

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

New in version 2.14.

Return type

QgsUnitTypes.DistanceUnit

dump(self)str

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

Returns evaluation error

Return type

str

evaluate(self)Any

Evaluate the feature and return the result.

Note

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

New in version 2.12.

evaluate(self, context: QgsExpressionContext) -> Any Evaluate the expression against the specified context and return the result.

Parameters

context – context for evaluating expression

Note

prepare() should be called before calling this method.

New in version 2.12.

Return type

Any

evaluateToDouble(text: str, fallbackValue: float)float

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

Parameters
  • text (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.

New in version 2.7.

expression(self)str

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

formatPreviewString(value: Any, htmlOutput: bool = True, maximumPreviewLength: int = 60)str

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

New in version 2.14.

formatVariableHelp(description: str, showValue: bool = True, value: Any = None)str

Returns formatted help text for a variable.

Parameters
  • description (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()

New in version 3.0.

Return type

str

functionCount()int

Returns the number of functions defined in the parser

Return type

int

Returns

The number of function defined in the parser.

functionIndex(name: str)int

Returns index of the function in Functions array

Parameters

name (str) –

Return type

int

geomCalculator(self)QgsDistanceArea

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

See also

distanceUnits()

See also

areaUnits()

Return type

QgsDistanceArea

group(group: str)str

Returns the translated name for a function group.

Parameters

group (str) – untranslated group name

Return type

str

hasEvalError(self)bool

Returns True if an error occurred when evaluating last input

Return type

bool

hasParserError(self)bool

Returns True if an error occurred when parsing the input expression

Return type

bool

helpText(name: str)str

Returns the help text for a specified function.

Parameters

name (str) – function name

Return type

str

isField(self)bool

Checks whether an expression consists only of a single field reference

New in version 2.9.

Return type

bool

isFieldEqualityExpression(expression: str)Tuple[bool, str, Any]

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

Parameters

expression (str) – expression to test

Return type

Tuple[bool, str, Any]

Returns

  • True if the expression is a field equality expression

  • field: will be set to the field name if the expression is a field equality expression

  • value: will be set to the value if the expression is a field equality expression

New in version 3.18.

isFunctionName(name: str)bool

tells whether the identifier is a name of existing function

Parameters

name (str) –

Return type

bool

isValid(self)bool

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

New in version 3.0.

Return type

bool

needsGeometry(self)bool

Returns True if the expression uses feature geometry for some computation

Return type

bool

parserErrorString(self)str

Returns parser error

Return type

str

parserErrors(self)List[QgsExpression.ParserError]

Returns parser error details including location of error.

New in version 3.0.

Return type

List[QgsExpression.ParserError]

prepare(self, context: QgsExpressionContext)bool

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

Parameters

context (QgsExpressionContext) – context for preparing expression

New in version 2.12.

Return type

bool

quotedColumnRef(name: str)str

Returns a quoted column reference (in double quotes)

See also

quotedString()

See also

quotedValue()

Parameters

name (str) –

Return type

str

quotedString(text: str)str

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

See also

quotedValue()

Parameters

text (str) –

Return type

str

quotedValue(value: Any)str

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

New in version 2.14.

quotedValue(value: Any, type: QVariant.Type) -> str Returns a string representation of a literal value, including appropriate quotations where required.

Parameters
  • value – value to convert to a string representation

  • type – value type

See also

quotedString()

New in version 2.14.

Return type

str

referencedAttributeIndexes(self, fields: QgsFields)object

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.

New in version 3.0.

Parameters

fields (QgsFields) –

Return type

object

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

New 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 a NULL QString, 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().

New in version 3.0.

referencedVariables(text: str) -> Set[str] This function returns variables in each expression between [% and %].

Parameters

text – The source string in which variables should be searched.

New in version 3.2.

Return type

Set[str]

registerFunction(function: QgsExpressionFunction, transferOwnership: bool = False)bool

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

Parameters
  • function (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

replaceExpressionText(action: str, context: QgsExpressionContext, distanceArea: QgsDistanceArea = None)str

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

New in version 2.12.

Return type

str

rootNode(self)QgsExpressionNode

Returns the root node of the expression.

The root node is None if parsing has failed.

Return type

QgsExpressionNode

setAreaUnits(self, unit: QgsUnitTypes.AreaUnit)

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

New in version 2.14.

Parameters

unit (QgsUnitTypes.AreaUnit) –

setDistanceUnits(self, unit: QgsUnitTypes.DistanceUnit)

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

New in version 2.14.

Parameters

unit (QgsUnitTypes.DistanceUnit) –

setEvalErrorString(self, str: str)

Sets evaluation error (used internally by evaluation functions)

Parameters

str (str) –

setExpression(self, expression: str)

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

New in version 3.0.

Parameters

expression (str) –

setGeomCalculator(self, calc: QgsDistanceArea)

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 (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
tags(name: str)List[str]

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

Parameters

name (str) – function name

New in version 3.12.

Return type

List[str]

unregisterFunction(name: str)bool

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

Parameters

name (str) – function name

Return type

bool

variableHelpText(variableName: str)str

Returns the help text for a specified variable.

Parameters

variableName (str) – name of variable

See also

helpText()

New in version 2.12.

Return type

str