Python“导入"范围 [英] Python "import" scope
问题描述
我正在处理一些自动为我生成的 Python 代码.我想避免手动编辑这些 python 文件 &因此这个问题/问题:
I am dealing with some python code automatically generated for me. I want to avoid manually editing these python files & hence this question/issue:
foo.py:
def foo():
print "foo"
boo.py:
def boo():
foo.foo() # <-- global name 'foo' not defined
print "boo"
bar.py:
import foo
import boo
def bar():
boo.boo()
print "bar"
执行:
python.exe bar.py
python.exe bar.py
给出一个错误,boo
没有找到 foo
.但是 bar 正在导入 foo
&嘘
.foo
不应该自动对 boo
可用吗?
gives an error that boo
did not find foo
. But bar is importing both foo
& boo
. Shouldn't foo
be automatically available to boo
?
有没有办法做到这一点?如上所述 boo.py 是为我自动生成的 &我想避免将 import foo 添加到 boo.py.
Is there a way to do so? As said boo.py is automatically generated for me & I want to avoid adding import foo to boo.py.
谢谢.
推荐答案
但是 bar 正在导入 foo &嘘.不应该 foo 是自动的可以嘘吗?
But bar is importing both foo & boo. Shouldn't foo be automatically available to boo?
不,不应该:import
,就像绑定名称的任何其他方式一样,将该名称绑定在单个特定范围内,而不是在您可能想要的所有范围内".
No it shouldn't: import
, like any other way to bind a name, binds that name in a single, specific scope, not "in all scopes you could ever possibly want it in".
有没有办法做到这一点?正如所说boo.py 是自动生成的我&我想避免添加 import foo到 boo.py
Is there a way to do so? As said boo.py is automatically generated for me & I want to avoid adding import foo to boo.py
有一个非常糟糕的 hack —— 我不想忍受它(我宁愿把我的精力放在让 boo.py
修复的完全损坏的代码生成器上——如果它有这么大的错误,比如缺少关键的必需导入,它还有什么可怕的东西?!),但是,嘿,这不是我的葬礼......;-)
There's one very bad hack -- I wouldn't want to live with it (I'd much rather pour my energy into getting that totally broken code generator that makes boo.py
fixed -- if it has such a huge bug as missing a crucial needed import, what other horrors can it have in store?!), but, hey, it ain't my funeral...;-)
让 bar.py
开始...:
import foo
import boo
import __builtin__
__builtin__.foo = foo
这样你就让标识符 foo
成为了一个假的、人工的内置名称"(唯一一种在每个范围内都可用的名称,除非被隐藏通过名称的其他干预绑定在更近的范围内)引用模块 foo
.
This way you've made identifier foo
a "fake, artificial built-in name" (the only kind of name that is available from every scope, unless shadowed by other intervening bindings of the name
in closer scopes) referring to the module foo
.
不推荐的程序,只是一个临时解决方法,用于构建 boo.py
的代码生成器中可怕的、明显的错误.修复该错误,以便您尽快停用此黑客!
NOT recommended procedure, just a temporary workaround for the horrible, glaring bug in the code generator that builds boo.py
. Get that bug fixed so you can retire this hack ASAP!
这篇关于Python“导入"范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!