Class: QgsProcessingContext

Contains information about the context in which a processing algorithm is executed.

Contextual information includes settings such as the associated project, and expression context.

Enums

LogLevel

alias of ProcessingLogLevel

ProcessArgumentFlag

Flags controlling the results given by asQgisProcessArguments().

Methods

addLayerToLoadOnCompletion

Adds a layer to load (by ID or datasource) into the canvas upon completion of the algorithm or model.

areaUnit

Returns the area unit to use for area calculations.

asQgisProcessArguments

Returns list of the equivalent qgis_process arguments representing the settings from the context.

clearModelResult

Clears model results previously populated when the context was used to run a model algorithm.

copyThreadSafeSettings

Copies all settings which are safe for use across different threads from other to this context.

currentTimeRange

Returns the current time range to use for temporal operations.

defaultEncoding

Returns the default encoding to use for newly created files.

distanceUnit

Returns the distance unit to use for distance calculations.

ellipsoid

Returns the ellipsoid to use for distance and area calculations.

exportToMap

Exports the context's settings to a variant map.

expressionContext

Returns the expression context.

feedback

Returns the associated feedback object.

flags

Returns any flags set in the context.

getMapLayer

Returns a map layer from the context with a matching identifier.

invalidGeometryCheck

Returns the behavior used for checking invalid geometries in input layers.

layerToLoadOnCompletionDetails

Returns a reference to the details for a given layer which is loaded on completion of the algorithm or model.

layersToLoadOnCompletion

Returns a map of layers (by ID or datasource) to LayerDetails, to load into the canvas upon completion of the algorithm or model.

logLevel

Returns the logging level for algorithms to use when pushing feedback messages to users.

maximumThreads

Returns the (optional) number of threads to use when running algorithms.

modelResult

Returns the model results, populated when the context is used to run a model algorithm.

preferredRasterFormat

Returns the preferred raster format to use for raster outputs.

preferredVectorFormat

Returns the preferred vector format to use for vector outputs.

project

Returns the project in which the algorithm is being executed.

pushToThread

Pushes the thread affinity for the context (including all layers contained in the temporaryLayerStore()) into another thread.

setAreaUnit

Sets the unit to use for area calculations.

setCurrentTimeRange

Sets the current time range to use for temporal operations.

setDefaultEncoding

Sets the default encoding to use for newly created files.

setDistanceUnit

Sets the unit to use for distance calculations.

setEllipsoid

Sets a specified ellipsoid to use for distance and area calculations.

setExpressionContext

Sets the expression context.

setFeedback

Sets an associated feedback object.

setFlags

Sets flags for the context.

setInvalidGeometryCallback

Sets a callback function to use when encountering an invalid geometry and invalidGeometryCheck() is set to GeometryAbortOnInvalid.

setInvalidGeometryCheck

Sets the behavior used for checking invalid geometries in input layers.

setLayersToLoadOnCompletion

Sets the map of layers (by ID or datasource) to LayerDetails, to load into the canvas upon completion of the algorithm or model.

setLogLevel

Sets the logging level for algorithms to use when pushing feedback messages to users.

setMaximumThreads

Sets the (optional) number of threads to use when running algorithms.

setPreferredRasterFormat

Sets the preferred raster format to use for raster outputs.

setPreferredVectorFormat

Sets the preferred vector format to use for vector outputs.

setProject

Sets the project in which the algorithm will be executed.

setTemporaryFolder

Sets the (optional) temporary folder to use when running algorithms.

setTransformContext

Sets the coordinate transform context.

setTransformErrorCallback

Sets a callback function to use when encountering a transform error when iterating features.

takeResultLayer

Takes the result map layer with matching id from the context and transfers ownership of it back to the caller.

takeResultsFrom

Takes the results from another context and merges them with the results currently stored in this context.

temporaryFolder

Returns the (optional) temporary folder to use when running algorithms.

temporaryLayerStore

Returns a reference to the layer store used for storing temporary layers during algorithm execution.

thread

Returns the thread in which the context lives.

transformContext

Returns the coordinate transform context.

willLoadLayerOnCompletion

Returns True if the given layer (by ID or datasource) will be loaded into the current project upon completion of the algorithm or model.

Attributes

Unused

class qgis.core.QgsProcessingContext[source]

Bases: object

