I have a problem understanding what is happening with the outcome of the following pieces of code:
my_str = "outside func"
def func():
my_str = "inside func"
class C():
print(my_str)
print((lambda:my_str)())
my_str = "inside C"
print(my_str)
The output is:
outside func
inside func
inside C
Another piece of code is:
my_str = "not in class"
class C:
my_str = "in the class"
print([my_str for i in (1,2)])
print(list(my_str for i in (1,2)))
The output is:
[‘in the class’, 'in the class’]
['not in class’, 'not in class’]
The question is:
- What is happening here in each print() statement?
- Can anyone explain why the print() statement get the string from the different namespaces?
Edit 1:
I think this is different from this question because I humbly think the answers there do not explain this variation:
my_str = "outside func"
def func():
my_str = "inside func"
class C():
print(my_str)
print((lambda:my_str)())
#my_str = "inside C"
print(my_str)
The output is:
inside func
inside func
inside func
Edit 2:
Indeed, this is a duplicate from this question because as Martijn Pieters says:
The answer there states: If a name is assigned to within a class body, almost at the start. You assigned to my_str, making it the same case as y there. Commenting out that line means you are no longer assigning to my_str, making it the same case as x.