Checking if variable from a list exists in imported file
Question:
I’m trying to build a simple iterative code that goes through a list of variables and checks it from a file.
For example, if could have 2 variables foo1 and foo2, I could do the following
try:
from file import foo1
except ImportError:
foo1 = None
try:
from file import foo2
except ImportError:
foo2 = None
And so forth. But now, my list of variables are getting pretty long. Is there an easier way to put my list of variables (i.e. foo1, foo2, foo3, etc) into a list and attempt to see if it exists in "file" instead of repeat this try-catch process?
I tried the following, but it didn’t seem to work, especially when foo1 or foo2 did exist.
my_list = ['foo1', 'foo2']
for listElem in my_list:
try:
from file import listElem
except ImportError:
print ("Can't find",listElem,"in file")
Thanks
Answers:
You can do something like this:
import file
my_list = ['foo1', 'foo2']
for listElem in my_list:
if not (value := getattr(file, listElem, None)):
print ("Can't find",listElem,"in file")
globals()[listElem] = value
globals()
is a dictionary that contains all top-level names. What we do in the above snippet is to create global variables using the names from my_list
.
I’m trying to build a simple iterative code that goes through a list of variables and checks it from a file.
For example, if could have 2 variables foo1 and foo2, I could do the following
try:
from file import foo1
except ImportError:
foo1 = None
try:
from file import foo2
except ImportError:
foo2 = None
And so forth. But now, my list of variables are getting pretty long. Is there an easier way to put my list of variables (i.e. foo1, foo2, foo3, etc) into a list and attempt to see if it exists in "file" instead of repeat this try-catch process?
I tried the following, but it didn’t seem to work, especially when foo1 or foo2 did exist.
my_list = ['foo1', 'foo2']
for listElem in my_list:
try:
from file import listElem
except ImportError:
print ("Can't find",listElem,"in file")
Thanks
You can do something like this:
import file
my_list = ['foo1', 'foo2']
for listElem in my_list:
if not (value := getattr(file, listElem, None)):
print ("Can't find",listElem,"in file")
globals()[listElem] = value
globals()
is a dictionary that contains all top-level names. What we do in the above snippet is to create global variables using the names from my_list
.