473,326 Members | 2,111 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

Existance of of variable

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
9 1869
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
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

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

"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
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
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Fabian | last post by:
How can I check whether or not a variable exists in a script? I'm thinking in terms of if (my variable exists) { myfunction(); } -- -- Fabian Visit my website often and for long periods!
4
by: lyndon hughey | last post by:
I'm having a problem setting the testing for the existance of a nodes outerxml property. Below I try to test for the existance before I access the property, but I receive a null exception error. ...
0
by: Bob | last post by:
I want to find a way to detect the existance of the private member of a particular type in the derived class from inside the base class itself and call its Dispose() method. Reflection GetFields()...
4
by: Iain Porter | last post by:
Hi all, I have a usercontrol (a textbox with dropdown calendar that fills the textbox with the selected date) that I implement in a datagrid in a webform. On first loading the page, the datagrid's...
2
by: allavarapu | last post by:
Hi All, How can we found whether directory or/and file existed in linux filesystem . In shell script to check file existance : if and Directory existance using if . Than how can we check...
3
by: Duggi | last post by:
Hi When does a static variable come into life? Well, as far as my knowledge goes, I think it is during the execution of static constructor. Because thats the logic point in the program where the...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.