在Python中非常专门地导入始终是个好主意吗? [英] Is it always a good idea to import very specifically in Python?

查看:46
本文介绍了在Python中非常专门地导入始终是个好主意吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这几乎是Python,但要向Django用户询问.

This is pretty much Python, but asking from a Django user.

假设这是Django应用程序的布局方式:

Suppose this is how Django apps are layout:

Webclient

Webclient

  • 应用
    • myapp#1
      • 图书馆
        • library.py
        • views.py

        如果我正在使用views.py,并且我想导入library.py,哪一个看起来更好?

        If I am working with views.py, and I want to import library.py, which one seems better?

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

        我正在使用PyCharm,无论哪种方式都不会抱怨未解决的引用".特别指定导入是否更好.如果可能的话,第二种导入方法是否更有可能避免名称冲突(例如/library/有多个.py文件)?

        I am using PyCharm, and either way doesn't complain about "unresolved references". 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)?

        谢谢.

        推荐答案

        您应始终从定义名称的位置导入名称.这样,如果 webclient.apps.myapp.library 有一天应该停止导入 LibraryClass ,那么您就不会中断其他导入.

        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.

        这篇关于在Python中非常专门地导入始终是个好主意吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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