[Tutor] Accessing variables in main from functions in a module
robert.lummis at gmail.com
Fri Oct 30 23:39:42 CET 2009
I want to move some functions from my "main" program file to a module
file because the main file is getting too big for convenience. The
functions access arrays (lists of lists) that are defined and
initialised in the main file. How do I reference the main file arrays
from statements within the module file?
The overall program solves a game by a recursive method. The arrays
are the game data. Functions in the main file and also functions in
the module need to read and write them. The program works when all the
functions are in the main file but now I want to develop it further
and the presence of a bunch of unchanging housekeeping functions in
the main file makes it cumbersome to read and edit.
With everything in the main file a function like the following works
def functionA (row, col, x):
grid[row][col] = <a value that depends on x and other values in grid>
where grid is initialised outside of any functions (i.e. in the main).
So how do I write that function when I move it to a module file? I
thought I read somewhere that the main routine has the name "__main__"
so I tried:
__main__.grid[row][col] = <...>
but that gives "NameError: name '__main__' is not defined".
I understand that it is best to minimize cross-file references but I
feel it is warranted in this case. Even if you think it isn't good
practice I would like to understand how to do it (or else why it can't
be done). Is there some other way to keep files from getting too big?
More information about the Tutor