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

Asked By: Chris

||

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.

Answered By: smac89
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.