Skip to content
Advertisement

Python: Function scope inside a class

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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement