Python“导入”范围 [英] Python "import" scope

查看:113
本文介绍了Python“导入”范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理为我自动生成的一些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的错误。但是酒吧正在进口foo&嘘。不应该自动嘘声?

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&嘘。
不应该自动为
提供嘘声?

But bar is importing both foo & boo. Shouldn't foo be automatically available to boo?

不,不应该:<$ c与任何其他绑定名称的方式一样,$ c> 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是自动生成的
me&我想避免将导入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

有一个非常糟糕的黑客 - 我不想要和它一起生活(我更倾向于把我的精力投入到完全破坏的代码生成器中,使得 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 的代码生成器中可怕的,明显的错误。 修复该错误,以便尽快退出此hack!

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