[GRASS-user] a question on how to split python code in multiple modules

Glynn Clements glynn at gclements.plus.com
Fri Oct 2 23:08:25 EDT 2009


Nikos Alexandris wrote:

> I am pythonising a rather long grass-bash script.
> 
> I try to split it in smaller python modules. Each module starts a
> definition of the main function and ends with the 'if __name__ ==
> "__main__":' trick (e.g. code below).
> 
> * Is this the way to go?

Generally, no.

The '__name__ == "main"' check is used to determine whether a Python
file is being run as a program rather than being imported as a module.

A large program should have a single executable file with the rest
being imported.

You might start by producing a single Python script, then ask for
advice about splitting it up once you have working code.

> The first independent "module" contains a series of variables required
> for the rest of the modules to run. However, I have difficulties to
> understand clearly how to load it so the variables are available to the
> rest of the modules. It loads fine but the actual variables (such as
> literal strings, lists, etc.) are no where to be found. I probably do
> some beginner's mistake here.

The top-level __main__ module is the last place that you should be
defining global variables, as these won't be readily accessible from
imported modules.

Instead, either put the variables in a module (e.g. "core"), and have
the various modules import that, or put them in whichever module uses
them. If module A imports module B, A can reference B's definitions
but B can't (easily) reference A's definitions.

> * How do I instruct Python to keep variables in memory after executing
> the function?

Variables which are written to within a function before they are read
are local by default. If you want to modify a global variable within a
function, use the "global" statement beforehand.

> Also, I've seen in several grass70 python scripts, in the end of the
> main() function and before the _trick_, "sys.exit(0)" calls or "return
> 0" code.
> 
> * What does this actually do? Is this mandatory?

sys.exit() terminates the process. It shouldn't actually be necessary;
reaching the end of the program without error should have the same
effect.

-- 
Glynn Clements <glynn at gclements.plus.com>


More information about the grass-user mailing list