user129975
user129975

Reputation: 3625

How to reload a Python module that was imported in another file?

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

Upvotes: 2

Views: 1062

Answers (1)

Alex Martelli
Alex Martelli

Reputation: 882681

   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).

Upvotes: 3

Related Questions