[Tutor] How do you make a module
alan.gauld@bt.com
alan.gauld@bt.com
Wed, 17 Apr 2002 11:38:01 +0100
> I'm stumped about how to handle a namespace issue.
>
> In the __main__ program I open a file for output like this:
>
> DEBUGOUT = open('f:/source/linkextr2/debug_rr.txt', 'w')
>
> and the functions that __main__ calls output logging data to
> it. Now that those functions have been moved to their own
> module (crawler.py), the functions have no idea of DEBUGOUT's
> existence.
from crawler import DEBUGOUT
should make it available. Alternatively set a local variable
to it via the module:
dbgout = crawler.DEBUGOUT
> to pass DEBUGOUT to crawl_site(), but crawl_site calls other functions
> within the same module and those functions also need to
> access the DEBUGOUT file.
That means they are using the name as a global variable which is
bad practice from a purist point of view. Better to have all
functions that use it take it as an argument. However that
may be a big edit job so use the techniques above to fake the
global...
> Is there a way to make DEBUGOUT created in __main__ available
> to the other module (crawler.py)?
Ah, I see, its the other way arround.
OK, In that case modify crawl_site() to take the DEBUGOUT as
an argument and at the begginning set a module level variable
in crawler.py to the log file
Like so:
if __name__ == "__main__":
DBGOUT = open(....)
crawl_site(DBGOUT,....)
And in crawler.py
DEBUGOUT = None # initialise the module level variable
def crawl_site(dbgfile,....):
global DEBUGOUT
DEBUGOUT = dbgfile # now set variable with value from __main__
.....as before....
def crawl_another():
# blah blah
DEBUGOUT.write("OOPS, An error happened\n")
etc etc...
HTH,
Alan g.