class Flag

Bases: int

class Flags
class Flags(f: QgsProcessingContext.Flags | QgsProcessingContext.Flag)
class Flags(a0: QgsProcessingContext.Flags)

Bases: object

class LayerDetails[source]

Bases: object

Details for layers to load into projects.

QgsProcessingContext.LayerDetails(name: Optional[str], project: Optional[QgsProject], outputName: Optional[str] = ‘’, layerTypeHint: QgsProcessingUtils.LayerHint = QgsProcessingUtils.LayerHint.UnknownType) Constructor for LayerDetails.

QgsProcessingContext.LayerDetails()

QgsProcessingContext.LayerDetails(a0: QgsProcessingContext.LayerDetails)

forceName: bool

Set to True if LayerDetails.name should always be used as the loaded layer name, regardless of the user’s local Processing settings.

Added in version 3.16.

groupName: str

Optional name for a layer tree group under which to place the layer when loading it into a project.

Added in version 3.32.

layerSortKey: int

Optional sorting key for sorting output layers when loading them into a project.

Layers with a greater sort key will be placed over layers with a lesser sort key.

Added in version 3.32.

layerTypeHint: LayerHint

Layer type hint.

Added in version 3.4.

name: str

Friendly name for layer, possibly for use when loading layer into project.

Warning

Instead of directly using this value, prefer to call setOutputLayerName() to generate a layer name which respects the user’s local Processing settings.

outputName: str

Associated output name from algorithm which generated the layer.

postProcessor(self) QgsProcessingLayerPostProcessorInterface | None[source]

Layer post-processor. May be None if no post-processing is required.

Added in version 3.2.

Return type:

Optional[QgsProcessingLayerPostProcessorInterface]

project: QgsProject

Destination project

setOutputLayerName(self, layer: QgsMapLayer | None)[source]

Sets a layer name to match this output, respecting any local user settings which affect this name.

Added in version 3.10.1.

Parameters:

layer (Optional[QgsMapLayer])

setPostProcessor(self, processor: QgsProcessingLayerPostProcessorInterface | None)[source]

Sets the layer post-processor. May be None if no post-processing is required.

Ownership of processor is transferred.

See also

postProcessor()

Added in version 3.2.

Parameters:

processor (Optional[QgsProcessingLayerPostProcessorInterface])

LogLevel

alias of ProcessingLogLevel

class ProcessArgumentFlag(*values)

Bases: IntEnum

Flags controlling the results given by asQgisProcessArguments().

Added in version 3.24.

  • IncludeProjectPath: Include the associated project path argument

IncludeProjectPath = 1
class ProcessArgumentFlags
class ProcessArgumentFlags(f: QgsProcessingContext.ProcessArgumentFlags | QgsProcessingContext.ProcessArgumentFlag)
class ProcessArgumentFlags(a0: QgsProcessingContext.ProcessArgumentFlags)

Bases: object

Unused = 1
addLayerToLoadOnCompletion(self, layer: str | None, details: QgsProcessingContext.LayerDetails)[source]

Adds a layer to load (by ID or datasource) into the canvas upon completion of the algorithm or model. The details parameter dictates the LayerDetails.

Parameters:
areaUnit(self) Qgis.AreaUnit[source]

Returns the area unit to use for area calculations.

See also

setAreaUnit()

See also

distanceUnit()

Added in version 3.16.

Return type:

Qgis.AreaUnit

asQgisProcessArguments(self, flags: QgsProcessingContext.ProcessArgumentFlags | QgsProcessingContext.ProcessArgumentFlag = QgsProcessingContext.ProcessArgumentFlags()) List[str][source]

Returns list of the equivalent qgis_process arguments representing the settings from the context.

Added in version 3.24.

Parameters:

flags (Union[QgsProcessingContext.ProcessArgumentFlags, QgsProcessingContext.ProcessArgumentFlag] = QgsProcessingContext.ProcessArgumentFlags())

Return type:

List[str]

clearModelResult(self)[source]

Clears model results previously populated when the context was used to run a model algorithm.

Added in version 3.42.

copyThreadSafeSettings(self, other: QgsProcessingContext)[source]

Copies all settings which are safe for use across different threads from other to this context.

Parameters:

other (QgsProcessingContext)

currentTimeRange(self) QgsDateTimeRange[source]

