重新导入python中的单个函数

Sci*_*ion 4 python import function

在交互模式下使用python导入模块,然后如果模块被更改(错误修复或其他),可以简单地使用reload()命令.

但是,如果我没有导入整个模块并使用'from M import f,g'import语句,该怎么办?有没有办法重新进口g?

(我尝试通过'del g'从参数表中删除该函数并从目录中删除.pyc文件.它没有帮助.当我重新导入函数'从M import g'时,旧的g被加载了).

Nou*_*him 9

When you do a from foo import bar, you are importing the entire module. You are just making a copy of the symbol bar in the current namespace. You are not importing just the function.

The reload function is not totally reliable (e.g. it will not work for compiled C modules). I would recommend that you exit and restart your interpreter.


小智 5

对于from M import f, gwhereM不是官方的 python 模块,请使用:

import sys
import importlib
importlib.reload(sys.modules['M'])
Run Code Online (Sandbox Code Playgroud)

然后,重新导入fg使用:

from M import f,g
Run Code Online (Sandbox Code Playgroud)

如果M是官方的 python 模块,请使用

import importlib
importlib.reload(M)
from M import f,g
Run Code Online (Sandbox Code Playgroud)