import 语句是否应该始终位于模块的顶部? [英] Should import statements always be at the top of a module?

查看:30
本文介绍了import 语句是否应该始终位于模块的顶部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PEP 8 声明:

导入总是放在文件的顶部,就在任何模块注释和文档字符串之后,在模块全局变量和常量之前.

Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.

但是,如果我导入的类/方法/函数仅在极少数情况下使用,那么在需要时进行导入肯定会更有效率吗?

However if the class/method/function that I am importing is only used in rare cases, surely it is more efficient to do the import when it is needed?

这不是:

class SomeClass(object):

    def not_often_called(self)
        from datetime import datetime
        self.datetime = datetime.now()

比这更有效?

from datetime import datetime

class SomeClass(object):

    def not_often_called(self)
        self.datetime = datetime.now()

推荐答案

模块导入速度很快,但不是即时的.这意味着:

Module importing is quite fast, but not instant. This means that:

  • 将导入放在模块的顶部是可以的,因为这是一个只需支付一次的微不足道的成本.
  • 将导入放在一个函数中会导致对该函数的调用需要更长的时间.

因此,如果您关心效率,请将导入放在首位.仅当您的分析显示有帮助时才将它们移至函数中(您确实 分析了哪些地方最能提高性能,对吗??)

So if you care about efficiency, put the imports at the top. Only move them into a function if your profiling shows that would help (you did profile to see where best to improve performance, right??)

我所见过的执行延迟导入的最佳原因是:

The best reasons I've seen to perform lazy imports are:

  • 可选的库支持.如果您的代码有多个使用不同库的路径,请不要在未安装可选库的情况下中断.
  • 在插件的 __init__.py 中,它可能被导入但实际上并未使用.例如 Bazaar 插件,它使用 bzrlib 的延迟加载框架.
  • Optional library support. If your code has multiple paths that use different libraries, don't break if an optional library is not installed.
  • In the __init__.py of a plugin, which might be imported but not actually used. Examples are Bazaar plugins, which use bzrlib's lazy-loading framework.

这篇关于import 语句是否应该始终位于模块的顶部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