1

Let's consider the code below.

name = "John"

class MyClass:
    name = "Tom"
    list_1 = [name] * 2
    list_2 = [name for i in range(2)]

On first look, one might expect list_1 and list_2 to both have the same content: ["Tom", "Tom"], but this is not the case. list_1 evaluates to ["Tom", "Tom"], whereas list_2 evaluates to ["John", "John"].

I read that when a function is nested inside a class, Python will use variables defined in the module scope and not in the class scope. list_1 is not a function, so it uses name from the class scope, whereas list_2 is a function and, therefore, uses name from the module scope. I understand this is how it works, but it seems counter-intuitive. I don't understand the reason.

  • What are you asking? The reasons *why*? Because python class bodies don't create enclosing scopes, which is why you have to use `self` to, for example, call other methods defined in the class scope. That was the design decision when Guido wrote the language – juanpa.arrivillaga Feb 18 '21 at 04:39

1 Answers1

0

Scoping with list comprehensions takes some getting used to. In this case, the local scope within the list comprehension list2 = [name for i in range(2)] temporarily blocks class local scope. See: this answer.

rhurwitz
  • 2,557
  • 2
  • 10
  • 18