Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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!


The main 'problem' there is the `global` keyword :^) (it's not needed for read access)


How would you read foo if it is hidden by a local parameter.


I 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


> But this being Python, this is a way

That's why I said nonlocal or global ;)


Seems like you shouldn’t do that?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: