[Tutor] function vs module

Magnus Lycka magnus@thinkware.se
Fri, 06 Sep 2002 12:35:55 +0200


At 22:22 2002-09-05 -0400, Chris Kassopulo wrote:
>Greetings,
>
>I'm working on some scripts that output stuff to the screen.  For
>example, the attached script, list_modules.py formats and outputs
>a list of builtin modules.  When I convert it to ListModules.py
>to use a module, ListColumns.py I get:
...
>NameError: global name 'ReturnFlag' is not defined
>
>ReturnFlag = 0 at the beginning of ListColumns gets around the
>error, but I can't set it there.  The intention is that scripts
>that use ListColumns will set the flag and ListColumns just reads
>it.  I thought that making ReturnFlag global in ListColumns would
>work, but it doesn't.
>
>Could someone shed some light on this please.

Sure. The "global scope" refers to the module. An imported
module should not know the context where it's used. If we
had modules changing their behaviour due to variables
outside of their own scope, it would both be much more
difficult to both write and use modules.

Thus 'import' in python is not like the preprocessor directive
"#include" in C, where source-files are copied into your code
and your own scope before compiling.

Import is also a lot less problematic than #include...

We might assume that this difference is one of the reasons why
people use a linker in C instead of just using #include to compile
all source code at once...

There are several options here.

You can set a variable in the global scope of your module
from an importing module.

import ListColumns
ListColumns.ReturnFlag = 1
ListColumns.ListColumns(...)

You can obviously send "ReturnFlag" as a parameter to
your function call.

You can use a class with a method instead of a module
with a function. Then you just set an approriate value
to ReturnFlag at initialization, or at any other point
before calling the method. But if you only need one
instance of this class, the first approach with the
module global variable is enough.



-- 
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/  mailto:magnus@thinkware.se