nonlocal fails ?

Terry Reedy tjreedy at udel.edu
Thu Nov 14 18:22:35 EST 2019


On 11/14/2019 4:16 PM, R.Wieser wrote:

>> If you mentioned what problem you are trying to solve
> 
> 1) Have value
> 2) use value in procedure 1
> 3) use updated value in procedure 2
> 4) use again updated value in procedure 1, 2 or maybe 3

> For the sake of learning I'm now going over all of the possibilities to see
> if and how they work.
  >  For that I've already excluded globals and the
> practice of feeding the value as an argument to the procedure and than store
> its result as the new one.

This is discouraged for anything very complex.

> I've also excluded using a class object and put
> the code in there,

This is the standard way in Python and other OO languages.  By 
'excluded', do you mean 'rejected', or 'tried that, what else is there?'

> as well as faking a "by reference" passing by using a tuple.

One has to pass a mutable, such as list, set, dict, or user class instance.

"nonlocal" looked to be another option, but it appears to be rather
> limited in its application.

Closures are standard in functional languages and are less limited than 
you seem to think.  But you have to enclose (nest) many or all of the 
functions that directly rebind 'val' (else one might as well use a 
global value).

def valclass(val):
     def set(newval):  # For functions not defined within valclass.
         nonlocal val
         val = newval
     def get()
         return val
     def proc1(args)
         nonlocal val
         ...
     dev proc2(args)
         nonlocal val
         ...
     return setval, getval, proc1, proc2
     # return {'set':set, 'get':get, 'proc1':proc1, 'proc2':proc2}

setval, getval, proc1, proc2 = valclass(3)
# val = valclass(3)

> In short, the /ways to the goal/ are (currently) important to me, not the
> goal itself (I'm sure that apart from the "nonlocal" one all of the above
> are viable, and I thus can get /something/ to work)


-- 
Terry Jan Reedy



More information about the Python-list mailing list