在Python中导入带有包名称的枚举枚举比较 [英] Importing with package name breaking enum comparison in Python

查看:79
本文介绍了在Python中导入带有包名称的枚举枚举比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Piece.py:

从枚举导入枚举中的

 PieceType(Enum)类:type_one = 1...def recognise_type(my_type):print("Passed",my_type)如果my_type为PieceType.type_one:打印(第一类")别的:打印(无法识别类型") 

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

ai.py:

 进口件def get_promotion():返回Piece.PieceType.type_one 

bug.py:

 进口件导入aimy_type = ai.get_promotion()Piece.recognise_type(my_type) 

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

  Passed PieceType.type_one第一类 

但是这是东西.该软件包的名称为"Chess",但是如果在ai.py中,我们将Chess import Piece 的 import Piece 更改为(例如,如果要放入ai.py在不同的程序包中),则出问题了.现在运行bug.py即可:

  Passed PieceType.type_one类型无法识别 

这是怎么回事?为什么在import语句中包含程序包名称会中断枚举比较?

解决方案

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

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

My friend and I are making chess AIs in Python, but we're running into a mysterious problem with enums. We encode the piece types in an enum like so:

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")

We ask the AI for a piece (for promoting a pawn for instance) and call 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)

So far so good; running bug.py outputs the following:

Passed PieceType.type_one
Type One

But here's the thing. The name of this package is 'Chess', but if in ai.py we change import Piece to from Chess import Piece (for instance if we want to put ai.py in a different package), then something goes wrong. Running bug.py now gives:

Passed PieceType.type_one
Type not recognised

What's happening here? Why does including the package name in the import statement break enum comparison?

解决方案

As far as Python is concerned, you are importing a different module; you have Piece and you have Chess.Piece. Python will create separate module objects for these two modules, each with a separate enum class. The values on those classes are never going to test as equal.

If all your modules are part of the Chess package then you should not treat the files in that package as top-level modules. That means you should not add that directory to your Python path (explicitly or implictly by using a script in that directory).

这篇关于在Python中导入带有包名称的枚举枚举比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