Issue
So I have 2 files , file1.py and file2.py
I have a couple of lists sam and dan from file2.py
so when I try this from file1.py I get
AttributeError: 'module' object has no attribute 'myvar'
file1.py
import file2
f_var=[]
myvar = raw_input("some string")
if myvar == "sam":
f_var = loopbov("sam")
def loopbov(myvar):
lst=[]
for each in file2.myvar:
te = fet(each):
lst.append(te)
return lst
def fet(vpf):
tmp=[]
# this gets me an list as an output
return tmp
file2.py
sam=["33:89","21:70"]
dan=["34:43","23:56"]
I know it's a simple error but can someone explain how to access by parsing a object here to access from another file
Solution
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)
Answered By - BorrajaX
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.