Existance of of variable

Benjamin Niemann pink at odahoda.de
Mon Jul 4 16:44:10 EDT 2005


George Sakkis wrote:

> Hi Josiah,
> 
>> 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?
>>
>> The following code finds the closest place to a position and rejects
>> places that are too far away.
>>
>>         dist = 1e9
>>         closest = -1
>>
>>         for n,p in galaxy.places.iteritems():
>>             dif = p.pos - pos
>>             len = dif.len()
>>             if len < dist and len < 10.0/self.zoom:
>>                 dist = len
>>                 closest = p
>>
>>         if closest != -1:
>>             self.sel = [closest.name]
> 
> I would write it like this:
> 
> def setClosest(self, pos, galaxy):
>     minDist, closestPlace = min([((place.pos-pos).len(), place)
>                            for place in galaxy.places.itervalues()])
>     if minDist < 10.0/self.zoom:
>         self.sel = [closestPlace.name]
>     else:
>         raise RuntimeError("No place close enough")

A galaxy can be pretty big and contain a lot of places ;) You'll easily run
out of memory, if you try to build a list of (dist, place) tuples. Better
use the generator syntax (requires python 2.4):

     minDist, closestPlace = min(((place.pos-pos).len(), place)
                            for place in galaxy.places.itervalues())



-- 
Benjamin Niemann
Email: pink at odahoda dot de
WWW: http://www.odahoda.de/



More information about the Python-list mailing list