4 ms·
You can't use this if you also have a nonlocal or global variable named foo that you want to access. foo = 123 def myfunc(foo="bar"): global fo
by amelius 5y ago
You can't use this if you also have a nonlocal or global variable named foo that you want to access.
foo = 123
def myfunc(foo="bar"):
global foo # problem!
- diarrhea 5y agoThe main 'problem' there is the `global` keyword :^) (it's not needed for read access)
- amelius 5y agoHow would you read foo if it is hidden by a local parameter.
- diarrhea 5y agoI guess not at all. It's shadowed. But this being Python, this is a way: foo = 123 def lol(foo="bar"): print(globals()["foo"], foo) That will output "123 bar". But it's terrible! Your example is a SyntaxError, it doesn't even compile: In [1]: def myfunc(foo="bar"): ...: global foo Input In [1] global foo ^ SyntaxError: name 'foo' is parameter and global
- amelius 5y ago> But this being Python, this is a way That's why I said nonlocal or global ;)
- oneoff786 5y agoSeems like you shouldn’t do that?