nonlocal fails ?

Rhodri James rhodri at kynesim.co.uk
Thu Nov 14 13:28:52 EST 2019


On 14/11/2019 17:11, R.Wieser wrote:
> Rhodri,
> 
>> MyVar is a global here, so nonlocal explicitly doesn't pick it up.
> I do not agree with you there (the variable being global).  If it where than
> I would have been able to alter the variable inside the procedure without
> having to resort to a "global" override (an override which is only valid for
> the context its used in by the way, not anywhere else)
> 
> Than again, that is how it works in a few other languages, so I might have
> been poisonned by them.:-)

You have been.

   # This is at the top level of a module
   # I.e. it's a global variable
   my_global_variable = 5

   # You can read globals from within a function without declaring them
   def show_my_global():
     print(my_global_variable)

   # If you try setting it, you get a local instead
   def fudge_my_global(n):
     my_global_variable = n

   show_my_global()  # prints '5'
   fudge_my_global(2)
   show_my_global()  # prints '5'

   # If you read the variable before setting it, you get an exception
   def mess_up_my_global(n):
     print(my_global_variable)
     my_global_variable = n

   mess_up_my_global(2) # UnboundLocalError!

   # ...because it must be a local because of the assignment, but it
   # doesn't have a value at the time print() is called.

   # To do it right, declare you want the global from the get go
   def love_my_global(n):
     global my_global_variable
     print("It was ", my_global_variable)
     my_global_variable = n

   love_my_global(3) # prints 'It was 5'
   show_my_global()  # prints '3'

-- 
Rhodri James *-* Kynesim Ltd


More information about the Python-list mailing list