Using "external" vars on module load time

M

Marco Aschwanden

Hi

I have a script that looks for modules and tries to load them. After
loading I attach the "server"-API function to it.

module = __import__(module_name, globals(), locals(), [])
module.server = server.server_api

Now, some modules need the "server" functionality on load/init. I tried to
modify the globals():

my_globals = globals().copy()
my_globals['server'] = server.server_api
module = __import__(module_name, my_globals, locals(), [])
module.server = server.server_api

This did not work as intended the module to be imported did not get the
"server" from my_globals. The solution I have, is to add __init_module__()
method that is called after the module was imported:

module = __import__(module_name, globals(), locals(), [])
module.server = server.server_api
if module.__dict__.has_key('__init_module__'):
module.__init_module__()

This is not really satisfying. I would like:

Load a module and hand in already the server_api. How can I achieve this?

Thanks for any suggestions,
Marco
 
P

Peter Otten

Marco said:
Load a module and hand in already the server_api. How can I achieve this?

Using execfile() is the simplest approach:

import imp
import sys

def import_preloaded(name, path=None, variables={}):
if path is None:
file, path, description = imp.find_module(name)
module = imp.new_module(name)
module.__dict__.update(variables)
execfile(path, module.__dict__)
sys.modules[name] = module
return module

if __name__ == "__main__":
demo = import_preloaded("demo", variables=dict(whatever=42))

I think you should consider a class instead of a module, though.

Peter
 
M

Marco Aschwanden

Marvelous that was the solution I was looking for.
I think you should consider a class instead of a module, though.

What I don't get: Why should I consider using a class?

Greetings from sunny Switzerland,
Marco
 
D

Diez B. Roggisch

Marco said:
Marvelous that was the solution I was looking for.


What I don't get: Why should I consider using a class?

Because sharing state in such a way that several functions need to
access some later bound globals cries for a class that gets that very
state passed on instantiation.

Diez
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top