Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tool to detect non-dotted relative imports in Python?

It's considered bad Python to use imports like this:

import my_module

When you are doing a relative import and this would work:

from . import my_module

Is there a tool that can detect these non-dotted relative imports in my code and warn me so I could update them to the dotted syntax? My project has hundreds of Python modules and I would like to do this automatically. (Possibly such a tool would override __import__ and detect the bad imports as they happen when I run the program.)

Does anyone know of such tool?

like image 710
Ram Rachum Avatar asked Dec 20 '10 14:12

Ram Rachum


People also ask

What does Importlib Import_module return?

The return value from import_module() is the module object that was created by the import. If the module cannot be imported, import_module() raises ImportError . The error message includes the name of the missing module. To reload an existing module, use reload() .

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.


1 Answers

[Reposted as an answer because it apparently did the trick]

2to3 will automatically convert them, because it's compulsory in Python 3.

Here's the relevant source code if you want to modify it for your purposes.

Alternatively, you could just run 2to3 with only that fixer: 2to3 -w -f import myproject/

like image 97
Thomas K Avatar answered Oct 14 '22 23:10

Thomas K