Python在不合并文件的情况下解析循环导入



我有一段定义游戏中可能的道具类型和魔法类型的代码。有些附魔类型彼此不兼容,或者与某些物品类型不兼容。我希望每种物品类型都有与之不兼容的附魔信息,以及每种附魔包含与之兼容的物品信息,而无需不断查找其中一种。

items.py:

from enum import Enum, auto
class ItemType(Enum):
PLATE = auto()
HELMET = auto()
BOOTS = auto()
SWORD = auto()
BOW = auto()
# Get compatible enchantment types
from enchantments import EnchantmentType
for it in ItemType:
it.compatible_enchantments = set(filter(lambda ench: it in ench.compatible_items, EnchantmentType))

class Item:
def __init__(self, item_type, enchantments=None):
self.type = item_type
self.enchantments = []
if enchantments:
for ench in enchantments:
self.add_enchantment(ench)
def add_enchantment(self, enchantment, i=None):
if enchantment.type not in self.compatible_enchantments:
raise ValueError(f"Enchantment {enchantment.type} is incompatible with {self.type}.")
if i is None:
self.enchantments.append(enchantment)
else:
self.enchantments.insert(enchantment, i)    from enum import Enum
from items import ItemType as IT

enchantments.py:

from enum import Enum, auto
class EnchantmentType(Enum):
ENHANCED_ARMOUR = IT.HELMET, IT.PLATE, IT.BOOTS, IT.RING
ENHANCED_DAMAGE = IT.SWORD, IT.BOW, IT.RING
YELLOW_COLOUR = ()
def __init__(self, *compatible_item_types):
self.compatible_items = set(IT) if not compatible_item_types else compatible_item_types
self.incompatible_enchantments = set()
# Fill in the incompatible enchantments
for mutualy_exclusive_group in (
{EnchantmentType.ENHANCED_ARMOUR, EnchantmentType.ENHANCED_DAMAGE}
):
for ench in mutualy_exclusive_group:
ench.incompatible_enchantments += mutualy_exclusive_group - {ench}

class Enchantment:
def __init__(self, enchantment_type, level=None):
self.type = enchantment_type
self.level = level

main.py:

from enchantments import EnchantmentType as ET
print(ET.ENHANCED_ARMOUR.compatible_items)
print(ET.ENHANCED_DAMAGE.compatible_items)
print(ET.YELLOW_COLOUR.compatible_items)

运行这段代码会得到一个引用循环导入的ImportError

在这个答案之后,我尝试将from x import y语句更改为import x,但仍然得到相同的错误。

我通过从items.py中删除from enchantments import EnchantmentType并移动

行暂时解决了这个问题
from enchantments import EnchantmentType
for it in ItemType:
it.compatible_enchantments = set(filter(lambda ench: it in ench.compatible_items, EnchantmentType))

intoenchantments.py。然而,这要求任何希望获得有关结魔的正确信息的模块手动导入enchantments.py—仅导入items.py将导致所有compatible_enchantments为空。

是否有一种方法可以使我的循环导入工作而不合并两个文件?

与其在每个ItemTypes上设置compatible_enchantments,为什么不在某处(可能在enchantments.py中)有一个字典,将一个EnchantmentType映射到它可以应用的有效的ItemTypes集合?

对我来说,似乎ItemType不需要知道结界,但结界需要知道它们是否可以应用于特定的ItemType。

最新更新