重装模块已导入到另一个模块 [英] reloading module which has been imported to another module

查看:143
本文介绍了重装模块已导入到另一个模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们面对现实,改变它后重新加载python代码的整个业务是一团糟。我想了一下,在解释器上调用 import< module> 比从< module>中调用更好。 import< class / function> ,因为那时我可以调用 reload(module)来获取更新的代码。

Let's face it, the whole business of reloading python code after changing it is a mess. I figured out awhile back that calling import <module> at the interpreter is better than from <module> import <class/function>, because then I can call reload(module) to get updated code.

但我现在有更复杂的问题。所以我有这个文件,module1.py,并在顶部说:

But I have more complicated issues now. So I have this file, module1.py, and at the top it says:

from module2 import <class1>, <function1>, etc.

然后我去改变module2中的代码。事实证明,调用 reload(module1)将不会重新加载module2中更改的代码,即使module2的代码是在module1的顶部导入的。有没有办法在不重新启动翻译的情况下重新加载所有内容?

And then I go and change code inside module2. Turns out that calling reload(module1) will not reload the code changed in module2, even though code from module2 is imported at the top of module1. Is there any way to reload everything without restarting the interpreter?

在任何人谈到我的关于风格的案例之前,我只会说:

Before anyone gets on my case about style, I'll just say that:


  1. 我只从解释器调用 reload ,从不在活动代码中。这个问题涉及我在测试新代码的时候。

  2. 我从不打电话给< module> import * ,我知道这会破坏可读性

  1. I only call reload from the interpreter, never in active code. This question concerns when I'm testing new code.
  2. I never call from <module> import *, I know that destroys readability


推荐答案

有一个看看IPython。它具有自动重载扩展,可在解释器会话期间自动重新加载模块在调用函数之前。我引用着陆页中的示例:

Have a look into IPython. It has the autoreload extension that automatically reloads modules during the interpreter session before calling functions within. I cite the example from the landing page:

In [1]: %load_ext autoreload

In [2]: %autoreload 2

In [3]: from foo import some_function

In [4]: some_function()
Out[4]: 42

In [5]: # open foo.py in an editor and change some_function to return 43

In [6]: some_function()
Out[6]: 43

这篇关于重装模块已导入到另一个模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