[GIS] Advanced Python Field Calculation gives error: TypeError: ‘in ‘ requires string as left operand, not QVariant

pythonqgisqgis-modeler

I am using the following function in QGIS 3.10 Advanced Python Field Calculator as part of a Processing Modelling file. The model processed 4 layers and generates a single layer for use in another program. I want to rerun the Process Model frequently as the base data changes regularly. I checked the function in Jupyter Notebook and it ran fine (note the indents in the version below are out):

def ADD(zone,area):
    if zone in "R1":
        return 0.7
    elif zone in ["R2","R5","RU1","RU2","RU4","RU5"]:
        return 0.96
    elif zone=="R1":
        return 0.4
    elif zone=="IN2":
        return 11.5*area
    elif zone=="IN2":
        return 26.5*area
    elif zone in ["IN3"]:
        return 68.5*area
    elif zone in ["B1","B3","B4","B5","B6"]:
        return 11.5*area
    else:
        return "0.0"

Where "zone" and "area" are from the input attribute table and are string and float types respectively. I am expecting the returned value to be float also. However, I receive the following error:

Traceback (most recent call last):
File "C:/PROGRA~1/QGIS3~1.10/apps/qgis/./python/plugins\processing\algs\qgis\FieldPyculator.py", line 176, in processAlgorithm
exec(bytecode, new_ns)
File "<string>", line 1, in <module>
File "<string>", line 2, in ADD
TypeError: 'in <string>' requires string as left operand, not QVariant
Error encountered while running Determine ADD flows in KLD day
Error encountered while running Determine ADD flows in KLD day
Execution failed after 25.19 seconds

Strangely the Processing model terminates, but it looks like it completes the calculation correctly and adds in the new attribute as intended. I actually have two functions in a row, both in similar structure, and the second one won't run after the model crashes. I tried swapping the order and the same thing occurs, it crashes after the first one. I need to add in quite a few more python functions so really need it to not crash!

I am not an expert in either Python or QGIS, and I am wondering if I have an obvious error anywhere or something I am missing.

Best Answer

I found out the cause of the error. If I change

`if zone in "R1":`

to

if zone == "R1":

the function work without the error.

Related Question