Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When or why to use relative imports in Python

Is there any rules or guidelines concerning when to use relative imports in Python? I see them in use all the time like in the Flask web framework. When searching for this topic, I only see articles on how to use relative imports, but not why.

So is there some special benefit to using:

from . import x 

rather than:

from package import x 

Moreover, I noticed that a related SO post mentions that relative imports are discouraged. Yet people still continue to use them.

like image 310
trinth Avatar asked Oct 05 '12 02:10

trinth


People also ask

Should I use relative or absolute imports Python?

With your new skills, you can confidently import packages and modules from the Python standard library, third party packages, and your own local packages. Remember that you should generally opt for absolute imports over relative ones, unless the path is complex and would make the statement too long.

Why we are using import 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.

Why is the use of import all statements not recommended in Python?

Using import * in python programs is considered a bad habit because this way you are polluting your namespace, the import * statement imports all the functions and classes into your own namespace, which may clash with the functions you define or functions of other libraries that you import.


1 Answers

Check out PEP 328's section on relative imports

The rationale seems to be as written:

Several use cases were presented, the most important of which is being able to rearrange the structure of large packages without having to edit sub-packages. In addition, a module inside a package can't easily import itself without relative imports.

like image 54
Bartek Avatar answered Sep 29 '22 12:09

Bartek