我收到以下错误,并且找不到任何循环依赖项。
导入错误:无法从“架构”导入名称“Base”
我已将代码组织到包中,如下所示:
customers/__init__.py
customers/customers_db.py
customers/schema.py
setup.py
schema.py(取决于 SqlAlchemy)
from typing import List
from typing import Optional
from sqlalchemy import ForeignKey
from sqlalchemy import String
from sqlalchemy.orm import declarative_base
from sqlalchemy.orm import Mapped
from sqlalchemy.orm import mapped_column
from sqlalchemy.orm import relationship
Base = declarative_base()
customers_db.py(取决于 schema.py)
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
import os
from schema import Base, Contact, Address
setup.py(取决于customers_db.py)
import customers.customers_db as db
在解释器中运行customers_db.py 本身没有错误。运行setup.py时出现错误。
更新
这是完整的回溯:
Traceback (most recent call last):
File "C:\devroot\PyCustomer\src\setup.py", line 1, in <module>
import customers.customers_db as db
File "C:\devroot\PyCustomer\src\customers\customers_db.py", line 4, in <module>
from schema import Base, Contact, Address
ImportError: cannot import name 'Base' from 'schema' (C:\devroot\PyCustomer\.venv\Lib\site-packages\schema.py)
看来customer_db.py文件需要使用相对路径引用schema.py,因此顶层模块可能会找到它。
from .schema import Base, Contact, Address
然后使用 -m 选项从顶级目录单独运行 customer_db.py。
$ python -m customers.customers_db