ianyoung
ianyoung

Reputation: 3035

List Comprehension - local variable referenced before assignment error

I have a source list of images which looks like this (simplified for brevity):

images = [
    {
        'url': 'https://example.com/image.jpg',
        'description': 'Caption',
        'type': 'photograph',
        'order': 1
    },
    {
        'url': 'https://example.com/image.jpg',
        'description': 'Caption',
        'type': 'photograph',
        'order': 2
    }
]

And I'm using a dictionary comprehension inside a list comprehension to remove 2 dictionary items and build a new list of cleaned dictionaries:

images_cleaned = [{k:v for k,v in i.items() if k != 'order' and k != 'type'} for i in images]

I then return the new list at the end of my function:

return images_cleaned

This is inside a list of properties (real estate) which contain a list of images available via a separate request. For 25 properties the code works fine, but then I get to the 26th and it trips up with an error:

UnboundLocalError: local variable 'images_cleaned' referenced before assignment

Looking at the images available for this property however, doesn't reveal anything different. It contains the same list of images.

Is there anything noticeably wrong with my images_cleaned list and dictionary comprehension which would result in nothing behind assigned to images_cleaned variable before returning? It's my assumption that even if there were no images then the variable would still be an empty list []?

Edit: Specifically the error occurs on the return statement, returning images_cleaned.

Upvotes: -1

Views: 16931

Answers (2)

Rob S.
Rob S.

Reputation: 2568

This is inside a list of properties (real estate) which contain a list of images available via a separate request.

Is the "separate request" within a try / except block? I suspect the 26th property is raising an Exception and images_cleaned is not getting assigned.

Upvotes: -1

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38552

Your existing code works fine when I tested it, seems the issue is on another part of your code. Note: I just replace multiple condition check with not in,

images = [
    {
        'url': 'https://example.com/image.jpg',
        'description': 'Caption',
        'type': 'photograph',
        'order': 1
    },
    {
        'url': 'https://example.com/image.jpg',
        'description': 'Caption',
        'type': 'photograph',
        'order': 2
    }
]

def filter_and_clean_image(images):
    images_cleaned = [{k:v for k,v in i.items() if k not in ['order','type']} for i in images]
    return images_cleaned


print(filter_and_clean_image(images))

Output:

[{'url': 'https://example.com/image.jpg', 'description': 'Caption'}, {'url': 'https://example.com/image.jpg', 'description': 'Caption'}]

What could be your case:

Referenced from here

The local variable referenced before the assignment occurs when some variable is referenced before the assignment within a function’s body. The error usually occurs when the code tries to access the global variable. As the global variables have global scope and can be accessed from anywhere within the program, the user usually tries to use the global variable within a function.

In Python, we do not have to declare or initialized the variable before using it; a variable is always considered local by default. Therefore when the program tries to access the global variable within a function without specifying it as global, the code will return the local variable referenced before the assignment error, since the variable being referenced is considered a local variable.

The below example code demonstrates the code scenario where the program will end up with the “local variable referenced before assignment” error.

count = 10
def myfunc():
    count = count + 1
    print(count)
  
myfunc()

Output:

UnboundLocalError: local variable 'count' referenced before assignment

To fix that, We need to declare the count variable as global using the global keyword to resolve this error. The below example code demonstrates how the error can be resolved using the global keyword in the above code scenario.

count = 10
def myfunc():
    global count
    count = count + 1
    print(count)
  
myfunc()

Output:

11

Upvotes: 1

Related Questions