How to reload a Python module that was imported in

2019-02-19 18:01发布

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

1条回答
成全新的幸福
2楼-- · 2019-02-19 18:46
   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).

查看更多
登录 后发表回答