简体   繁体   中英

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

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

Suppose this is how Django apps are layout:

Webclient

  • apps
    • myapp#1
      • library
        • library.py
    • myapp#2
      • views.py
    • myapp#3

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

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)?

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.

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. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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