nonlocal fails ?

Richard Damon Richard at Damon-Family.org
Thu Nov 14 23:17:44 EST 2019


On 11/14/19 1:43 PM, R.Wieser wrote:
> Richard,
>
>> Assuming that one language works like another is a danger
> Abitrarily redefining words and using misnomers is another ...  ("global" 
> and "nonlocal" respecivily if you wonder)
>
>> First, Python doesn't really have 'Variables' like a lot of other 
>> languages
>> (they don't hold a bag of bytes), as Python names don't hold values, but
>> are just references to objects which actually hold the value
> That's a principle as old as programming languages itself I believe.

There are at least two very different concepts that act like variables
in different languages. In a language like C, a variable is a 'bucket of
byte' that holds some value. If you assign the value of one variable to
another, that byte pattern is copied from one to another. That
representation might include a pointer to some other block (a pointer or
reference), but generally this is something explicit. In this sort of
language your names represent variables that actually hold values.

In Python, the name for your 'variable' doesn't actually hold the value
that is assigned to it, but instead the bucket of bytes associated with
the name is ALWAYS a pointer to a bucket of bytes that represents the
value. Multiple names are allowed to point to the same value object, so
assigning one name to another just copies that pointer, and they share
the same value object. You shouldn't really think of names as holding
'values' but the names are 'bound' to the value objects (which aren't
tied to a given name).

>
>> If the name is never bound to something, then the name will be also looked
>> for in the global namespace.
> Can you give an example of that ?    I currently cannot wrap my head around 
> what you could be meaning there - anything I can imagine simply doesn't make 
> any sense ...
>
> Regards,
> Rudy Wieser
>
#This Function creates a local name and updates it. str will be created
locally and looked up locally

def useslocal():

    str = "String"

    str = str + " Added"


gstr = "Global"

# This function never binds a value to gstr, so it will look in the
'global' space to find the name

def useglobal():

   str = gstr + " Seen"


# This function include a binding to gstr, so it is only looked for
locally,

#so this use will create an error that it can't find gstr,

# even though it was defined in the global name space

def getserror():

    str = gstr + " Error"

    gstr = str

# This works because of the global statement, and updates the global

def workingglobal():

    global gstr

    str = gstr + " Error"

    gstr = str


-- 
Richard Damon



More information about the Python-list mailing list