Dportology
Dportology

Reputation: 808

Can't resolve outer reference to global variable because of inner reference

I Have the following code:

    l_sortedQueue = sorted(l_queue, key=lambda i: i['priority'])

    for i, d in enumerate(l_sortedQueue):
        if d['key'] == some_value:
            l_queue= l_sortedQueue.insert(n_queue_position, l_sortedQueue.pop(i))

So I'm basically trying to move one of the dictionary entries in l_queue into a new index while shifting all the other values over one but because of how the data is organized in the list, I had to do it this way (sorting the list based on a 'priority' value before moving the item to a new index). For some reason however, when I reference l_queue within the for loop as in this line:

l_queue = l_sortedQueue.insert(n_queue_position, l_sortedQueue.pop(i))

The OUTER reference to l_queue becomes unresolved, and the inner reference refers to a new local variable instead of the global list variable. Without this inner reference, it properly references the global variable however. Why is this? How do I get the inner and outer reference to l_queue to reference the global list variable?

Not sure if it is relevant, but this code comes from a flask function.

Upvotes: 0

Views: 37

Answers (1)

Joost
Joost

Reputation: 3729

Try printing this line: l_sortedQueue.insert(n_queue_position, l_sortedQueue.pop(i)). You will see that it prints to None. This is because insert is a function, which doesn't return a value. So what you think you're doing is assigning l_SortedQueue to l_queue, but what you're actually doing is overwriting your l_queue list with the None.

What you should change it to:

sortedQueue.insert(n_location, sortedQueue.pop())
que = sortedQueue

However, it looks like you're looping in a pretty hacky way which I'm not really following. I think there are better solution to your problem than this solution though.

Upvotes: 1

Related Questions