1

I'm trying to create variable with a certain function (see code below). When I run get_cloud() and print cloud from the console, it says:

NameError: name 'cloud' is not defined

When I run the for loop outside the function, it works just fine.

def get_cloud():
   for layer in iface.legendInterface().layers():
        if "cloud" in layer.name():
            cloud = layer
        else:
            pass
2

One way is to return the layer in your function and call this when you run it:

def get_cloud():
    for layer in iface.legendInterface().layers():
        if "cloud" in layer.name():
            cloud = layer
    return cloud

Then run the following to get the layer:

cloud = get_cloud()

Now you should be able to print cloud.

1

I try to understand why you make cloud variable global. @Joseph didn't mention that in his answer, which is correct. I guess you can simply write, it does nothing if your layer is not named cloud:

def get_cloud():
    for layer in iface.legendInterface().layers():
        if "cloud" in layer.name():
            return layer

cloud = get_cloud()
2
  • I set the cloud variable to global because my qgis crashed/ did not respond without it being set. I think its because of recursion? I'm not sure.
    – Wonka
    Dec 22 '17 at 15:22
  • Can you share your script? QGIS mustn't crash because of that.
    – etrimaille
    Dec 25 '17 at 9:43
1

@Joseph

It seems working. Thanks!. I rewrote my function according to Joseph's solution below. I put cloud = get_cloud() inside my function because I need to connect the function with a signal in my full script. I also set the cloud variable to global cloud because my QGIS did not respond without this being set first.

def get_cloud():
    for layer in iface.legendInterface().layers():
            if "cloud" in layer.name():
                cloud = layer
            else:
                pass
    return cloud
    global cloud
    cloud = get_cloud()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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