Python 中的好坏习惯:在文件中间导入 [英] Good or bad practice in Python: import in the middle of a file

查看:34
本文介绍了Python 中的好坏习惯:在文件中间导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Suppose I have a relatively long module, but need an external module or method only once.

在模块中间导入那个方法或模块是否可以?

Is it considered OK to import that method or module in the middle of the module?

或者 import 应该只在模块的第一部分.

Or should imports only be in the first part of the module.

示例:

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

请证明您的回答是合理的,并添加指向 PEP 的链接s 或相关来源

Please justify your answer and add links to PEPs or relevant sources

推荐答案

PEP8 权威声明:

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

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 就 PEP 8 达成一致.

PEP 8 should be the basis of any "in-house" style guide, since it summarizes what the core Python team has found to be the most effective style, overall (and with individual dissent of course, as on any other language, but consensus and the BDFL agree on PEP 8).

这篇关于Python 中的好坏习惯:在文件中间导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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