Values and objects

MRAB python at mrabarnett.plus.com
Sat May 10 15:22:12 EDT 2014


On 2014-05-10 20:10, Ethan Furman wrote:
> On 05/10/2014 02:32 AM, Chris Angelico wrote:
>>
>> Tell me, what may this function do in a compliant Python?
>>
>> def demo():
>>      ret = spam
>>      spam = 23
>>      return ret
>>
>> In CPython, that'll raise UnboundLocalError, because the local
>> variable 'spam' does already exist, and currently has no value (no
>> object bound to it).
>
> No, it does not exist -- or, more accurately, it does not exist *yet* but will.  The fact that there is a slot waiting
> for what will be spam is a cpython implementation detail.
>
> And if you don't like that argument (although it is a perfectly sound and correct argument), think of the module name space:
>
> ret = spam
> spam = 23
>
> will net you a simple NameError, because spam has not yet been created.
>
>
>>  If a compliant Python implementation is allowed
>> to have this return the value of a global or builtin spam, then I
>> would agree that you can create variables at run time.
>
> See module example above.  This behavior is not allowed in functions for scope and sanity (mostly sanity) reasons.
>
UnboundLocalError is like NameError, except that Python knows that the
name is local because somewhere in the function you're binding to that
name and you haven't said that it's global or nonlocal. Having a
different exception for that case makes it clearer to the user what the
problem is.



More information about the Python-list mailing list