I periodically need to refresh my QGIS map based on changed underlying data sources (currently locally-saved KML, GPKG, but trying to be general) using PyQGIS. Following Make a Qgis layer update from a changed data source, for a specific layer I can use:


However, I need to find all current layers depending on a specific updated source, and also keep track of the layers found vs the layers (=database tables, KML folders) in the source. The latter is to alert the user if there are map layers to deprecate that are no longer in the datasource, or new ones in the datasource to potentially add and style. For this I need to parse layer.source() to extract filename and (source as opposed to map) layer name.

What's a robust, non-provider specific, and reasonably future-proof way of doing this? At the moment, all the relevant sources are loaded via ogr, and by inspection the relevant sourcestring has the URI-like format full_filename|layername=table_or_folder_name_in_source and sometimes also ...|geometrytype=Point_or_LineString_or_Whatever. Therefore I use a simple if filename in layer.source() to find layers that need updating, and layer.source().split('|layername=')[1].split('|')[0] to pick out the layer name in the source file. But this could be confused by layers with different providers (e.g. a WMS layer whose URI happens to have a confounding substring) and for all I know ogr could change its datasource string format at any time.

More specifically, is there either a method/function to parse a layer.source() string into meaningful components, or -- failing that -- a documented canonical format for the string? I've noticed some providers use & as a delimiter but others |.

1 Answer 1


because data source parsing depends of provider you have to:

QgsProviderRegistry.instance().decodeUri( layer.providerType(), layer.dataProvider().dataSourceUri() )

so in case of a file based provider you have

decoded = QgsProviderRegistry.instance().decodeUri( layer.providerType(), layer.dataProvider().dataSourceUri() )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.