scope - python: variable availability in imported files -
i've got noob python question variable scope.
i've created 2 scripts. 1 included other:
file1.py
a = 10 file2 import * file2.py
print when seek execute file1.py, error: nameerror: name 'a' not defined
so, question. possible create script's variables available in included scripts?
update: i'm trying this: main.py
from config include * utils include * in config.py i'd have
filename = "/tmp/file.txt" in utils.py i'd have
def write_file(): the problem have whole bunch of little functions need filename. right don't have function in utils.py. have them in main.py. on time main.py got bigger , bigger i'm thinking if there easy way move utility functions away main script.
the print a in sec file executes in scope, not of first one. python modules aren't c header files, in code isn't 'embedded' file - module loaded, , code run, hence allowing access names module.
a demonstration of if __name__ == '__main__': block commonly found in modules. if code embedded script, code within block run every time, __name__ '__main__'. because code run within scope of imported module, __name__ different value, code run if in top-level script.
to able print a need from file1 import a in sec file.
addressing update, shouldn't problem. from config import filename in utils script allow utilize variable, long imported before filename referenced.
python scope
No comments:
Post a Comment