change in import handling / modules from python2 to python3?

前端 未结 2 1990
日久生厌
日久生厌 2021-01-05 08:19

I was trying to following the design pattern shown in this previous question related to SQLAlchemy and intended to share a common Base instance across multiple files. The co

相关标签:
2条回答
  • 2021-01-05 09:19

    One solution I found is to:

    • move the code from base.py to __init__.py.
    • change the import base lines in a.py, b.py, and c.py to from . import Base
    • in model.py change from model import base to from model import Base
    • also in model.py change base.Base to Base.

    I'm still uncertain why the previous design works in python2 but not python3. The changes above make it work in both python2 and python3.

    0 讨论(0)
  • 2021-01-05 09:21

    Python 3 switches to absolute imports by default, and disallows unqualified relative imports. The from base import Base line is such an import.

    Python 3 will only look for top-level modules; you don't have a base top-level module, only model.base. Use a full module path, or use relative qualifiers:

    from .base import Base
    

    The . at the start tells Python 3 to import starting from the current package.

    You can enable the same behaviour in Python 2 by adding:

    from __future__ import absolute_import
    

    This is a change introduced by PEP 328, and the from future import is available from Python 2.5 onwards.

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