initializing modules?
Corrado Gioannini
gioco at nekhem.com
Mon Aug 13 13:09:45 EDT 2001
hi all,
i have some general functions that i want to be used within different
modules. those functions are defined when i launch the main script
(they depend on some parameters read from a configfile, whose name is passed
on the command line).
i'd like to put them in a separate module to be imported from the other
modules, but i need to 'initialize' them when i run the main script.
how can i approach this problem in a better way?
here's a simplified version of the problem:
--------main.py----------
t = 'long text read from config file '
def f(s):
return t+s
from modA import classA
a = classA().methodA()
print a
-------------------------
--------modA.py----------
class classA:
def __init__(self):
self.txt = 'plus other things'
def methodA(self):
return 'method A returns %s. hope you like" % f(self.txt)
-------------------------
of course this won't work beacuse f will not be found in modA
i could do something like:
class classA:
def __init__(self,g):
self.f = g['f']
self.txt = 'plus other things'
in modA.py and then call
a = classA(globals()).methodA()
inside main.py. but this is very ugly imho. and i should replicate it for
different functions and lots of classes.
so i thougth that the best thing should be to put the definition of f in a
modF.py, and then put a "from modF import *" line at the beginning of each
module, like modA, which uses it...
if only i could do something like a 'module initialization'.
at this point i realized there was something wrong in my approach :)
(ah, i cannot just read the configfile inside modF, because inside main.py i
do some computation using configfile's parameters before defining the
functions. to do all this just once is my aim.)
thanks for your help.
Corrado.
--
Corrado Gioannini
<gioco at nekhem.com>
"Thought is only a flash between two long nights,
but this flash is everything."
(H. Poincaré)
More information about the Python-list
mailing list