13

I'm reading Two Scoops Django Best Practices to make my coding style improve. I'm in relative imports and here is the sample code to make it reusable.

Old Way:
from cones.foo import bar

New way:
from .foo import bar

The code above is for cones app, what if I call the other model in other app? Do I have to put like this:

from .foo import bar
from .other import sample

OR

from .foo import bar
from test.other import sample

What is the correct way?

Tms91
  • 3,456
  • 6
  • 40
  • 74
catherine
  • 22,492
  • 12
  • 61
  • 85
  • 3
    There is a legitimate python module called "test" - don't call your modules that way to avoid confusion. – Evgeny Sep 24 '13 at 21:47

2 Answers2

21

I usually use imports like this only for one reason

from .foo import bar
from .other import sample

The reason being If Tomorrow, my module name changes from say 'test' to 'mytest' then the code does not require a refactoring. The code works without breaking.

Update

All imports starting with a '.' dot, only works within that package. Cross package imports need require the whole path.

Crazyshezy
  • 1,530
  • 6
  • 27
  • 45
  • 1
    You're right so that's the reason for refactoring, thanks for the info – catherine Feb 08 '13 at 07:25
  • Are you sure? Because it says here I can put double or more dots depends on the location of other files in other apps – catherine Feb 08 '13 at 07:48
  • '.' and '..' are known as intra-package references the name says it all. Only works within a module/package read.. read more [here] (http://docs.python.org/2/tutorial/modules.html#intra-package-references). The examples given in for sub-modules not two different modules – Crazyshezy Feb 08 '13 at 07:58
  • What do you mean it only works within that module? Assuming you also refer to a module as simply a ```.py``` file then why would you import a function that is already in your current module (aka ```.py``` file). – gmarais Feb 18 '20 at 19:33
  • @gmarais, yes what i wanted to mention was "with that package", I updated the answer. thank you – Crazyshezy Feb 19 '20 at 08:32
3

If test is another app,

from .other import sample

wont work.

Update:

You can only use relative imports when you're importing from the same app.

Inside test app

from .other import sample

will work. But you'll still need the complete form

from cones.foo import bar

if you import method defined in foo from test app.

So answering your question the second way is the correct way.

Antony Hatchkins
  • 31,947
  • 10
  • 111
  • 111