By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,767 Members | 1,987 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,767 IT Pros & Developers. It's quick & easy.

Existance of of variable

P: n/a
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 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?

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

Thanks for your help!

-- Josiah

Jul 21 '05 #1
Share this Question
Share on Google+
9 Replies


P: n/a
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).

You can therefore write:

if 'closest' in locals():
self.sel = [closest.name]
On the other hand, if you try to access a variable which doesn't exist,
you'll get the NameError exception. Another way is then:

try:
self.sel = [closest.name]
except NameError:
pass

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

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


The '__class__' special attribute [1] will return the class. You can
also look at the builtin 'isinstance' [2].

However, type checking is not a common idiom in python since we tend to
use 'duck typing': if your object can do what you want with it, don't
bother to check if it is exactly of the class you expect.
Therefore we often try to use the object then catch the exception rather
than check the object then use it.

Of course, there may be situations where it's not suitable but type
checking seems not to be too common in python.
[1] http://docs.python.org/lib/specialattrs.html
[2] http://docs.python.org/lib/built-in-funcs.html
Jul 21 '05 #2

P: n/a
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

Jul 21 '05 #3

P: n/a

"Josiah Manson" <sl*******@gmail.com> wrote in message
news:11**********************@g43g2000cwa.googlegr oups.com...
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
Python does not have variables is the sense some other languages do. It
has (typeless) names bound to typed objects with values. This is a
different object-value model and a different mindset from some other
languages.
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?
What you did is normal Python code. Checking whether 'closest' is bound to
anything can be done but that *is* a kludge, which I will leave for you to
discover elsewhere.
The following code finds the closest place to a position and rejects
places that are too far away.

dist = 1e9
closest = -1
closest = None # is the standard for 'not bound to anything'
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 you generate a sequence of (distance, place) pairs, beginning with
(1e99, None), you can select the mimimum distance pair with the min()
builtin function instead of rewriting it.
if closest != -1:
if closest: # bool(None) == False, bool(anyplace) == True
self.sel = [closest.name]

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?
Maybe, depending on the compiler. For now, I would stick with a known
larger-than-possible value.
Extending my existance checking question, how does one check what type
a variable has?


See the first two sentences above and look up type() and isinstance() in
the 2nd chapter of the Library reference. (And do read that entire chapter
if you have not.)

Terry J. Reedy

Jul 21 '05 #4

P: n/a
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")

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


Regards,
George

Jul 21 '05 #5

P: n/a
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/
Jul 21 '05 #6

P: n/a

"tiissa" <ti****@nonfree.fr> wrote in message
news:42***********************@news.free.fr...
Variables are stored in two dictionnaries: globals() (for global
variables) and locals() (for the local ones, which are also global on
top level).


Within a function, the local namespace is usually *not* a dictionary.
D=locals() makes a dictionary copy of the namespace,
which takes more time than one might expect, and
which has the trap that changes to D do *not* affect the namespace itself.
So the try..except idiom is faster and does not have that particular trap.

Terry J. Reedy


Jul 21 '05 #7

P: n/a
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.
Jul 21 '05 #8

P: n/a
Steven D'Aprano <st***@REMOVETHIScyber.com.au> wrote:
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?


Why risk damaging perfectly good footwear?

But, seriously, I agree with you. The cannonical way to tell if a variable
exists in Python is to try to access it and catch any resulting NameError.
Jul 21 '05 #9

P: n/a
Am Montag, den 04.07.2005, 20:25 -0400 schrieb Roy Smith:
Steven D'Aprano <st***@REMOVETHIScyber.com.au> wrote:
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?


Why risk damaging perfectly good footwear?

But, seriously, I agree with you. The cannonical way to tell if a variable
exists in Python is to try to access it and catch any resulting NameError..

Although it should be said that this goes only for variables. obj.value
isn't such a beast (even if some newbies might think so), and would
throw an AttributeError.

Another thing to consider when it comes to footwear: Ruining it once and
enduring the resulting discomfort teaches quite well. And leaves a
respect for the "magic" features of Python that stays the rest of one's
life :)

So I think every newbie at some time of his/her learning process should
probably have fun with all the cool features of Python (be it globals(),
assigning to __builtins__, __getattr__ and derived classes, or what
ever ;) ). Playing alone is not enough, but playing and living to
maintain the code afterwards is very educative ;)
OTOH, perhaps for me it was teaching more, because I have been forced to
maintain by first bigger python application almost for a decade. One
learns quite a bit about software engineering this way ;)

Andreas
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)

iD8DBQBC1MJ5HJdudm4KnO0RAt92AJoCg9s76OVPR5rowMMbgu W5MdGw+wCg2oFX
6drWNA8V0cSCuYJ3JIJMHg0=
=ADxJ
-----END PGP SIGNATURE-----

Jul 21 '05 #10

This discussion thread is closed

Replies have been disabled for this discussion.