Python通过循环导入让我疯狂

问题描述 投票:0回答:2

来自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:无法从'helpers'导入名称'Printable'

如果我完全删除Printable依赖项,一切正常。

如果我稍微更改了datasets.py中的导入:

import helpers as ma_helpers

class Dataset(ma_helpers.Printable):
   ...

然后错误消息变为:

AttributeError:模块'helpers'没有属性'Printable'

我怎样才能使用来自datasets.py的helpers.py的Printable,同时使用来自helpers.py的datasets.py的my_datasets

python python-3.x python-import circular-dependency
2个回答
2
投票

假设您对两个模块都有编辑权限,并且helpers.py包含自包含辅助函数,您可能希望将与dataset.py相关的辅助代码移动到dataset.py - 这可能会略微减少模块化,但它会解决周期的最快方法。


0
投票

您获得循环依赖性错误的原因是,您从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)

现在,如果您尝试从get_some_dataset导入test然后尝试执行它,它将起作用。

© www.soinside.com 2019 - 2024. All rights reserved.