Anyway to check if a variable exits in other python file without NameError?

Ken Seehof kens at sightreader.com
Tue Apr 24 15:54:03 EDT 2001


<ed_tsang at yahoo.com> wrote:
> Hi  am tryin to find if another variable, called EVENTHANDLEr exits
> in a file caled pixit.py.
>
> pixit.py looks like:
>
> EVENTHANDLER = {}
> print EVENTHANDLER
>
> The following is the script I am test trying, but it always print
> None. wWhat gives? Any suggestion? Or is ther another way?
>
>
>
> guiCb = CtfGui(None)
> pixitObj = None
>
> EventHandler = None
>
> def setPixit(value):
>     global pixitObj

global guiCb not necessary. It's value is -not- changed.

>     global guiCb  # setting value of guiCb
>     global EventHandler
>     pixitObj = value

-attribute- in guiCb is modified

>     guiCb.pixitObj = value # copy value
>     print "where are you?"
>     try:
>        EventHandler = guiCb.pixitObj.EventHandler
>        print EventHandler
>     except:

print something here.  Better yet, get rid of this try-except
so you can see the traceback.  Maybe you wanted
except NameError
but we will improve on that....

>        pass
>
> exec("import pixit")
> exec("reload(pixit)")
> setPixit(pixit)
>
> if EventHandler != None:
>    print "Hi"
> else:
>    print EventHandler
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

My guess is that the line:
  EventHandler = guiCb.pixitObj.EventHandler
is throwing an exception.  Remove the try-except to find out.

Don't debug just by inspection. You will get nowhere.  Debug
by binary search.  Cut the area in your program where the bug
might be in half.  Repeat the process.  When you are down to
one line you will know where your bug is.  try-except: pass
just hides the problem.  If the binary search approach doesn't
actually find the problem, it will at least shrink the probem so
you can post it here as a very short example (6 lines or less).

Also, when sharing your bug, please show us the -complete-
output of your program (did the "where are you?" show up?)

To answer your original question: Yes.  Use hasattr.

>>> import string
>>> hasattr(string, 'lowercase')
1
>>> hasattr(string, 'superstring')
0

- Ken Seehof kseehof at neuralintegrator.com








More information about the Python-list mailing list