在交互时重新导入python中的模块 [英] Reimport a module in python while interactive

查看:34
本文介绍了在交互时重新导入python中的模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道可以做到,但我不记得怎么做.

I know it can be done, but I never remember how.

如何在python中重新导入模块?场景如下:我以交互方式导入一个模块并修改它,但随后我遇到了错误.我修复了 .py 文件中的错误,然后我想在不退出 python 的情况下重新导入固定模块.我该怎么做?

How can you reimport a module in python? The scenario is as follows: I import a module interactively and tinker with it, but then I face an error. I fix the error in the .py file and then I want to reimport the fixed module without quitting python. How can I do it ?

推荐答案

这应该有效(对于 Python <3.4):

reload(my.module)

来自 Python 文档

重新加载之前导入的模块.参数必须是一个模块对象,所以它之前必须成功导入.如果您使用外部编辑器编辑了模块源文件并希望在不离开 Python 解释器的情况下试用新版本,这将非常有用.

Reload a previously imported module. The argument must be a module object, so it must have been successfully imported before. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter.

如果运行 Python 3.4 及更高版本,执行 import importlib,然后执行 importlib.reload(nameOfModule).

不要忘记使用这种方法的注意事项:

Don't forget the caveats of using this method:

  • 当一个模块被重新加载时,它的字典(包含模块的全局变量)被保留.名称的重定义会覆盖旧的定义,所以这通常不是问题,但如果模块的新版本没有定义旧版本定义的名称,旧的定义不会被删除.

  • When a module is reloaded, its dictionary (containing the module’s global variables) is retained. Redefinitions of names will override the old definitions, so this is generally not a problem, but if the new version of a module does not define a name that was defined by the old version, the old definition is not removed.

如果一个模块使用 from ... import ... 从另一个模块导入对象,则为另一个模块调用 reload() 不会重新定义从它导入的对象 — 一种解决方法是重新执行 from 语句,另一种方法是使用 import 和限定名称 (module.*name*) 代替.

If a module imports objects from another module using from ... import ..., calling reload() for the other module does not redefine the objects imported from it — one way around this is to re-execute the from statement, another is to use import and qualified names (module.*name*) instead.

如果一个模块实例化了一个类的实例,重新加载定义该类的模块不会影响实例的方法定义——它们继续使用旧的类定义.派生类也是如此.

If a module instantiates instances of a class, reloading the module that defines the class does not affect the method definitions of the instances — they continue to use the old class definition. The same is true for derived classes.

这篇关于在交互时重新导入python中的模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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