Class: QgsExpression¶
Class for 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
Returns the desired areal units for calculations involving |
|
Returns the desired distance units for calculations involving |
|
Returns an expression string, constructed from the internal abstract syntax tree. |
|
Returns evaluation error |
|
Evaluate the feature and return the result. |
|
Returns the original, unmodified expression string. |
|
Returns calculator used for distance and area calculations (used by $length, $area and $perimeter functions only) |
|
Returns |
|
Returns |
|
Checks whether an expression consists only of a single field reference |
|
Checks if this expression is valid. |
|
Returns |
|
Returns parser error |
|
Returns parser error details including location of error. |
|
Gets the expression ready for evaluation - find out column indexes. |
|
Returns a list of field name indexes obtained from the provided fields. |
|
Gets list of columns referenced by the expression. |
|
Returns a list of the names of all functions which are used in this expression. |
|
Returns a list of all variables which are used in this expression. |
|
Returns the root node of the expression. |
|
Sets the desired areal units for calculations involving |
|
Sets the desired distance units for calculations involving |
|
Sets evaluation error (used internally by evaluation functions) |
|
Set the expression string, will reset the whole internal structure. |
|
Sets the geometry calculator used for distance and area calculations in expressions. |
Static Methods
Adds a help string for a custom variable. |
|
Attempts to reduce a list of expressions to a single "field IN (val1, val2, . |
|
Tests whether a string is a valid expression. |
|
Deletes all registered functions whose ownership have been transferred to the expression engine. |
|
Create an expression allowing to evaluate if a field is equal to a value. |
|
Attempts to evaluate a text string as an expression to a resultant double value. |
|
Attempts to resolve an expression to a field index from the given layer. |
|
Formats an expression result for friendly display to the user. |
|
Returns formatted help text for a variable. |
|
Returns the number of functions defined in the parser |
|
Returns index of the function in Functions array |
|
Returns the translated name for a function group. |
|
Returns the help text for a specified function. |
|
Returns |
|
tells whether the identifier is a name of existing function |
|
Validate if the expression is a field in the layer and ensure it is quoted. |
|
Returns a quoted column reference (in double quotes) |
|
Returns a quoted version of a string (in single quotes) |
|
Returns a string representation of a literal value, including appropriate quotations where required. |
|
Registers a function to the expression engine. |
|
This function replaces each expression between [% and %] in the string with the result of its evaluation with the specified context |
|
Returns a string list of search tags for a specified function. |
|
Unregisters a function from the expression engine. |
|
Returns the help text for a specified variable. |
Attributes
- 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:
objectDetails 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¶
The message for the error at this location.
- errorType¶
The type of parser error that was found.
- firstColumn¶
The first column that contained the error in the parser. Depending on the error sometimes this doesn’t mean anything.
- firstLine¶
The first line that contained the error in the parser. Depending on the error sometimes this doesn’t mean anything.
- lastColumn¶
The last column that contained the error in the parser.
- lastLine¶
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
nameshould not have an existing help string set. If a help string is already present thenFalsewill 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:
Trueif the help string was successfully added
See also
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 setSee also
See also
- Return type:
- 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
Trueif the givenexpressionscould be converted to an IN type expression.- Parameters:
expressions (Iterable[Optional[str]]) -> (bool) – expressions to test
- Returns:
Trueif the expression was converted to a field IN type expressionresult: 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:
Trueif string is a valid expressionerrorMessage: 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 setSee also
See also
- Return type:
- 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
- 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
expressiondoes not represent a field from the layer.
See also
Added in version 3.22.
- Parameters:
expression (Optional[str])
layer (Optional[QgsVectorLayer])
- 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
Trueto allow HTML formatting, orFalsefor plain text outputmaximumPreviewLength (int = 60) – define the maximum character length of the preview
- Return type:
str
- Returns:
formatted string, may contain HTML formatting characters if
htmlOutputisTrue
- 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
Trueto include current value of variable in help textvalue (Any = None) – current value of variable to show in help text
See also
See also
- 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
See also
See also
- 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
Trueif an error occurred when evaluating last input- Return type:
bool
- hasParserError(self) bool[source]¶
Returns
Trueif 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
See also
See also
- Return type:
str
- isField(self) bool[source]¶
Checks whether an expression consists only of a single field reference
See also
- Return type:
bool
- static isFieldEqualityExpression(expression: str | None)[source]¶
Returns
Trueif the givenexpressionis a simple “field=value” type expression.- Parameters:
expression (Optional[str]) -> (bool) – expression to test
- Returns:
Trueif the expression is a field equality expressionfield: 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
Trueif the expression uses feature geometry for some computation- Return type:
bool
- parserErrors(self) List[QgsExpression.ParserError]¶
Returns parser error details including location of error.
- Return type:
- 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
layerand 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
expressionif not a field or quotes are not required, otherwise returns a quoted field.
See also
Added in version 3.24.
- Parameters:
expression (Optional[str])
layer (Optional[QgsVectorLayer])
- static quotedColumnRef(name: str | None) str[source]¶
Returns a quoted column reference (in double quotes)
See also
See also
- 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
See also
- 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
See also
- 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
See also
- 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
See also
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 toQgsExpressionNode.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 toQgsExpressionNode.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.See also
- 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 toQgsExpression.prepare(), orQgsExpressionNode.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 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 toQgsExpression.prepare(), orQgsExpressionNode.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
Trueto transfer ownership of function to expression engine
- Return type:
bool
- Returns:
Trueon successful registration
See also
- 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:
action (Optional[str]) – The source string in which placeholders should be replaced.
context (Optional[QgsExpressionContext]) – Expression context
distanceArea (Optional[QgsDistanceArea] = None) – Optional
QgsDistanceArea. If specified, theQgsDistanceAreais used for distance and area conversion
- Return type:
str
- rootNode(self) QgsExpressionNode | None[source]¶
Returns the root node of the expression.
The root node is
Noneif 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 toQgsUnitTypes.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 setSee also
See also
- 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 toQgsUnitTypes.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 setSee also
See also
- 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 ifsetGeomCalculator()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
Noneto force Cartesian calculations.
See also
- 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
See also
- Return type:
bool