简体   繁体   English

导入和名称绑定最佳实践

[英]Imports and name bindings best practice

This is closely related to: Importing modules in Python - best practice , but the following case is not really discussed in details.这与:在 Python 中导入模块 - 最佳实践密切相关,但并未真正详细讨论以下情况。

If we have a module coordinates that defines one class Coordinates and several utility function to work with the Coordinates type.如果我们有一个模块coordinates ,它定义了一个类Coordinates和几个实用函数来处理Coordinates类型。 What is the recommended way to do the following two things:做以下两件事的推荐方法是什么:

  1. Import the complete coordinates module导入完整的coordinates模块
  2. While binding Coordinates to coordinates.Coordinates虽然结合Coordinatescoordinates.Coordinates

The two options I see for now:我现在看到的两个选项:

import coordinates
from coordinates import Coordinates

But that seems a bit odd, on the other hand the other solution I see doesn't seem very clean either:但这似乎有点奇怪,另一方面,我看到的另一个解决方案似乎也不是很干净:

import coordinates 
Coordinates = coordinates.Coordinates

Which one of this two is the most commonly used or the prefered way of doing this?这两个中哪一个是最常用的或首选的方法? Or maybe both of these shouldn't be used, in which case what would be a better solution?或者也许这两个都不应该使用,在这种情况下什么是更好的解决方案?

Another option I'm considering but that I would prefer to avoid is one proposed in the referenced question: import coordinates as crd and then simply use crd.Coordinates instead of Coordinates .我正在考虑但我更愿意避免的另一个选项是在引用的问题中提出的一个选项: import coordinates as crd ,然后简单地使用crd.Coordinates而不是Coordinates The reason why I want to avoid this is because it would make my code less readable, in particular when I use a function from the coordinates module.我想避免这种情况的原因是它会使我的代码可读性降低,特别是当我使用coordinates模块中的函数时。 To this alternative I would probably prefer to simply call coordinates.Coordinates even if that looks redundant.对于这个替代方案,我可能更喜欢简单地调用coordinates.Coordinatescoordinates.Coordinates即使这看起来是多余的。

I've also considered making my module callable to make coordinates() to automatically call Coordinates() but I'm not really sure it's really a good solution either (and I'm not sure how to handle the documentation in such case).我还考虑过让我的模块可调用以使coordinates()自动调用Coordinates()但我也不确定这是否真的是一个好的解决方案(并且我不确定在这种情况下如何处理文档)。

It is a matter of personal preference, but for myself, I'd go with:这是个人喜好的问题,但对于我自己,我会选择:

from coordinates import Coordinates

Unless , that is, you are using more than, oh, three or four things from the coordinates module, or one of the names you are importing from it clashs with names you are using from elsewhere.除非,也就是说,您正在使用coordinates模块中的三四个以上的东西,或者您从中导入的名称之一与您从其他地方使用的名称冲突。 In either of those cases, go with在这两种情况中的任何一种情况下,请使用

import coordinates

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

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