English 中文(简体)
使用 import 进行动态舱装货有什么影响吗?
原标题:Any impact of doing dynamic module loading using __import__?

在我的申请中,我有:

...
folder_a/
    __init__.py
    a.py
    folder_b/
        __init__.py
        b1.py 
        b2.py
        ...

并且我需要将 folder_b 模块动态地装入 a.py , 以变量为基础,例如 module_ from_b 。 要做到这一点,请在 a.py 中写到:

mymodule = __import__("folder_b.%s" % module_from_b, globals(), locals(), fromlist=["*"])

既然这将会生活在一个循环中,即被称作多次,我想知道它是否会对性能或其它方面有任何影响?如果是这样,在保持动态舱装货能力的同时,是否有办法减轻影响?

最佳回答

我从未设定过基准,但我认为进口(动态的还是静态的)一个模块以前被输入运行中的口译员(即使是完全不相关的代码 ), 应该非常便宜。 它真正需要做的应该是一些(成功的)字典搜索。

导入新模块当然会运行模块中的所有代码, 加上要查找的文件系统搜索 。

所以,如果您反复从一组相对较小的模块中导入一个动态选择模块,那么您就不应该有太多问题,只要您能够容忍延迟,每个特定模块第一次使用(延迟的多少取决于您的模块);稍稍过一段时间后,您重新导入的几乎所有模块都将被导入,因此,的电话将变得便宜。

您可能考虑的替代设计 : 如果您需要的全部模块集在前方( 静态或动态) 是可以了解的, 您可以在循环“ 暖化” Python 导入模块集之前预先导入它们 。 如果 b 中没有很多不使用的模块, 您可以在 b s < code_ init_. py 中导入所有模块 。

这样在启动时进口延迟就会在启动时失控, 您可以在 b 套件上使用 < code> getattr 来动态地获取您的模块, 而不是需要使用 < codeimport/ code > 。 如果您重新装入如此多的模块, 以至于您 < em> 想要 将导入成本分散在循环中, 或者如果您有许多模块, 但只需要相对较少的模块, 并且很难提前知道哪些模块 。

还有一个可能更好的方法,如果在您重新识别要导入的模块的位置,您可以选择某个常数字符串(而不是从配置文件或用户输入中读取的东西),那么这个方法就会有效。与其将模块的名称从模块的名称转到最终要导入到别处,为什么不导入模块然后和那里,然后将“坚固的”模块本身 输入到其它处最终使用?作为一个编造的例子,因为我不知道你在做什么,而不是:

for module_name in [ b1 ,  b2 ,  b3 ,  b4 ]:
    function_using_module(module_name)

def function_using_module(module_name):
    module = __import__(...)
    ...

你可以做到这一点:

from folder_b import b1, b2, b3, b4

for module in [b1, b2, b3, b4]:
    function_using_module(module)

def function_using_module(module):
    ...

模块是对象,就像其他任何东西一样,所以您可以将其存储在列表或对象中,或者您正在用名称做什么。直接通过模块通常比作为模块的代名词传到周围然后导入更干净。

问题回答

在字节码中,绝对没有区别的进口说明被作为调用的调用来表示。以下两个调用是"http://docs.python.org/library/forms.html_import_" rel=“nofollow” 等同

import spam
spam = __import__( spam , globals(), locals(), [], -1)

如果您可能要做很多次, 为什么不只检查该模块是否已经存在于您当前命名空间中, 如果不是只导入的话 。

if  module_I_need_to_load  not in dir():
    from b import module_I_need_to_load
# Or you can look in vars() instead if you have a
# hell of a lot of modules loaded up as dir is a 
# list and vars is a dictionary which will have a
# faster lookup time when you start having a lot of
# elements
if  module_I_need_to_load  not in vars():
    from b import module_I_need_to_load




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签