Python 循环导入让我抓狂
Python driving me crazy with circular import
来自 helpers.py:
import ...
from datasets import my_datasets
class Printable():
def __str__(self):
return 'foobar'
def get_some_dataset(ds_id):
return my_datasets.get(ds_id, None)
来自 datasets.py:
import ...
from helpers import Printable
class Dataset(Printable):
def __init__(self, param):
self.baz = param
my_datasets = {
'id1': Dataset(foo),
'id2': Dataset(bar)
}
现在 Python 尖叫
ImportError: cannot import name 'Printable' from 'helpers'
如果我完全删除 Printable 依赖项,一切正常。
如果我稍微更改 datasets.py 中的导入:
import helpers as ma_helpers
class Dataset(ma_helpers.Printable):
...
然后报错信息变成:
AttributeError: module 'helpers' has no attribute 'Printable'
如何使用helpers.py的datasets.py的Printable
,同时使用helpers.py的datasets.py的my_datasets
=]?
假设您对这两个模块都有编辑权限,并且 helpers.py 包含独立的辅助函数,您可能希望将与 dataset.py 相关的辅助代码移动到 dataset.py - 这可能会稍微减少模块化,但这是解决循环的最快方法。
您收到循环依赖错误的原因是,您正在从 helper.py
导入某些内容到 dataset.py
,反之亦然。做法不对。考虑到您正在尝试做一些 OOP 并对其进行测试,让我们像下面这样重写代码-
domain.py
=========
class Printable():
def __str__(self):
return 'foobar'
class Dataset(Printable):
def __init__(self, param):
self.baz = param
test.py
=======
from domain import Dataset
my_datasets = {
'id1': Dataset(foo),
'id2': Dataset(bar)
}
def get_some_dataset(ds_id):
return my_datasets.get(ds_id, None)
现在,如果您尝试从 test
导入 get_some_dataset
,然后尝试执行它,它就会成功。
来自 helpers.py:
import ...
from datasets import my_datasets
class Printable():
def __str__(self):
return 'foobar'
def get_some_dataset(ds_id):
return my_datasets.get(ds_id, None)
来自 datasets.py:
import ...
from helpers import Printable
class Dataset(Printable):
def __init__(self, param):
self.baz = param
my_datasets = {
'id1': Dataset(foo),
'id2': Dataset(bar)
}
现在 Python 尖叫
ImportError: cannot import name 'Printable' from 'helpers'
如果我完全删除 Printable 依赖项,一切正常。
如果我稍微更改 datasets.py 中的导入:
import helpers as ma_helpers
class Dataset(ma_helpers.Printable):
...
然后报错信息变成:
AttributeError: module 'helpers' has no attribute 'Printable'
如何使用helpers.py的datasets.py的Printable
,同时使用helpers.py的datasets.py的my_datasets
=]?
假设您对这两个模块都有编辑权限,并且 helpers.py 包含独立的辅助函数,您可能希望将与 dataset.py 相关的辅助代码移动到 dataset.py - 这可能会稍微减少模块化,但这是解决循环的最快方法。
您收到循环依赖错误的原因是,您正在从 helper.py
导入某些内容到 dataset.py
,反之亦然。做法不对。考虑到您正在尝试做一些 OOP 并对其进行测试,让我们像下面这样重写代码-
domain.py
=========
class Printable():
def __str__(self):
return 'foobar'
class Dataset(Printable):
def __init__(self, param):
self.baz = param
test.py
=======
from domain import Dataset
my_datasets = {
'id1': Dataset(foo),
'id2': Dataset(bar)
}
def get_some_dataset(ds_id):
return my_datasets.get(ds_id, None)
现在,如果您尝试从 test
导入 get_some_dataset
,然后尝试执行它,它就会成功。