Existance of of variable

Peter Otten __peter__ at web.de
Mon Jul 4 15:34:28 EDT 2005


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

try:
    variable
except NameError:
    # variable doesn't exist
else:
    # variable exists

But it is rare that you actually need to do that.

> 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 prefer to set the variable to the first item in the sequence and later
update that when I find "better" matches:

if galaxy.places:
    pos = somewhere()
    places = galaxy.places.itervalues()
    closest = places.next()
    closest_dist = (closest.pos - pos).len()
    for p in places:
        dist = (p.pos - pos).len()
        if dist < closest_dist:
            closest_dist = dist
            closest = p

    if closest_dist < 10.0/self.zoom:
        self.sel = [closest.name]

This is easy to understand but has the disadvantage of some redundant code
(the distance between 'pos' and 'some other place' is calculated both
before and in the loop. So here is an alternative that uses the min()
builtin:

def dp(places, pos):
    for i, p in enumerate(places):
        yield (p.pos - pos).len(), i, p

if galaxy.places:
    pos = somewhere()
    dist, _, place = min(dp(galaxy.places.itervalues(), pos))
    if  dist < 10.0/self.zoom:
        self.sel = [place.name]

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

type(variable) == some_type

or better

isinstance(variable, some_type) 

which is also true if variable is an instance of a subclass of some_type.

But again, I'd rather avoid that if possible because you can easily prevent
a function from working with objects you didn't think of when you wrote it
and that implement the same methods and attributes but are of a totally
unrelated class (google for "duck type").

Peter




More information about the Python-list mailing list