Existance of of variable

George Sakkis gsakkis at rutgers.edu
Mon Jul 4 22:12:56 CEST 2005

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]
        raise RuntimeError("No place close enough")

> 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?

Here's a safer way; it doesn't rely on what the maximum and minimum
number is in a specific platform:

Smallest = type("Smallest", (object,), {'__cmp__' :
                lambda self,other: self is not other and -1 or 0})()

Largest = type("Largest", (object,), {'__cmp__' :
                lambda self,other: self is not other and 1 or 0})()

assert Smallest == Smallest < -1e300 < 0 < 1e300 < Largest == Largest
assert Largest == Largest > 1e300 > 0 > -1e300 > Smallest == Smallest

Strictly speaking, Smallest and Largest should be singletons, to
protect you from stupid mistakes such as making copies of them.

> Extending my existance checking question, how does one check what type
> a variable has?

>>> type(3)
<type 'int'>
>>> type(3.0)
<type 'float'>

Almost in all cases though you should prefer "isinstance(variable,
sometype)" instead of "type(variable) == sometype", so that it doesn't
break for subclasses of sometype.

> Thanks for your help!
> -- Josiah


More information about the Python-list mailing list