views:

228

answers:

1

I am trying to learn how Python reloads modules, but have hit a roadblock. Let's say I have:

dir1\file1.py:

from dir2.file2 import ClassOne
myObject = ClassOne()

dir1\dir2\file2.py:

class ClassOne():
   def reload_module():
       reload(file2)

The reload call fails to find module "file2".

My question is, how do I do this properly, without having to keep everything in one file?

A related question: When the reload does work, will myObject use the new code?

thank you

+3  A: 
   def reload_module():
       import file2
       reload(file2)

However, this will not per se change the type of objects you've instantiated from classes held in the previous version of file2. The Python Cookbook 2nd edition has a recipe on how to accomplish such feats, and it's far too long and complex in both code and discussion to reproduce here (I believe you can read it on google book search, or failing that the original "raw" version [before all the enhancements we did to it], at least, should still be on the activestate cookbook online site).

Alex Martelli
reload needs as its argument a module object; import binds that module object into the current naming scope. Essentially a module file2 containing this code is able to "refresh itself in memory" on request (if the source was changed), net of the issue with objects instantiated with classes from previous versions, which I've mentioned in my answer.
Alex Martelli
Sorry, I had just deleted my question (after it became clear to me). I essentially asked what the point of this importing twice in a row (which it really isn't) would be.
balpha
Thanks Alex. I tried this and it works, insofar as it doesn't throw any errors. I still need to reload those objects somehow. I noticed you wrote that book. Cool...!
Co-edited it (with my wife in the 2nd ed), yes; the original recipe I mention was from Michael Hudson, if I recall correctly, but Anna and I helped enhance most recipes quite substantially (and not all authors put the enhancements back into the online site).
Alex Martelli
(BTW, if this answer helps, what about accepting it? if you need to update code within objects you should probably open another question anyway, as it's quite a different issue).
Alex Martelli
Ok I accepted. Took a moment to realize the checkmark button is what I had to click on! lol. If you are interested what I am trying to achieve with Python please take a look here, its opensource: https://launchpad.net/bloom
Interesting project -- gonna look for your next question and see if I can help.
Alex Martelli