在Python中导入带有包名称的枚举枚举比较 - python

我和我的朋友正在用Python制作国际象棋AI,但是我们遇到了一个枚举的神秘问题。我们将枚举类型编码为枚举,如下所示:

Piece.py:

from enum import Enum

class PieceType(Enum):
    type_one = 1
    ...

def recognise_type(my_type):
    print("Passed ", my_type)

    if my_type is PieceType.type_one:
        print("Type One")
    else:
        print("Type not recognised")

我们要求AI提供一块(例如,用于提升典当),然后调用recognise_type:

ai.py:

import Piece

def get_promotion():
    return Piece.PieceType.type_one

bug.py:

import Piece
import ai

my_type = ai.get_promotion()
Piece.recognise_type(my_type)

到目前为止,一切都很好;运行bug.py将输出以下内容:

Passed PieceType.type_one
Type One

但是,这就是事情。该程序包的名称为“ Chess”,但是如果在ai.py中将import Piece更改为from Chess import Piece(例如,如果我们要将ai.py放入另一个程序包中),则会出问题。运行bug.py现在可以得到:

Passed PieceType.type_one
Type not recognised

这里发生了什么事?为什么在import语句中包含包名称会中断枚举比较?

python大神给出的解决方案

就Python而言,您正在导入一个不同的模块。您有Piece并且您有Chess.Piece。 Python将为这两个模块创建单独的模块对象,每个模块对象都有一个单独的enum类。这些类上的值永远不会相等。

如果所有模块都是Chess软件包的一部分,则不应将该软件包中的文件视为顶级模块。这意味着您不应该将该目录添加到您的Python路径(通过使用该目录中的脚本来显式或隐式)。