开发者

Best way to handle reload-ing of objects, not modules

开发者 https://www.devze.com 2023-01-08 20:10 出处:网络
I\'m doing a lot of development in IPython where In[3]: from mystuff import MyObject and then I make lots of changes in mystuff.py. In order to update the namespace, I have to do

I'm doing a lot of development in IPython where

In[3]: from mystuff import MyObject

and then I make lots of changes in mystuff.py. In order to update the namespace, I have to do

In[4]: reload(mystuff)
In[5]: from mystuff import MyObject

Is there a better way to do this? Note that I cannot import MyObject by referencing mystuff directly as with

In[6]: import mystuff
In[7]: mystuff.MyObject

since that's not how it works in the code. Even better would be开发者_开发知识库 to have IPython automatically do this when I write the file (but that's probably a question for another time).

Any help appreciated.


You can use the deep_reload feature from IPython to do this.

http://ipython.scipy.org/doc/manual/html/interactive/reference.html?highlight=dreload

If you run ipython with the -deep_reload parameter to replace the normal reload() method.

And if that does not do what you want, it would be possible to write a script to replace all the imported modules in the scope automatically. Fairly hacky though, but it should work ;)

I've just found the ipy_autoreload module. Perhaps that can help you a bit. I'm not yet sure how it works but this should work according to the docs:

import ipy_autoreload
%autoreload 1


If the object is a class or a function, you can use its __module__ attribute to determine which module to reload:

def reload_for(obj):
    module = reload(__import__(obj.__module__, fromlist=True))
    return getattr(module, obj.__name__)

MyClass = reload_for(MyClass)


Try using the %run magic to import the contents of the file you are editing. When you use this to import objects from a file it updates those objects every time you %run it. This way it's not autoreloading every time you carriage return.

0

精彩评论

暂无评论...
验证码 换一张
取 消