Existance of of variable

Steven D'Aprano steve at REMOVETHIScyber.com.au
Mon Jul 4 19:21:04 EDT 2005


On Mon, 04 Jul 2005 21:17:21 +0200, tiissa wrote:

> Josiah Manson wrote:
>> Hello. I am very new to Python, and have been unable to figure out how
>> to check if a variable exists or not. In the following code I have made
>> a kludge that works, but I think that it would be clearer to check if
>> closest exists and not have to initialize it in the first place. How is
>> that check done?
> 
> Variables are stored in two dictionnaries: globals() (for global 
> variables) and locals() (for the local ones, which are also global on 
> top level).

Should we *really* be encouraging newbies to mess with globals() and
locals()? Isn't that giving them the tools to shoot their foot off before
teaching them how to put shoes on?

[snip]

>> I also have a few other questions to tack on if you don't mind. I
>> am
>> setting dist to 1e9, because that is a larger value than any of the
>> places in the galaxy will be far away. Is there a better way to
>> initialize dist so that it is impossible for this to fail? For example,
>> would setting dist to infinity work, and how is that done?
> 
> The float constructed from the string 'inf', float('inf'), may do the
> trick. I don't know the details, though.
> 
>   >>> 1e100 < float('inf')
>   True

This is not guaranteed to work in any Python. It *might* work, depending
on the underlying C library, which is operating system dependent.


-- 
Steven.





More information about the Python-list mailing list