Should I use “from package import utils, settings” or “from . import utils, settings”

前端 未结 1 786
无人及你
无人及你 2021-01-13 14:56

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 interpr

相关标签:
1条回答
  • 2021-01-13 15:55

    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.

    0 讨论(0)
提交回复
热议问题