lordofcode wrote:
> Hi All
> 
> Not an expert in Python, so sorry if this sounds like a silly
> question.
> I went through other few threads in the mailing list but they are not
> helping me much.
> I have run into a problem related to dynamically loading and unloading
> a module.
> I need to dynamically load a module and unload it and load another
> module.
> 
> For example I have many files(All files in Python are modules right?)
> like mobile_1.py ,mobile_2.py, mobile_3.py  etc.. in my project folder
> which contains classes and methods with same name but different
> functionality.(am afraid I cannot change this structure as these files
> are generated randomly by the user)
> 
> So initially when my program starts I have to load a default module. I
> do this as follows:
> ##############################
>>> MODULE_name = "mobile_1"
>>> exec "from "+MODULE_name+" import *"
> ##############################
> And use the methods defined in "mobile_1.py" file
> 
> Now as the application continues , I may have to use the methods
> defined in "mobile_2.py" or "mobile_3.py" etc instead of the
> previously loaded module,which I incorrectly try to do as below:
> ####################
>>> MODULE_name = "mobile_2"
>>> exec "from "+MODULE_name+" import *"
> #####################
> The above import does not have any impact and the methods called from
> my application still pertain to mobile_1.py as its still in the
> current namespace(?).
> I tried below code with del(), reload() etc but could not figure it
> out.
> ###Code to unload a dll####
>>> del sys.modules[MODULE_name]    #==> does not delete the reference in 
>>> namespace
> 
> 
> 1)How do I unload a module dynamically and completely remove the
> references in the module so a new module with same name references can
> be loaded?
> 2)Are there any alternative way to do the above requirement?
> Currently I am working around by restarting the whole initial setup
> for each new module which is unnecessary waste.Can I avoid this
> "reset"?
> 
I'd argue that you don't want to unload the old code before loading the
new module, and that what you really need is an understanding that if
mod1 and mod2 both define a function called f then you can perfectly
happily reference the two functions as

  mod1.f

and

  mod2.f

Indeed, if x is some object that needs processing by functions f, g and
h from module mod1 then it's perfectly valid to write

  mod = mod1
  result = mod.f(mod.g(mod.h(x)))

for example. So you can write code that uses the appropriate module for
each input.

It's possible, of course, that I am misunderstanding your requirements,
but I hope that helps.

regards
 Steve
-- 
Steve Holden           +1 571 484 6266   +1 800 494 3119
PyCon is coming! Atlanta, Feb 2010  http://us.pycon.org/
Holden Web LLC                 http://www.holdenweb.com/
UPCOMING EVENTS:        http://holdenweb.eventbrite.com/

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to