Subgroup: Expression
Class: QgsExpression¶
-
class
qgis.core.
QgsExpression
¶ Bases:
sip.wrapper
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
Methods
BuiltinFunctions
Functions
areaUnits
Returns the desired areal units for calculations involving geomCalculator(), e.g., “$area”. 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
Return 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
Return 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
return index of the function in Functions array geomCalculator
Return calculator used for distance and area calculations 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 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 prepare
Get 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
Return a list of field name indexes obtained from the provided fields. referencedColumns
Get list of columns referenced by the expression. referencedVariables
Return 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 %] rootNode
Returns 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
Set 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. 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]¶
-
Functions
() → object¶
-
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
New in version 2.14.
See also
See also
-
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
- errorMessage – will be filled with any error message from the validation
Returns: true if string is a valid expression
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
New in version 2.14.
See also
See also
-
dump
(self) → str¶ Return 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
New in version 2.7.
Note
this method is inefficient for bulk evaluation of expressions, it is intended for one-off evaluations only.
-
expression
(self) → str¶ Return 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) → 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 Returns: formatted string, may contain HTML formatting characters 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¶ return index of the function in Functions array
-
geomCalculator
(self) → QgsDistanceArea¶ Return 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
-
prepare
(self, context: QgsExpressionContext) → bool¶ Get 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 New in version 2.14.
See also
See also
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
New in version 2.14.
See also
See also
-
referencedAttributeIndexes
(self, fields: QgsFields) → object¶ Return a list of field name indexes obtained from the provided fields.
New in version 3.0.
-
referencedColumns
(self) → Set[str]¶ Get 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
-
referencedVariables
(self) → Set[str]¶ Return 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.
-
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”.
Note
areas are only converted when a geomCalculator() has been set
New in version 2.14.
See also
See also
-
setDistanceUnits
(self, unit: QgsUnitTypes.DistanceUnit)¶ Sets the desired distance units for calculations involving geomCalculator(), e.g., “$length” and “$perimeter”.
Note
distances are only converted when a geomCalculator() has been set
New in version 2.14.
See also
See also
-
setEvalErrorString
(self, str: str)¶ Set 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). By default, no geometry calculator is set and 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
- 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
New in version 2.12.
-