CppLearner
CppLearner

Reputation: 17040

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.

Upvotes: 2

Views: 139

Answers (2)

Tom Prince
Tom Prince

Reputation: 682

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.

Upvotes: 3

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798646

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.

Upvotes: 4

Related Questions