python - 从导入的模块重新定义被调用的函数

标签 python

例如,我有 mod1.py:

def foo():
    bar()

def bar():
    print("This is bar in mod1")

还有一个 mod2.py:
from mod1 import *

def bar():
    print("This is bar in mod2")

然后是 mod3.py:
import mod1
import mod2

mod1.foo()
mod2.foo()

运行 mod3.py 后,我得到相同的输出:“这是 mod1 中的栏”,即使我在 mod2.py 中重新定义了它。

据我了解,当我在 mod2 中调用 foo 时,它会在 mod1 中查找它,因为我导入了它并且没有重新定义它。

有没有办法让 foo 在 mod2 而不是 mod1 中寻找 bar?

Ofc 无需将 foo 复制到 mod2 或触摸 mod1 中的 foo 或 bar 并且能够在 mod3 中调用它们,通过它们的命名空间来区分,如 mod3.py 示例。

最佳答案

难度不大,传入bar即可明确地。

仔细阅读该问题后, 是禁区。 mod1.py 不能碰。哦,好吧,还是别说了。

mod1.py

def bar():
    print("This is bar in mod1")

def foo(bar=bar):
    bar()


mod2.py 不变

模组3.py
import mod1
import mod2

mod1.foo()
mod2.foo()
mod2.foo(mod2.bar)

输出:
This is bar in mod1
This is bar in mod1
This is bar in mod2

更新:不接触 mod1 的来源:

Monkeypatching,或多或少。线程安全?可能不是。
import mod1
import mod2

mod1.foo()

ori_bar = mod1.bar

# I think this would be a good place for a context manager rather than 
# finally which needs adjustments to handle exceptions
try:
    mod1.bar = mod2.bar
    mod2.foo()
finally:
    mod1.bar = ori_bar

mod1.foo()

输出:
This is bar in mod1
This is bar in mod2
This is bar in mod1

术语方面,原始 foo执行算不算闭包?因为我相信这种特定行为在 Python 中已经存在了很长时间。

关于python - 从导入的模块重新定义被调用的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60571418/

相关文章:

python - 如何确定numpy数组的概率分布函数是什么?

python - 为什么我需要 DJANGO_SETTINGS_MODULE 集?

python OptionParser.has_option 错误

python - 从一列字符串中提取整数

python - 如何在 Ubuntu 16 上从 python 3 连接到 MySQL 数据库

Python Scrapy XPathSelector

python - 如何解压缩字节数组中的 gzip 数据?

python - 很好地将 .txt 文件转换为 .json 文件

python - 使用 PyPDF2 仅选择 PDF 的第一页

python - 在 OpenShift 上安装 MySQL-python 模块