![](/img/trans.png)
[英]python - why is it possible to use a variable in a function that is declared in the main scope and is not global
[英]Is it possible to import to the global scope from inside a function (Python)?
我正在尝试从 function 内部导入一个模块,并让它可用于我的整个文件,就像我在任何函数之外和所有其他代码之前导入一样。 它在 function 中的原因是因为我对脚本的结构没有太多控制权。 如果不求助于黑客 __builtin__ 或在我的代码周围传递我需要的东西,这是否可能?
像globals()["os"] = __import__("os")?
我想如果你愿意的话,这可以包装在一个通用的 function 中,因为模块名称是一个字符串。
看到你的新评论,我想强调这听起来没有必要。 您实际上是通过在function中导入来修改脚本,而不是通过以正常方式在脚本顶部导入。 尽管如此,本着回答所提问题的精神,我将留下我之前的答案。
老实说,我不确定这是执行此操作的正确方法,但快速检查确认,如果您在导入之前在 function 中将模块名称声明为global
名称,则会将其导入全局命名空间。
>>> def import_re():
... global re
... import re
...
>>> re
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 're' is not defined
>>> import_re()
>>> re
<module 're' from '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/re.pyc'>
除非你真的必须这样做,否则不要这样做——然后用大红字写,可以这么说。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.