简体   繁体   English

导入已安装软件包的最佳做法

[英]Best practices for imports for installed package

Imagine I have a package "foolibrary" that is installed via setup.py, and I'm the primary developer. 想象我有一个通过setup.py安装的“ foolibrary”软件包,而我是主要开发人员。 Which is the preferred means of calling imports inside the package? 调用包内部导入的首选方法是什么? Imagine foolibrary has two modules (a.py, b.py) and I need to access them in c.py: 想象一下foolibrary有两个模块(a.py,b.py),我需要在c.py中访问它们:

  • foolibrary foolibrary
    • a.py a.py
    • b.py b.py
    • c.py c.py

In c.py, what is the preferred way to import these and why? 在c.py中,导入这些文件的首选方式是什么?为什么?

from a import blah

vs VS

from foolibrary.a import blah

vs VS

from .a import blah

I've seen all three and generally use the foolibrary.a import style, but mostly out of habit. 我已经看过所有这三种方法,并且通常使用foolibrary.a import样式,但大多出于习惯。

The relative import syntax, from .a import blah , is the modern way to do things. 相对进口的语法, from .a import blah ,就是做事情现代生活方式。 See PEP 328, https://www.python.org/dev/peps/pep-0328/ , as to why it's superior to the alternatives. 请参阅PEP 328, https://www.python.org/dev/peps/pep-0328/ ,以了解它为何优于其他方法。 (Though admittedly PEP 8 prefers absolute exports, it also allows within-package relative imports as an acceptable alternative). (尽管可以肯定的是,PEP 8倾向于绝对出口,但它也允许包装内相对进口作为可接受的替代方案)。

Personally, BTW, I always ever import only modules , not "stuff" (functions, classes, whatever) from inside a module. 顺便说一句,顺便说一句,我总是从模块内部只导入模块 ,而不导入“东西”(函数,类等)。

But, this is a style constraint that is far from universal (it is , however, part of https://google-styleguide.googlecode.com/svn/trunk/pyguide.html -- and having been at Google 10 years now and helped shape parts of its Python practices and style, I'm understandably biased in favor of that style:-). 但是,这是一个样式约束,远非普遍适用(但是,它 https://google-styleguide.googlecode.com/svn/trunk/pyguide.html的一部分,并且在Google已有10年了,帮助塑造了部分Python的实践和风格,我偏爱于这种风格:-)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM