python - absolute import for module in the same directory

前端 未结 2 1797
旧巷少年郎
旧巷少年郎 2021-01-04 03:55

I have this package:

mypackage/
    __init__.py
    a.py
    b.py

And I want to import things from module a to module b, does it make sense

2条回答
  •  南笙
    南笙 (楼主)
    2021-01-04 04:34

    You should use from mypackage.a import things, you, want.

    There are two issues here, the main one is relative vs absolute imports, the semantics of which changed in Python 3, and can optionally be used in Python 2.6 and 2.7 using a __future__ import. By using mypackage.a you guarantee that you will get the code you actually want, and it will work reliably on future versions of Python.

    The second thing is that you should avoid import *, as it can potentially mask other code. What if the a.py file gained a function called sum? It would silently override the builtin one. This is especially bad when importing your own code in other modules, as you may well have reused variable or function names.

    Therefore, you should only ever import the specific functions you need. Using pyflakes on your sourcecode will then warn you when you have potential conflicts.

提交回复
热议问题