简体   繁体   English

导入1.7与1.8样式的点运算符

[英]dot operator for import 1.7 vs 1.8 style

I noticed between the Django 1.7 and the newer 1.8 official tutorial, this minor change in syntax. 我注意到在Django 1.7和较新的1.8官方教程之间,语法上的微小变化。

1.7 1.7

from django.contrib import admin
from polls.models import Question

admin.site.register(Question)

1.8 (you can see the app removed) 1.8(您可以看到该应用已删除)

from django.contrib import admin

from .models import Question

admin.site.register(Question)

Why the change? 为什么要改变? Which is better code? 哪个更好的代码? Forgot the right terminilogy but had something to do with scoping, the dot operator. 忘记了正确的术语,但与范围界定(点运算符)有关。

Also I have seen the dot operator used like this; 我也看到点运算符像这样使用; what does is mean here? 这是什么意思?

from django.conf.urls import url

from . import views

Getting some testing/learning done and want to know the how and why this is used this way. 完成一些测试/学习,并想知道如何以及为什么使用这种方式。 Thanks all. 谢谢大家

This is at least somewhat subjective, but in my opinion a relative import is generally better when you're trying to import files from the same package. 这至少是主观的,但是在我看来,当您尝试从同一包中导入文件时,相对导入通常会更好。

If you happen to have a module named polls in the current package but also a package named polls at the top level, using polls is ambiguous to the reader--and has different meanings in old vs. new versions of Python. 如果您在当前软件包中碰巧有一个名为polls的模块,但在顶层也有一个名为polls的软件包,则使用polls对读者来说是模棱两可的-在旧版本和新版本的Python中含义不同。 But using . 但是使用. has only one meaning to any reader or any version of Python, and there's no way it can collide with anything else accidentally. 对于任何阅读器或任何版本的Python而言,它仅具有一种含义,并且它不可能与其他任何内容意外碰撞。

Also, with relative imports, you can rename your package and everything still works; 同样,通过相对导入,您可以重命名您的程序包,并且一切仍然有效; with absolute, you have to edit every file. 如果使用绝对值,则必须编辑每个文件。 If you move the package inside another package, it may require even bigger changes. 如果将包装移动到另一个包装中,则可能需要进行更大的更改。

There are also some minor reasons. 还有一些次要原因。 If you accidentally put a package on sys.path (eg, by running your top-level app with the current working directory set to the package), it's usually easier to debug with relative imports. 如果您不小心将软件包放在sys.path (例如,通过将当前工作目录设置为软件包运行顶级应用程序),则通常可以相对轻松地进行调试。 Importing yourself (and in some cases doing so implicitly with pickle or multiprocessing) is easier with relative imports. 通过相对导入,可以更轻松地导入自己(在某些情况下,使用pickle或多处理程序进行隐式导入)。

The best reason to use the old style is if you need to be backward-compatible with Python 2.5 or earlier. 使用旧样式的最佳理由是,如果您需要与Python 2.5或更早版本向后兼容。 (Which Django used to support, but no longer does. Although I don't know whether or not they switched in 1.8 because that's when they dropped enough old versions.) (哪个Django曾经支持,但不再支持。尽管我不知道他们是否切换到1.8版本,因为那是他们删除足够多的旧版本的时候。)

Read PEP 328 for further discussion of the rationale. 阅读PEP 328,以进一步了解其原理。

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

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