Is it possible to import to the global scope from inside a function (Python)?

本秂侑毒 提交于 2019-12-01 16:12:07

How about something like globals()["os"] = __import__("os")?

I guess this could be wrapped in a generic function if you wanted since the module name is a string.

Seeing your new comments, I want to emphasize that this sounds unnecessary. You're actually modifying the script more by importing within a function than by importing at the top of the script in the normal way. Still, in the spirit of answering the question asked, I'm leaving my previous answer.


I'm honestly not certain this is the correct way to do this, but a quick check confirms that if you declare the module name as global within the function before importing, it is imported into the global namespace.

>>> 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'>

Don't do this unless you really have to -- and then write it in big red letters, so to speak.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!