简体   繁体   English

在Python中专门导入总是一个好主意吗?

[英]Is it always a good idea to import very specifically in Python?

This is pretty much Python, but asking from a Django user. 这几乎是Python,但要向Django用户询问。

Suppose this is how Django apps are layout: 假设这是Django应用程序的布局方式:

Webclient Web客户端

  • apps 应用
    • myapp#1 MYAPP#1
      • library 图书馆
        • library.py library.py
    • myapp#2 MYAPP#2
      • views.py views.py
    • myapp#3 MYAPP#3

If I am working with views.py, and I want to import library.py, which one seems better? 如果我正在使用views.py,并且要导入library.py,哪个更好?

from webclient.apps.myapp.library import LibraryClass
from webclient.apps.myapp.library.library import LibraryClass

I am using PyCharm, and either way doesn't complain about "unresolved references". 我正在使用PyCharm,无论哪种方式都不会抱怨“未解决的引用”。 Is it better to import very speifically. 特别指定导入是否更好。 Is second import method more likely to avoid name collison, if possible at all (say /library/ has several .py files)? 如果可能的话,第二种导入方法是否更有可能避免名称冲突(例如/ library /有多个.py文件)?

Thanks. 谢谢。

You should always import names from where they're defined. 您应该始终从定义的位置导入名称。 That way if webclient.apps.myapp.library should stop importing LibraryClass one day, you won't break the other imports. 这样,如果webclient.apps.myapp.library有一天应该停止导入LibraryClass ,则不会中断其他导入。

As a follow-up to Ignacio's answer, you should look at the documentation of the libraries you are using, to see where it suggests you import things. 作为对Ignacio的回答的后续操作,您应该查看所使用的库的文档,以了解它在哪里建议您导入内容。 It may be that although LibraryClass is defined in webclient.apps.myapp.library.library , it is documented as being in webclient.apps.myapp.library , so at some point, it the definition might be moved there, or webclient.apps.myapp.library.oldversion , but still accessible from webclient.apps.myapp.library . 可能是,虽然LibraryClass是在webclient.apps.myapp.library.library定义的,但它已记录为在webclient.apps.myapp.library ,因此在某些时候,它的定义可能会移到该位置,也可能是webclient.apps.myapp.library.oldversion ,但仍可从webclient.apps.myapp.library访问。

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

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