首页 > 解决方案 > 在导入的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

解决方案


Python 是词法范围的;sauce定义中的名称是指(定义magic的)全局范围内的名称,而不是恰好被调用的位置的范围。includedmagicmagic

证明是这样的(而不是建议以这种方式编写代码):

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论点,而不是依赖某人为其未定义的全局引用提供定义。


推荐阅读