Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

4
  • In Python 3 there is the nonlocal keyword. Commented Aug 23, 2012 at 13:03
  • I don't get your replacement - cache[:] creates a copy of the list (which obviously works because you now don't assign to cache anymore) and assigns to this copy - but the copy is immediately discarded, so you're not actually assigning to the variable. So while your replacement fixes the error message, it doesn't actually do anything useful... Commented Aug 23, 2012 at 13:09
  • 1
    @l4mpi: Incorrect. cache[:] creates a copy when it's on the the right side of the assignment, but when it's on the left side, it indicates assignment to a slice, which is a mutating operation. To see this in action, paste this into the interpreter: a=[]; a_id = id(a); a[:] = [1,2,3]; id(a) == a_id. It will return True. Commented Aug 23, 2012 at 14:37
  • @StevenRumbalski, thanks for the info, I wasn't aware of this usage of the slice operation - upvoted the answer. Ok, so this works because it calls __setslice__ on the list, but still has some limitations: Obviously it only works for lists and not arbitrary variable types; it would fail if the variable had been initialized with None instead of []; the right side can only contain iterables meaning you can't set the variable to None or change its reference to another type or even another list (as a[:]=b where b is an iterable only copies b, so modifying a won't effect b). Commented Aug 23, 2012 at 16:06