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:
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
Enums
Methods
Returns the desired areal units for calculations involving geomCalculator(), e.g., “$area”.
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.
Returns the desired distance units for calculations involving geomCalculator(), e.g., “$length” and “$perimeter”.
Returns an expression string, constructed from the internal abstract syntax tree.
Returns evaluation error
Evaluate the feature and return the result.
Attempts to evaluate a text string as an expression to a resultant double value.
Returns the original, unmodified expression string.
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 calculator used for distance and area calculations (used by $length, $area and $perimeter functions only)
Returns the translated name for a function group.
Returns true if an error occurred when evaluating last input
Returns true if an error occurred when parsing the input expression
Returns the help text for a specified function.
Checks whether an expression consists only of a single field reference
tells whether the identifier is a name of existing function
Checks if this expression is valid.
Returns true if the expression uses feature geometry for some computation
Returns parser error
Returns parser error details including location of error.
Gets the expression ready for evaluation - find out column indexes.
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.
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.
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 root node of the expression.
Sets the desired areal units for calculations involving geomCalculator(), e.g., “$area”.
Sets the desired distance units for calculations involving geomCalculator(), e.g., “$length” and “$perimeter”.
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.
Unregisters a function from the expression engine.
Returns the help text for a specified variable.
Signals
Attributes
-
BuiltinFunctions
() → List[str]¶
-
Functions
() → object¶
-
class
ParserError
¶ Bases:
sip.wrapper
QgsExpression.ParserError(QgsExpression.ParserError)
-
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
See also
New in version 2.14.
-
checkExpression
(text: str, context: QgsExpressionContext) → Tuple[bool, str]¶ Tests whether a string is a valid expression.
- Parameters
text – string to test
context – optional expression context
- 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 – the name of the field
value – the value of the field
- 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
See also
New in version 2.14.
-
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.
-
evalErrorString
(self) → str¶ Returns evaluation error
-
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.
-
evaluateToDouble
(text: str, fallbackValue: float) → float¶ Attempts to evaluate a text string as an expression to a resultant double value.
- Parameters
text – text to evaluate as expression
fallbackValue – value to return if text can not be evaluated as a double
- 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.
-
formatPreviewString
(value: Any, htmlOutput: bool = True) → 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 – expression result to format
htmlOutput – set to true to allow HTML formatting, or false for plain text output
- 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 – translated description of variable
showValue – set to true to include current value of variable in help text
value – current value of variable to show in help text
See also
See also
New in version 3.0.
-
functionCount
() → int¶ Returns the number of functions defined in the parser
- Returns
The number of function defined in the parser.
-
functionIndex
(name: str) → int¶ Returns index of the function in Functions array
-
geomCalculator
(self) → QgsDistanceArea¶ Returns calculator used for distance and area calculations (used by $length, $area and $perimeter functions only)
See also
See also
See also
-
group
(group: str) → str¶ Returns the translated name for a function group.
- Parameters
group – untranslated group name
-
hasEvalError
(self) → bool¶ Returns true if an error occurred when evaluating last input
-
hasParserError
(self) → bool¶ Returns true if an error occurred when parsing the input expression
-
helpText
(name: str) → str¶ Returns the help text for a specified function.
- Parameters
name – function name
See also
See also
-
isField
(self) → bool¶ Checks whether an expression consists only of a single field reference
New in version 2.9.
-
isFunctionName
(name: str) → bool¶ tells whether the identifier is a name of existing function
-
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.
-
needsGeometry
(self) → bool¶ Returns true if the expression uses feature geometry for some computation
-
parserErrorString
(self) → str¶ Returns parser error
-
parserErrors
(self) → object¶ Returns parser error details including location of error.
New in version 3.0.
-
prepare
(self, context: QgsExpressionContext) → bool¶ Gets the expression ready for evaluation - find out column indexes.
- Parameters
context – context for preparing expression
New in version 2.12.
-
quotedColumnRef
(name: str) → str¶ Returns a quoted column reference (in double quotes)
See also
See also
-
quotedString
(text: str) → str¶ Returns a quoted version of a string (in single quotes)
See also
See also
-
quotedValue
(value: Any) → str¶ Returns a string representation of a literal value, including appropriate quotations where required.
- Parameters
value – value to convert to a string representation
See also
See also
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
See also
New in version 2.14.
-
referencedAttributeIndexes
(self, fields: QgsFields) → object¶ Returns a list of field name indexes obtained from the provided fields.
New in version 3.0.
-
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.
See also
-
referencedFunctions
(self) → Set[str]¶ Returns a list of the names of all functions which are used in this expression.
New in version 3.2.
-
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.
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.
-
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 – function to register
transferOwnership – set to true to transfer ownership of function to expression engine
- Returns
true on successful registration
See also
-
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
action – The source string in which placeholders should be replaced.
context – Expression context
distanceArea – Optional
QgsDistanceArea
. If specified, the QgsDistanceArea is used for distance and area conversion
New in version 2.12.
-
rootNode
(self) → QgsExpressionNode¶ Returns root node of the expression. Root node is null is parsing has failed
-
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
See also
New in version 2.14.
-
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
See also
New in version 2.14.
-
setEvalErrorString
(self, str: str)¶ Sets evaluation error (used internally by evaluation functions)
-
setExpression
(self, expression: str)¶ Set the expression string, will reset the whole internal structure.
New in version 3.0.
-
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 – geometry calculator. Ownership is not transferred. Set to a None to force Cartesian calculations.
See also
-
soBbox
= 0¶
-
soContains
= 2¶
-
soCrosses
= 3¶
-
soDisjoint
= 5¶
-
soEquals
= 4¶
-
soIntersects
= 1¶
-
soOverlaps
= 6¶
-
soTouches
= 7¶
-
soWithin
= 8¶
-
unregisterFunction
(name: str) → bool¶ Unregisters a function from the expression engine. The function will no longer be usable in expressions.
- Parameters
name – function name
See also
-
variableHelpText
(variableName: str) → str¶ Returns the help text for a specified variable.
- Parameters
variableName – name of variable
See also
New in version 2.12.
-