python - 在导入的python源中调用导入(!)python源的函数
问题描述
假设我有一些main.py
def sauce():
print "This is the secret"
from included import magic
magic()
并包含.py
def magic():
sauce()
这应该打印This is the secret但它当然会引发错误。
与通常需要的情况相反。但是有什么秘方可以实现我想要的吗?
解决方案
Python 是词法范围的;sauce
定义中的名称是指(定义magic
的)全局范围内的名称,而不是恰好被调用的位置的范围。included
magic
magic
证明是这样的(而不是建议以这种方式编写代码):
import included
from included import magic
def sauce_implementation():
print "This is the secret"
included.sauce = sauce_implementation # Patch the global scope of included
magic()
更好的选择是magic
接受一个sauce
论点,而不是依赖某人为其未定义的全局引用提供定义。
推荐阅读
- laravel - Laravel 分页 & 获取所有
- python - 如何向函数内部分布和定义的张量流图添加操作?
- botframework - MS Teams 中的布局视图与 Webchat 控制台中的 Azure 门户测试完全不同,我该如何解决?
- c++ - 不能将超过 32 位的 char 移位为 unsigned long long
- javascript - Bootstrap datePicker(仅限月份和年份)不会正确显示
- sql - Pyspark 中的解码替代品
- reactjs - 使用代理时,React 应用程序正在寻找不同位置的静态文件
- typescript - 使用 mockResolvedValueOnce 和 async/await 时抛出 tslint 警告
- r - 标签太长,无法放入条形区域
- sql - 插入第一个表后如何使用一些相同的信息自动更新第二个表