List comprehension rebinds names even after scope of comprehension. Is this right?

后端 未结 6 2216
清酒与你
清酒与你 2020-11-22 04:03

Comprehensions are having some unexpected interactions with scoping. Is this the expected behavior?

I\'ve got a method:

def leave_room(self, uid):
           


        
6条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 04:40

    Yes, assignment occurs there, just like it would in a for loop. No new scope is being created.

    This is definitely the expected behavior: on each cycle, the value is bound to the name you specify. For instance,

    >>> x=0
    >>> a=[1,54,4,2,32,234,5234,]
    >>> [x for x in a if x>32]
    [54, 234, 5234]
    >>> x
    5234
    

    Once that's recognized, it seems easy enough to avoid: don't use existing names for the variables within comprehensions.

提交回复
热议问题