在 Python 中使用包名破坏枚举比较导入

Importing with package name breaking enum comparison in 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

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

就Python而言,您正在导入一个不同的模块;你有 PieceChess.Piece。 Python 将为这两个模块创建 单独的模块对象 ,每个模块都有一个单独的枚举 class。这些 classes 上的值永远不会被测试为相等。

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