0

while i was reading about namespacing and scopping in python, i read that

-the innermost scope, which is searched first, contains the local names
-the scopes of any enclosing functions, which are searched starting with the nearest enclosing scope, contains non-local, but also non-global names
-the next-to-last scope contains the current module’s global names
-the outermost scope (searched last) is the namespace containing built-in names

but when i tried this :

def test() :
    name = 'karim'

    def tata() :
        print(name)
        name='zaka'
        print(name)
    tata()

i have received this error :

UnboundLocalError: local variable 'name' referenced before assignment

when the statement print(name) the tata() function will not find name in the current scope so python will go up in scope and find it in test() function scope no??

zhangxaochen
  • 32,744
  • 15
  • 77
  • 108
KarimS
  • 3,812
  • 9
  • 41
  • 64

1 Answers1

0

In python 3 you can use nonlocal name to tell python that name is not defined in the local scope and it should look for it in an outer scope.

This works:

def tata():
    nonlocal name
    print(name)
    name='zaka'
    print(name)
eugecm
  • 1,189
  • 8
  • 14