2

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.

jsbueno
  • 99,910
  • 10
  • 151
  • 209
CppLearner
  • 16,273
  • 32
  • 108
  • 163

2 Answers2

4

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.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
3

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.

Tom Prince
  • 682
  • 3
  • 9