4
class A:
    func = lambda x: x+4
    added_values = [func(45)]


if __name__=="__main__":
    print(A.added_values)

The above code outputs [49], that is expected. Then why this code

class A:
    func = lambda x: x+4
    added_values = [func(45) for _ in range(1)]


if __name__=="__main__":
    print(A.added_values)

gives undefined error, what is happening here?

Traceback (most recent call last):
  File "/home/yeti/Documents/PycharmProjects/pythonProject/main.py", line 1, in <module>
    class A:
  File "/home/yeti/Documents/PycharmProjects/pythonProject/main.py", line 3, in A
    added_values = [func(45) for _ in range(1)]
  File "/home/yeti/Documents/PycharmProjects/pythonProject/main.py", line 3, in <listcomp>
    added_values = [func(45) for _ in range(1)]
NameError: name 'func' is not defined

I do not know what is happening under the hood, looks very strange to me.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
HaoZhang
  • 41
  • 1
  • What happens if you use `def` and annotate with `@classmethod` or `@staticmethod`? – OneCricketeer Dec 13 '22 at 23:57
  • Looks like the list comprehension creates a new scope that `func` isn't defined in. Seems kinda weird, since that doesn't happen in (e.g.) a function body. – Samwise Dec 13 '22 at 23:59

0 Answers0