Returns the current time range to use for temporal operations.

Added in version 3.18.

Return type:

QgsDateTimeRange

defaultEncoding(self) str[source]

Returns the default encoding to use for newly created files.

Return type:

str

distanceUnit(self) Qgis.DistanceUnit[source]

Returns the distance unit to use for distance calculations.

See also

areaUnit()

Added in version 3.16.

Return type:

Qgis.DistanceUnit

ellipsoid(self) str[source]

Returns the ellipsoid to use for distance and area calculations.

See also

setEllipsoid()

Added in version 3.16.

Return type:

str

exportToMap(self) Dict[str, Any][source]

Exports the context’s settings to a variant map.

Added in version 3.24.

Return type:

Dict[str, Any]

expressionContext(self) QgsExpressionContext

Returns the expression context.

Return type:

QgsExpressionContext

feedback(self) QgsProcessingFeedback | None[source]

Returns the associated feedback object.

See also

setFeedback()

Return type:

Optional[QgsProcessingFeedback]

flags(self) QgsProcessingContext.Flags[source]

Returns any flags set in the context.

See also

setFlags()

Return type:

QgsProcessingContext.Flags

getMapLayer(self, identifier: str | None) QgsMapLayer | None[source]

Returns a map layer from the context with a matching identifier. This method considers layer IDs, names and sources when matching the identifier (see QgsProcessingUtils.mapLayerFromString() for details).

Ownership is not transferred and remains with the context.

Parameters:

identifier (Optional[str])

Return type:

Optional[QgsMapLayer]

invalidGeometryCheck(self) Qgis.InvalidGeometryCheck[source]

Returns the behavior used for checking invalid geometries in input layers.

Return type:

Qgis.InvalidGeometryCheck

layerToLoadOnCompletionDetails(self, layer: str | None) QgsProcessingContext.LayerDetails

Returns a reference to the details for a given layer which is loaded on completion of the algorithm or model.

Warning

First check willLoadLayerOnCompletion(), or calling this method will incorrectly add layer as a layer to load on completion.

Added in version 3.2.

Parameters:

layer (Optional[str])

Return type:

QgsProcessingContext.LayerDetails

layersToLoadOnCompletion(self) Dict[str, QgsProcessingContext.LayerDetails]

Returns a map of layers (by ID or datasource) to LayerDetails, to load into the canvas upon completion of the algorithm or model.

Return type:

Dict[str, QgsProcessingContext.LayerDetails]

logLevel(self) Qgis.ProcessingLogLevel[source]

Returns the logging level for algorithms to use when pushing feedback messages to users.

See also

setLogLevel()

Added in version 3.20.

Return type:

Qgis.ProcessingLogLevel

maximumThreads(self) int[source]

Returns the (optional) number of threads to use when running algorithms.

Warning

Not all algorithms which support multithreaded execution will respect this setting, depending on the multi-threading framework in use. Multithreaded algorithms must check this value and adapt their thread handling accordingly – the setting will not be automatically applied.

Added in version 3.32.

Return type:

int

modelResult(self) QgsProcessingModelResult[source]

Returns the model results, populated when the context is used to run a model algorithm.

Added in version 3.38.

Return type:

QgsProcessingModelResult

preferredRasterFormat(self) str[source]

Returns the preferred raster format to use for raster outputs.

This method returns a file extension to use when creating raster outputs (e.g. “tif”). Generally, it is preferable to use the extension associated with a particular parameter, which can be retrieved through QgsProcessingDestinationParameter.defaultFileExtension(). However, in some cases, a specific parameter may not be available to call this method on (e.g. for an algorithm which has only an output folder parameter and which creates multiple output layers in that folder). In this case, the format returned by this function should be used when creating these outputs.

It is the algorithm’s responsibility to check whether the returned format is acceptable for the algorithm, and to provide an appropriate fallback when the returned format is not usable.

Added in version 3.10.

Return type:

str

preferredVectorFormat(self) str[source]

Returns the preferred vector format to use for vector outputs.

This method returns a file extension to use when creating vector outputs (e.g. “shp”). Generally, it is preferable to use the extension associated with a particular parameter, which can be retrieved through QgsProcessingDestinationParameter.defaultFileExtension(). However, in some cases, a specific parameter may not be available to call this method on (e.g. for an algorithm which has only an output folder parameter and which creates multiple output layers in that folder). In this case, the format returned by this function should be used when creating these outputs.

