In python, accessing global variables of one file in another -
i have 2 python scripts, 1 of contains global variable globvar wish use in file. file structures follows:
file1.py
from file2 import * globvar = [] def func1(a,b): globvar.append(range(a,b)) printlast() def main(): in range(1,10): j in range(1,5): func1(i,j) if __name__=="__main__": main()
file2.py
from file1 import globvar def printlast(): element = globvar[-1] print 'latest element ',element
dont' bother productivity of code, it's example sample problem @ hand.
on running script file1.py, error pops up, globvar[-1] list index out of range. or simply, list empty.
why so?
edit :
this question, posted, contained "from file2 import printlast" first line of file1.py. syntax resulting in importerror pointed out @user2357112 in comments.
now has been changed from file2 import *, error indexerror, trying point out begin with.
any reasonable explanation appreciated.
this because main module file1.py
executed directly python special, , when import it, created second time, there 2 globvar
s. see: http://python-notes.curiousefficiency.org/en/latest/python_concepts/import_traps.html#executing-the-main-module-twice
Comments
Post a Comment