Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if a variable exists in another Python file

Tags:

python

file

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?

like image 729
paassno Avatar asked Aug 04 '10 20:08

paassno


2 Answers

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.

like image 100
Yuval Adam Avatar answered Oct 10 '22 16:10

Yuval Adam


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).

like image 29
Eric O Lebigot Avatar answered Oct 10 '22 18:10

Eric O Lebigot