When to use absolute imports

后端 未结 1 1312
余生分开走
余生分开走 2020-12-08 11:17

I\'m changing a bunch of old python code that is occasionally running into name collisions between packages. I have a question about when absolute imports should be used an

相关标签:
1条回答
  • 2020-12-08 11:54

    Relative imports turned out to be a very bad idea, even though they were the default behavior for long. You can find quite a few questions on this site where someone simply named their file after a builtin module and broke their application with weird error messages.

    That's why it's always a good to do absolute imports by referencing your project everywhere, including packages.

    In short, use this style:

    import myproject.mypackage
    from myproject.mypackage.myfile import MyClass
    

    Quote from PEP8:

    Relative imports for intra-package imports are highly discouraged. Always use the absolute package path for all imports. Even now that PEP 328 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.

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