It is the algorithm’s responsibility to check whether the returned format is acceptable for the algorithm, and to provide an appropriate fallback when the returned format is not usable.

Added in version 3.10.

Return type:

str

project(self) QgsProject | None[source]

Returns the project in which the algorithm is being executed.

See also

setProject()

Return type:

Optional[QgsProject]

pushToThread(self, thread: QThread | None)[source]

Pushes the thread affinity for the context (including all layers contained in the temporaryLayerStore()) into another thread. This method is only safe to call when the current thread matches the existing thread affinity for the context (see thread()).

See also

thread()

Parameters:

thread (Optional[QThread])

setAreaUnit(self, areaUnit: Qgis.AreaUnit)[source]

Sets the unit to use for area calculations.

If not explicitly set, the unit will default to the project()’s area unit setting.

See also

areaUnit()

Added in version 3.16.

Parameters:

areaUnit (Qgis.AreaUnit)

setCurrentTimeRange(self, currentTimeRange: QgsDateTimeRange)[source]

Sets the current time range to use for temporal operations.

Added in version 3.18.

Parameters:

currentTimeRange (QgsDateTimeRange)

setDefaultEncoding(self, encoding: str | None)[source]

Sets the default encoding to use for newly created files.

Parameters:

encoding (Optional[str])

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

Sets the unit to use for distance calculations.

If not explicitly set, the unit will default to the project()’s distance unit setting.

See also

distanceUnit()

See also

setAreaUnit()

Added in version 3.16.

Parameters:

unit (Qgis.DistanceUnit)

setEllipsoid(self, ellipsoid: str | None)[source]

Sets a specified ellipsoid to use for distance and area calculations.

If not explicitly set, the ellipsoid will default to the project()’s ellipsoid setting.

See also

ellipsoid()

Added in version 3.16.

Parameters:

ellipsoid (Optional[str])

setExpressionContext(self, context: QgsExpressionContext)[source]

Sets the expression context.

Parameters:

context (QgsExpressionContext)

setFeedback(self, feedback: QgsProcessingFeedback | None)[source]

Sets an associated feedback object. This allows context related functions to report feedback and errors to users and processing logs. While ideally this feedback object should outlive the context, only a weak pointer to feedback is stored and no errors will occur if feedback is deleted before the context. Ownership of feedback is not transferred.

See also

setFeedback()

Parameters:

feedback (Optional[QgsProcessingFeedback])

setFlags(self, flags: QgsProcessingContext.Flags | QgsProcessingContext.Flag)[source]

Sets flags for the context.

See also

flags()

Parameters:

flags (Union[QgsProcessingContext.Flags, QgsProcessingContext.Flag])

setInvalidGeometryCallback(self, a0: Callable[..., None] | None)[source]

Sets a callback function to use when encountering an invalid geometry and invalidGeometryCheck() is set to GeometryAbortOnInvalid. This function will be called using the feature with invalid geometry as a parameter.

See also

invalidGeometryCallback()

Parameters:

a0 (Optional[Callable[..., None]])

setInvalidGeometryCheck(self, check: Qgis.InvalidGeometryCheck)[source]

Sets the behavior used for checking invalid geometries in input layers. Settings this to anything but QgsFeatureRequest.GeometryNoCheck will also reset the invalidGeometryCallback() to a default implementation.

Parameters:

check (Qgis.InvalidGeometryCheck)

setLayersToLoadOnCompletion(self, layers: Dict[str | None, QgsProcessingContext.LayerDetails])[source]

Sets the map of layers (by ID or datasource) to LayerDetails, to load into the canvas upon completion of the algorithm or model.

Parameters:

layers (Dict[Optional[str], QgsProcessingContext.LayerDetails])

setLogLevel(self, level: Qgis.ProcessingLogLevel)[source]

Sets the logging level for algorithms to use when pushing feedback messages to users.

See also

logLevel()

Added in version 3.20.

Parameters:

level (Qgis.ProcessingLogLevel)

setMaximumThreads(self, threads: int)[source]

Sets the (optional) number of threads to use when running algorithms.

