Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relative Imports

Tags:

django

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?

like image 886
catherine Avatar asked Feb 08 '13 07:02

catherine


People also ask

What is a relative import?

A relative import specifies the resource to be imported relative to the current location—that is, the location where the import statement is. There are two types of relative imports: implicit and explicit.

What is an absolute import?

Absolute import involves a full path i.e., from the project's root folder to the desired module. An absolute import state that the resource is to be imported using its full path from the project's root folder.

How do you use relative import in Python?

Here is the solution which works for me: I do the relative imports as from .. sub2 import mod2 and then, if I want to run mod1.py then I go to the parent directory of app and run the module using the python -m switch as python -m app. sub1.

What are the imports in Python?

In Python, you use the import keyword to make code in one module available in another. Imports in Python are important for structuring your code effectively. Using imports properly will make you more productive, allowing you to reuse code while keeping your projects maintainable.


1 Answers

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.

like image 108
Crazyshezy Avatar answered Sep 30 '22 00:09

Crazyshezy