1

如果始终不需要导入模块,那么导入模块的最佳方法是什么?

我应该在没有条件的情况下导入文件头部的模块还是应该在有条件的情况下导入它?

导入会减慢应用程序的导入速度吗?

例如:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from app.settings import CONDITION
from foo.bar import myClass

if CONDITION:
    # ... do some action with myClass

或者:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from app.settings import CONDITION

if CONDITION:
    from foo.bar import myClass
    # ... do some action with myClass
4

3 回答 3

3

根据PEP 8,您应该将所有 import 语句放在文件的顶部,我同意这一点,即使您只打算在函数中使用它一次。

如果您的导入语句分散在您的代码中,您的代码可能会有点不可读。

至于导入是否会减慢您的脚本速度:可能。但并不是你真正应该担心的大量数字。

于 2013-08-14T07:40:57.710 回答
1

以导入为开头,无论导入需要多少毫秒,都将在程序启动期间进行。它比在某个条件处于活动状态时让程序停止导入要好。

此外,在顶部导入可以生成干净的代码。

于 2013-08-14T07:51:18.640 回答
1

Your second way of importing is probably better if you only occasionally need the module. Especially if the module does some heavy initialization works.

What import does is calling the builtin function __import__(name), see details.

if True:
    import os

is equivalent to:

if True:
    os = __import__('os')

And the best part is that the result of __import__ is cached, so you don't need to worry that by calling it multiple times you would end up parsing the module multiple times.

EDIT: The other answers do have good points, that it is cleaner to have it on top and if the condition is ever evaluated to True, you end up paying the price sooner or later.

I guess it depends on your specific use case too. For example, often times we want to choose one of the implementations of a particular module, we do:

try:
    import simplejson as json
except ImportError:
    import json
于 2013-08-14T07:52:26.190 回答