Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

3rd Edition, Chapter 4 Nested Scope section #6

Open
gitgithan opened this issue Jul 23, 2023 · 0 comments
Open

3rd Edition, Chapter 4 Nested Scope section #6

gitgithan opened this issue Jul 23, 2023 · 0 comments

Comments

@gitgithan
Copy link

def f(x):
    def g():
      x = 'abc'
      print('x =', x)
    def h():
      z = x
      print('z =', z)
    x = x + 1
    print('x =', x)
    h()
    g()
    print('x =', x)
    return g

Book says If the name is found (which it is in this case), the value to which it is bound (4) is used. If it is not found there, an error message is produced.

I'm not sure if above is correct. My understanding of LEGB is python will look in the closest enclosing scope, then global. x does not have to be defined in the immediately enclosing scope of f, but any enclosing scope, searching outwards through all enclosing functions until it finds one. Failing which, it goes to global scope to find x, which will happen in this example if x is not found in scope of def f, and print the global x=3, so no error message is produced.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant