Values and objects

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun May 11 03:29:07 EDT 2014


On Sun, 11 May 2014 11:59:21 +1000, Chris Angelico wrote:

> On Sun, May 11, 2014 at 11:28 AM, Ethan Furman <ethan at stoneleaf.us>
> wrote:
>> Well, with function variables they have to exist *when you use them*.
>> ;)
>>
>> This seems like more of a scoping issue than a "can we create variables
>> in Python" issue.
>>
>> I am curious, though, what other python's do with respect to function
>> variables.
> 
> Variables exist in scope. Apart from assembly language, where registers
> have universal scope, every language I know of has some concept of
> scope. 

BASIC.


> (REXX is very different from most, in that "PROCEDURE EXPOSE"
> isn't at all your classic notion of scoping, but there's still the
> concept that there can be two variables with the same name.) When you
> create one, you create it in a particular scope, and that's how it must
> be.

Yes. But when do you create it? At declaration time, or when a value is 
bound to it?


# Ensure spam does not exist.
try:
    del spam
except NameError:
    pass
assert "spam" not in globals()

# Declare spam.
global spam
print ("spam" in globals())  # prints False
print (spam)  # raises NameError


The same applies to locals. Whether a slot is pre-allocated or not, the 
variable doesn't exist until there is a value bound to the name.


-- 
Steven D'Aprano
http://import-that.dreamwidth.org/



More information about the Python-list mailing list