[Tutor] Accessing variables in main from functions in a module

Kent Johnson kent37 at tds.net
Sat Oct 31 00:59:40 CET 2009


On Fri, Oct 30, 2009 at 6:39 PM, Robert Lummis <robert.lummis at gmail.com> wrote:
> 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?

A couple of solutions:
- Put the arrays into some kind of structure that you can pass as an
argument. The structure could be a list, dict or custom class.
- Create a class (or possibly more than one class) to hold both the
data and the functions that operate on it.

> With everything in the main file a function like the following works
> as expected:
>
> 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

That might make a good method of a grid class. Then it would become
something like
def functionA(self, row, col, x):
  self.grid[row][col] = ...

> 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".

You can
  import __main__
and the above will work but that is *not* the best solution.

> I understand that it is best to minimize cross-file references but I
> feel it is warranted in this case.

Cross-file references are not bad by themselves but circular
references (module A uses module B and B uses A) are a bad idea.

> 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?

Yes. Object-oriented design is the most common way of dealing with
this. Think about decomposing your code into cooperating objects.

Kent


More information about the Tutor mailing list