nonlocal fails ?

Richard Damon Richard at Damon-family.org
Thu Nov 14 13:37:40 EST 2019


> On Nov 14, 2019, at 12:56 PM, R.Wieser <address at not.available> wrote:
> 
> Jan,
> 
>> So what you want to do is dynamic scope?
> 
> No, not really.    I was looking for method to let one procedure share a 
> variable with its caller - or callers, selectable by me.   And as a "by 
> reference" argument does not seem to exist in Python ...
> 
> And yes, I am a ware that procedures can return multiple results.  I just 
> didn'want to go that way (using the same variable twice in a single 
> calling).
> 
> Regards,
> Rudy Wieser

Watch out about thinking about ‘Variables’ because Python doesn’t really have them. In one sense EVERYTHING in Python is by reference, as names are just references bound to objects.

If you are pass a mutable object to a function, and the function uses the parameter that was bound to the object to mutate the object, that same object referenced in the caller has changed. (Note that strings, number, and tupples are not mutable, but lists, dictionaries and most class objects are).

The key is that the function should use assignment to the parameter name to try and change the object, but use mutating methods on the object to change it.

Thus if the caller creates a list and binds it to a name, and passes that to the function, then the function can manipulate the list (things like parm[0] = 5) and that change will be see by the caller. The function just needs to be careful not to do a parm = statement that would rebind the name and thus lose the reference to the callers object.


More information about the Python-list mailing list