469,362 Members | 2,447 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,362 developers. It's quick & easy.

Establishing if an Object is Defined

Hi,

The following code works -

one = 1
if one == 1:
ok = 1
print ok

but this does not, without exception -

one = 2
if one == 1:
ok = 1
print ok

How do I establish before printing ok if it actually exists so as to
avoid this exception?

Thanks for your help,

Barry.

Jan 10 '07 #1
2 831
bg***@yahoo.com a écrit :
Hi,

The following code works -

one = 1
if one == 1:
ok = 1
print ok

but this does not, without exception -

one = 2
if one == 1:
ok = 1
print ok

How do I establish before printing ok if it actually exists so as to
avoid this exception?
ok = 0
....do the job...

Very simple, failure-proof, no special case.
Jan 10 '07 #2
bg***@yahoo.com a écrit :
Hi,

The following code works -

one = 1
if one == 1:
ok = 1
print ok

but this does not, without exception -

one = 2
Are you competing for the Most Misleading Name Award(tm) ?-)
if one == 1:
ok = 1
print ok

How do I establish before printing ok if it actually exists so as to
avoid this exception?
The simplest way is to make sure the name will be defined whatever the
value of the test:

one = 42
# ...
ok = (one == 1)
print ok
As a side note, if you want to check wether a name exists in the current
namespace, you can use a try/except block:

try:
toto
print "toto is defined"
except NameError:
print "toto is not defined"
Jan 10 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

8 posts views Thread by gs | last post: by
reply views Thread by Tor Inge Rislaa | last post: by
21 posts views Thread by phpCodeHead | last post: by
reply views Thread by gnewsgroup | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by suresh191 | last post: by
1 post views Thread by Marylou17 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.