change in import handling / modules from python2 to python3?

前端 未结 2 2006
日久生厌
日久生厌 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: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.

提交回复
热议问题