相对进口 [英] Relative Imports

查看:71
本文介绍了相对进口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读《两勺Django最佳实践》,以提高我的编码风格。我处于相对进口状态,这是使代码可重用的示例代码。

I'm reading Two Scoops Django Best Practices to make my coding style improve. I'm in relative imports and here is the sample code to make it reusable.

Old Way:
from cones.foo import bar

New way:
from .foo import bar

上面的代码适用于锥应用程序,如果我在其他应用程序中调用其他模型怎么办?我必须这样写吗:

The code above is for cones app, what if I call the other model in other app? Do I have to put like this:

from .foo import bar
from .other import sample

OR

from .foo import bar
from test.other import sample

正确的方法是什么?

推荐答案

我通常仅出于一个原因使用这种导入方式

I usually use imports like this only for one reason

from .foo import bar
from .other import sample

原因是
如果明天,我的模块名称从 test更改为 mytest,则代码不需要重构。该代码可以正常工作。

The reason being If Tomorrow, my module name changes from say 'test' to 'mytest' then the code does not require a refactoring. The code works without breaking.

所有以'。'点开头的导入,仅在内有效那个包裹。
跨包导入需要整个路径。

All imports starting with a '.' dot, only works within that package. Cross package imports need require the whole path.

这篇关于相对进口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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