Python中的好与坏实践:在fi中间导入

2024-09-25 08:26:21 发布

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

假设我有一个相对较长的模块,但只需要一次外部模块或方法。

在模块中间导入该方法或模块是否被认为是可以的?

或者imports应该只在模块的第一部分。

示例:

import string, pythis, pythat
...
...
...
...
def func():
     blah
     blah 
     blah
     from pysomething import foo
     foo()
     etc
     etc 
     etc
...
...
...

请证明您的答案正确,并添加指向PEPs或相关来源的链接


Tags: 模块方法fromimport示例stringfoodef
3条回答

其他人都已经提到了pep,但也要注意在关键代码中间不要有import语句。至少在Python2.6下,当函数有import语句时,还需要几个字节码指令。

>>> def f():
    from time import time
    print time()

>>> dis.dis(f)
  2           0 LOAD_CONST               1 (-1)
              3 LOAD_CONST               2 (('time',))
              6 IMPORT_NAME              0 (time)
              9 IMPORT_FROM              0 (time)
             12 STORE_FAST               0 (time)
             15 POP_TOP             

  3          16 LOAD_FAST                0 (time)
             19 CALL_FUNCTION            0
             22 PRINT_ITEM          
             23 PRINT_NEWLINE       
             24 LOAD_CONST               0 (None)
             27 RETURN_VALUE

>>> def g():
    print time()

>>> dis.dis(g)
  2           0 LOAD_GLOBAL              0 (time)
              3 CALL_FUNCTION            0
              6 PRINT_ITEM          
              7 PRINT_NEWLINE       
              8 LOAD_CONST               0 (None)
             11 RETURN_VALUE  

2001年在Python邮件列表中详细讨论了这个主题:

https://mail.python.org/pipermail/python-list/2001-July/071567.html

以下是该主题中讨论的一些原因。从Peter Hansen,这里有三个不让导入全部位于文件顶部的原因:

Possible reasons to import in a function:

  1. Readability: if the import is needed in only one function and that's very unlikely ever to change, it might be clearer and cleaner to put it there only.

  2. Startup time: if you don't have the import outside of the function definitions, it will not execute when your module is first imported by another, but only when one of the functions is called. This delays the overhead of the import (or avoids it if the functions might never be called).

  3. There is always one more reason than the ones we've thought of until now.

只是范罗森插嘴说了第四句:

  1. Overhead: if the module imports a lot of modules, and there's a good chance only a few will actually be used. This is similar to the "Startup time" reason, but goes a little further. If a script using your module only uses a small subset of the functionality it can save quite some time, especially if the imports that can be avoided also import a lot of modules.

第五个建议是,本地进口是避免循环进口问题的一种方法。

请随意阅读这篇文章,以便进行全面的讨论。

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.

PEP 8应该是任何“内部”风格指南的基础,因为它总结了核心Python团队发现的最有效的总体风格(当然,和其他语言一样,也有个人的不同意见,但是共识和BDFL同意pep8)。

相关问题 更多 >