7

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?

3 Answers 3

8

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 (depending on how you want to use it).

Sign up to request clarification or add additional context in comments.

2 Comments

Could we also get its value?
@Yuval Adam's try solution would be the way to go.
6
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.

7 Comments

Is it OK to put in import statement in the middle of the code? By OK I mean not bad convention.
Sure, it's totally acceptable to defer module loading to a later stage.
You could also just import file at the beginning, and later on check for file.varName, exactly the same way.
Alrite your comment is exactly what I needed.
I do have a problem in the script. For some reason, it goes into the try statement, passes, then goes to the except statement?
|
3

With the getattr() built-in function you also can specify a default value like:

import file2

myVar = getattr(file2, attribute, False)

See the documentation

2 Comments

This does not generally answer the original question: what if the variable exists and is false?
Then the answer would be False anyway so still correct although i see what your saying

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.