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

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

问题描述

PEP 08 状态:

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

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.

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

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