I am trying to select features of a layer based on an expression that uses the variable jenks_var_sep_minclass. When running it I don't get an error message, but there are also no features selected even though some of their attribute values are in the range that is supposed to be selected.

When I run the code using a number instead of the variable for the expression, everything works well.

# create list of area attributes

area_list = [feature.attributes()[1] for feature in layer.getFeatures()]

# calculate Jenks Natural Breaks and assign second value as variable

jenks_breaks = jenkspy.jenks_breaks(area_list, nb_class=10)
jenks_var_sep_minclass = float(jenks_breaks[1])

# Select

layer = iface.activeLayer()
layer.selectByExpression('"Area" > jenks_var_sep_minclass', QgsVectorLayer.SetSelection)

  • when you set the variable directly as a number, it's an integer. Are you converting it to a float? Perhaps that is breaking the query...
    – Theo F
    Nov 6, 2019 at 16:20
  • @TheoF, that's unfortunately not the problem - also tried to just create an integer variable x = 50000 and use that - didn't work either.
    – mnowatzki
    Nov 6, 2019 at 17:17
  • 3
    Change your expression to '"Area" > {}'.format(jenks_var_sep_minclass). In your version of the expression you're passing the variable as a simple string in the expression, so it never gets evaluated. Nov 6, 2019 at 18:10
  • @GermánCarrillo - of course, that makes sense... and it works! Thank you!
    – mnowatzki
    Nov 6, 2019 at 18:17


Browse other questions tagged or ask your own question.