Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use "from package import utils, settings" or "from . import utils, settings"

Tags:

python

I'm developing a Python application; it has all its code in one package and runs inside this of course. The application's Python package is of no interest from the interpreter to the user, it's simply a GUI application.

The question is, which style is preferred when importing modules inside the application package

from application import settings, utils

or

from . import settings, utils

That is I can either specify the name as it is (here 'application') or I can say "current package" by using "."

This is a Free software package so the possibility exists that someone wants to make a fork of my application and change its name. In that case, alternative 1 is a slight nuisance. Still, I use style 1 all the time (although early code uses style 2 in some places), since style 1 looks much better.

Are there any arguments for my style (1) that I have missed? Or is it stupid not to go with style 2?

like image 314
u0b34a0f6ae Avatar asked Dec 30 '22 16:12

u0b34a0f6ae


1 Answers

The Python Style Guide recommends explicitly against relative imports (the . style):

Relative imports for intra-package imports are highly discouraged. Always use the absolute package path for all imports. Even now that PEP 328 [7] is fully implemented in Python 2.5, its style of explicit relative imports is actively discouraged; absolute imports are more portable and usually more readable.

I tend to agree. Relative imports mean the same module is imported in different ways in different files, and requires that I remember what I'm looking at when reading and writing. Not really worth it, and a rename can be done with sed.

Besides the issue of renaming, the only problem with absolute imports is that import foo might mean the top-level module foo or a submodule foo beneath the current module. If this is a problem, you can use from __future__ import absolute_import; this is standard in Python 3.

like image 91
Eevee Avatar answered Jan 26 '23 21:01

Eevee