So, in file2.py
there are two variables defined, right? sam
and dan
.
You can see that taking advantage than in Python, everything is an object:
import file2
print("This is what I found in file2:\n%s" % vars(file2))
You'll see a looot of stuff, but among other things, you will see your sam
and dan
variables. There is no myvar
name, right? In your question file1.py
's myvar
will contain the name of the variable that you want to access...
And here's where getattr
comes in: Given an instance, how can you get one of its fields if you know its name (if you have the name stored in a string). Like this: getattr(file2, myvar)
So your loopbov
function, where you pass the name of the list to iterate in the myvar
argument would become:
def loopbov(myvar):
lst=[]
for each in getattr(file2, myvar):
# myvar will be the string `"sam"`
te = fet(each):
lst.append(te)
return lst
As @MadPhysicist mentioned in his comment, it's probably worth mentioning what getattr
will do when it's trying to get an attribute by name that is not defined: You will get an AttributeError
exception. Try it. Put somewhere in your file1.py
this code: getattr(file2, "foobar")
However! If you see the docs for getattr
you will see that accepts an optional argument: default
. That can be read like "ok, if I don't find the attribute, I won't give you an error, but that default
argument".
Probably it's also worth it reading a bit, if you're interested in the subject, about how import works and the namespaces it creates (see this and this)