Importing with package name breaking enum comparison in Python

720 views Asked by At

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?

1

There are 1 answers

2
Martijn Pieters On BEST ANSWER

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