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?
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.
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.
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.
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.
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.
All imports starting with a '.' dot, only works within that package. Cross package imports need require the whole path.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With