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

Establishing if an Object is Defined

P: n/a
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
Share this Question
Share on Google+
2 Replies


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

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