If set, this overrides the standard global Processing number of threads setting. Note that if algorithm implementation does not support multhreaded execution, this setting will be ignored.

Warning

Not all algorithms which support multithreaded execution will respect this setting, depending on the multi-threading framework in use. Multithreaded algorithms must check this value and adapt their thread handling accordingly – the setting will not be automatically applied.

See also

maximumThreads()

Added in version 3.32.

Parameters:

threads (int)

setPreferredRasterFormat(self, format: str | None)[source]

Sets the preferred raster format to use for raster outputs.

This method sets a file extension to use when creating raster outputs (e.g. “tif”). Generally, it is preferable to use the extension associated with a particular parameter, which can be retrieved through QgsProcessingDestinationParameter.defaultFileExtension(). However, in some cases, a specific parameter may not be available to call this method on (e.g. for an algorithm which has only an output folder parameter and which creates multiple output layers in that folder). In this case, the format set by this function will be used when creating these outputs.

Added in version 3.10.

Parameters:

format (Optional[str])

setPreferredVectorFormat(self, format: str | None)[source]

Sets the preferred vector format to use for vector outputs.

This method sets a file extension to use when creating vector outputs (e.g. “shp”). Generally, it is preferable to use the extension associated with a particular parameter, which can be retrieved through QgsProcessingDestinationParameter.defaultFileExtension(). However, in some cases, a specific parameter may not be available to call this method on (e.g. for an algorithm which has only an output folder parameter and which creates multiple output layers in that folder). In this case, the format set by this function will be used when creating these outputs.

Added in version 3.10.

Parameters:

format (Optional[str])

setProject(self, project: QgsProject | None)[source]

Sets the project in which the algorithm will be executed.

This also automatically sets the transformContext(), ellipsoid(), distanceUnit() and areaUnit() to match the project’s settings.

See also

project()

Parameters:

project (Optional[QgsProject])

setTemporaryFolder(self, folder: str | None)[source]

Sets the (optional) temporary folder to use when running algorithms.

If set, this overrides the standard global Processing temporary folder and should be used for all temporary files created during algorithm execution.

Added in version 3.32.

Parameters:

folder (Optional[str])

setTransformContext(self, context: QgsCoordinateTransformContext)[source]

Sets the coordinate transform context.

Note that setting a project for the context will automatically set the coordinate transform context.

Parameters:

context (QgsCoordinateTransformContext)

setTransformErrorCallback(self, a0: Callable[..., None] | None)[source]

Sets a callback function to use when encountering a transform error when iterating features. This function will be called using the feature which encountered the transform error as a parameter.

See also

transformErrorCallback()

Parameters:

a0 (Optional[Callable[..., None]])

takeResultLayer(self, id: str | None) QgsMapLayer | None[source]

Takes the result map layer with matching id from the context and transfers ownership of it back to the caller. This method can be used to remove temporary layers which are not required for further processing from a context.

See also

getMapLayer()

Parameters:

id (Optional[str])

Return type:

Optional[QgsMapLayer]

takeResultsFrom(self, context: QgsProcessingContext)[source]

Takes the results from another context and merges them with the results currently stored in this context. This includes settings like any layers loaded in the temporaryLayerStore() and layersToLoadOnCompletion(). This is only safe to call when both this context and the other context share the same thread() affinity, and that thread is the current thread.

Parameters:

context (QgsProcessingContext)

temporaryFolder(self) str[source]

Returns the (optional) temporary folder to use when running algorithms.

If set, this overrides the standard global Processing temporary folder and should be used for all temporary files created during algorithm execution.

Added in version 3.32.

Return type:

str

temporaryLayerStore(self) QgsMapLayerStore | None[source]

Returns a reference to the layer store used for storing temporary layers during algorithm execution.

Return type:

Optional[QgsMapLayerStore]

thread(self) QThread | None[source]

Returns the thread in which the context lives.

See also

pushToThread()

Return type:

Optional[QThread]

transformContext(self) QgsCoordinateTransformContext[source]

Returns the coordinate transform context.

Return type:

QgsCoordinateTransformContext

willLoadLayerOnCompletion(self, layer: str | None) bool[source]

Returns True if the given layer (by ID or datasource) will be loaded into the current project upon completion of the algorithm or model.

Added in version 3.2.

Parameters:

layer (Optional[str])

Return type:

bool