I've coded something like
#!/usr/bin/env python3
'''
Illustration
'''
class C1:
lst1 = "one", "two", "three"
lst2 = "red", "green", "blue"
dct1 = { "ten": 10, "eleven": 11, "twelve": 12 }
lst3 = tuple(dct1.keys())
lst4 = tuple(x for x in lst2)
lst5 = tuple(x for x in lst1 if x not in lst2)
# vim:set ft=python ai et ts=4 sts=4 sw=4 cc=80:EOF #
then ran the code and got
Traceback (most recent call last):
File "/home/jno/xxx.py", line 7, in <module>
class C1:
File "/home/jno/xxx.py", line 13, in C1
lst5 = tuple(x for x in lst1 if x not in lst2)
File "/home/jno/xxx.py", line 13, in <genexpr>
lst5 = tuple(x for x in lst1 if x not in lst2)
NameError: name 'lst2' is not defined
So, I wonder, why the hell lst2
is visible in lst4
creation and not visible in lst5
?
I mean, what's the difference in appearance in different clauses of the same symbol regarding that symbol visibility?
Or how do I have to reference it here?
PS. RESOLVED (Thanks to moderator for way better refs than were provided at the time of question creation!)
It will work in this notation:
class C1:
lst1 = "one", "two", "three"
lst2 = "red", "green", "blue"
dct1 = { "ten": 10, "eleven": 11, "twelve": 12 }
lst3 = tuple(dct1.keys())
lst4 = tuple(x for x in lst2)
# lst5 = tuple(x for x in lst1 if x not in lst2)
lst5 = (lambda P1, P2: tuple(x for x in P1 if x not in P2))(lst1, lst2) # move name resolution out of "function scope"
See https://stackoverflow.com/a/40849176/1278896 And https://docs.python.org/3/reference/executionmodel.html#resolution-of-names