Relative imports

I read Two Songs. Django best practices to improve the coding style. I am in relative import, and here is a sample code to make it reusable.

Old Way: from cones.foo import bar New way: from .foo import bar 

The code above for the cone application, what if I call another model in another application? Should I do this:

 from .foo import bar from .other import sample OR from .foo import bar from test.other import sample 

What is the right way?

+8
django
source share
2 answers

I usually use imports like this for only one reason.

 from .foo import bar from .other import sample 

The reason that if Tomorrow, my module name will change from "test" to "mytest", then the code does not require refactoring. The code works without breaking.

Update

All imports starting with the character '.' point, only works inside . Importing cross modules takes the whole path.

+17
source share

If test is another application,

 from .other import sample 

does not work.

Update:

You can use relative imports only when importing from the same application.

Inside test application

 from .other import sample 

will work. But you still need the full form

 from cones.foo import bar 

if you import the method defined in foo from the test application.

Thus, answering your question, the second way is the right way.

+3
source share

All Articles