Python:通过函数导入到main namesp

2024-05-13 12:19:28 发布

您现在位置:Python中文网/ 问答频道 /正文

(重要提示:请参阅下面的更新。)

我正在尝试编写一个函数,import_something,它对某些模块很重要。(对于这个问题,哪一个并不重要)问题是,我希望那些模块在调用函数的级别导入。例如:

import_something() # Let's say this imports my_module
my_module.do_stuff() #

这可能吗?在

更新:

对不起,我原来的措辞和例子是误导。我会尽力解释我的整个问题。我有一个包,里面有一些模块和包。在它的__init__.py中,我想导入所有模块和包。因此,在程序的其他地方,我导入整个包,并迭代它导入的模块/包。在

(为什么?这个包名为crunchers,其中定义了各种各样的cruncher,比如CruncherThreadCruncherProcess,将来可能是{}。我希望crunchers包自动包含所有放置在其中的crunchers,因此在程序的后面,当我使用crunchers时,我知道它可以确切地知道我定义了哪些cruncher。)

我知道,如果我完全避免使用函数,并在主级别上使用for循环之类的方法进行所有导入,我就可以解决这个问题。但它很难看,我想看看我能不能避免它。在

如果还有什么不清楚的地方,请在评论中询问。在


Tags: 模块函数import程序定义my地方请参阅
3条回答

你在找这样的东西吗?在

def my_import(*names):
    for name in names:
        sys._getframe(1).f_locals[name] = __import__(name)

你可以这样称呼它:

^{pr2}$

或者

namelist = ["os", "re"]
my_import(*namelist)

函数可以将某些内容返回到调用它们的位置。它叫做它们的返回值:p

def import_something():
    # decide what to import
    # ...
    mod = __import__( something )
    return mod
my_module = import_something()
my_module.do_stuff()

风格不错,没有麻烦。在

关于您的更新,我认为向您添加这样的内容__init__.py可以满足您的需要:

^{pr2}$

其他地方:

import crunchers
crunchers.installed # all names
crunchers.cruncherA # actual module object, but you can't use it since you don't know the name when you write the code
# turns out the be pretty much the same as the first solution :p
mycruncher = getattr(crunchers, crunchers.installed[0])  

您可以在CPython中对父框架执行monkey操作,将模块安装到该框架的局部变量中(并且只安装该框架)。它的缺点是a)这确实非常老套,b)sys.\u getframe()不能保证存在于其他python实现中。在

def importer():
  f = sys._getframe(1) # Get the parent frame
  f.f_locals["some_name"] = __import__(module_name, f.f_globals, f.f_locals)

您仍然需要将模块安装到f_locals中,因为import实际上不会为您完成这项工作—您只需为适当的上下文提供父框架局部变量和全局变量。在

然后在您的调用函数中,您可以:

^{pr2}$

相关问题 更多 >