tags:

views:

137

answers:

1

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?

+7  A: 

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.

Eevee
I was confused about absolute/relative. I mean, there are not two styles, there are three: import utils, from . import utils, and from application import utils. I figured that case "." here is actually an absolute import, in contrast with case "import x". And thus that my presented 1 and 2 above where at equal standing. It is true that for a deeper application (mine has only one package and one subpackage), there are many places to call "."
kaizer.se
Early problem with the application was that since I had a module called "application.application", cPickle would not work, but pickle would (differing abs/rel import handling). I had to work around by renaming the module, it was a bad name anyway.
kaizer.se