Skip to main content
4 of 4
replaced http://stackoverflow.com/ with https://stackoverflow.com/

Why the order of imports matters in a standalone PyQGIS processing script?

I've come across a weird issue while running standalone PyQGIS processing scripts. The order of imports in the script affects its normal execution.

You can reproduce the problem by opening a Python console and entering the following script (I use GNU/Linux, QGIS 2.6.1, processing plugin v.2.2.0-2, and Python 2.7.3):

# Prepare the environment
import sys
from qgis.core import QgsApplication
from PyQt4.QtGui import QApplication
app = QApplication([])
QgsApplication.setPrefixPath("/usr", True)
QgsApplication.initQgis()

# Prepare processing framework 
sys.path.append('/home/YOUR_USER/.qgis2/python/plugins')
from processing.core.Processing import Processing
Processing.initialize()

print Processing.getAlgorithm("qgis:creategrid")

# Exit applications
QgsApplication.exitQgis()
QApplication.exit()

You should obtain:

ALGORITHM: Create grid
    HSPACING <ParameterNumber>
    VSPACING <ParameterNumber>
    WIDTH <ParameterNumber>
    HEIGHT <ParameterNumber>
    CENTERX <ParameterNumber>
    CENTERY <ParameterNumber>
    GRIDTYPE <ParameterSelection>
    CRS <ParameterCrs>
    SAVENAME <OutputVector>

On the other hand, if you switch the order of imports (lines 3 and 4), this way:

from PyQt4.QtGui import QApplication
from qgis.core import QgsApplication

the script now returns... None, because the algorithm was not found.

This issue implies that you cannot run processing algorithms out of QGIS if you (by chance) write imports in the wrong order.

I've checked in StackOverflow but according to Does Python import order matter, the order shouldn't really matter. Moreover, the Style Guide for Python Code tells us to import standard (more generic) libraries first, then related third party libraries, and finally, local application specific imports. I think PyQt4 lies in the 2nd category of imports, whereas PyQGIS would be local application specific, so PyQt4 imports should come first (I'm not an expert on this, though).

Do you have an idea of why this could happen? Have you ever experienced something similar?


EDIT 1: Changed implicit imports (from abc import *) by explicit ones (e.g., from abc import xyz) as suggested by @mike-t.

Germán Carrillo
  • 37k
  • 5
  • 125
  • 180