tags:

views:

51

answers:

2

I have two python files. From python file #1, I want to check to see if there is a certain global variable defined in python file #2.

What is the best way to do this?

+1  A: 
try:
    from file import varName
except ImportError:
    print 'var not found'

Alternatively you could do this (if you already imported the file):

import file
# ...
try:
    v = file.varName
except AttributeError:
    print 'var not found'

This will work only if the var is global. If you are after scoped variables, you'll need to use introspection.

Yuval A
Is it OK to put in import statement in the middle of the code? By OK I mean not bad convention.
paassno
Sure, it's totally acceptable to defer module loading to a later stage.
Yuval A
You could also just `import file` at the beginning, and later on check for `file.varName`, exactly the same way.
Yuval A
Alrite your comment is exactly what I needed.
paassno
I do have a problem in the script. For some reason, it goes into the try statement, passes, then goes to the except statement?
paassno
If there's only one line in the `try` block that is impossible. You are debugging wrong.
Yuval A
Yea I figured it out. For some reason when I do v = file.varName, its still going into the except statement even when the variable existsUpdate: using getattr(file, varName) works
paassno
+1 for a nice EAFP
katrielalex
A: 

You can directly test whether the file2 module (which is a module object) has an attribute with the right name:

import file2
if hasattr(file2, 'varName'):
    # varName is defined in file2…

This may be more direct and legible than the try… except… approach.

EOL