4 ms·
> That said, is there a reason not to use relative imports? Yes, they make reading imports across your entire project rather difficult: Suddenly there are mult
by codethief 4y ago
> That said, is there a reason not to use relative imports?
Yes, they make reading imports across your entire project rather difficult: Suddenly there are multiple ways of referring to the same module. If you ever have to do a project-wide search & replace during a refactoring (because your favorite refactoring tool failed you), this will be hell.
Moreover, in each file you'll end up with a weird blend of absolute and relative imports, depending on what was shorter or looked nicer to the author at the time. Not nice to look at at all.
> This led me to dig into why we might add to __init__.py
…or why we might rather not. Init files are one of the main reasons imports in Python often behave in unexpected ways. As a library user I do not want to study the library's init files first, but unfortunately I often have to in order to understand what is going on. (Case in point: Tensorflow 1/2. To this day, I can't claim I understand how exactly their init magic works and time and again I get bitten by failed imports.)
- zzzeek 4y ago>Yes, they make reading imports across your entire project rather difficult: Suddenly there are multiple ways of referring to the same module. If you ever have to do a project-wide search & replace during a refactoring (because your favorite refactoring tool failed you), this will be hell. > Moreover, in each file you'll end up with a weird blend of absolute and relative imports, depending on what was shorter or looked nicer to the author at the time. Not nice to look at at all. it sounds like your project had inconsistent import styles leading to this issue. IMO imports should always be relative and always be one imported symbol per line, they should be sorted and linted [1] that they follow this exact form. you will have no issues with imports, merges, search and replaces, etc. after that. [1] I use https://pypi.org/project/flake8-import-order/ https://pypi.org/project/flake8-import-order/ along with an in-house import rendering tool.
- DandyDev 4y agoImports from 3rd party packages are always absolute. That's why I prefer imports from first party packages to be absolute as well
- zzzeek 4y agowell yes but when you sort your imports, 3rd party imports are always in a separate stanza entirely. there's no "weird blend of absolute and relative imports, depending on what was shorter or looked nicer to the author at the time.", nothing is blended and also Black should be used for formatting. That way nobody is making any "this looks nicer" kinds of decisions nor does anyone have to waste their time on that.