Could you explain this rebinding (or some other action) on "nums = nums"?

fl rxjwg98 at gmail.com
Wed Jun 24 19:52:10 EDT 2015


Hi,

I read a blog written by Ned and find it is very interesting, but I am still
unclear it in some parts. In the following example, I am almost lost at the
last line: 

nums = num


Could anyone explain it in a more detail to me?

Thanks,





.......................
The reason is that list implements __iadd__ like this (except in C, not Python):

class List:
    def __iadd__(self, other):
        self.extend(other)
        return self
When you execute "nums += more", you're getting the same effect as:

nums = nums.__iadd__(more)
which, because of the implementation of __iadd__, acts like this:

nums.extend(more)
nums = nums
So there is a rebinding operation here, but first, there's a mutating operation, and the rebinding operation is a no-op.



More information about the Python-list mailing list