Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

python - Enum with infinite/dynamic members

Abstract: I would like to have an (integer) enum which has some (negative) members which correspond to specific states and unbound (positive) members.

Example: Assume we have a database entry which stores the winning position in a race. These entries are positive if the race was finished. However there are also some special values for e.g. Did not finish, Did not attend, Disqualified. These are stored in the database as negative values.

Now I would like to represent this structure in Python. As enums are immutable this turns out to be rather difficult. I already studied enum.EnumMeta and the looked at the aenum library but did not find a solution. My least ridiculous idea was to have an enum like the following:

import enum

class RankingPlace(enum.IntEnum):
    FINISHED = 0
    DID_NOT_FINISH = -1
    DID_NOT_ATTEND = -2
    DISQUALIFIED = -3

    def __call__(self, value):
        if value < 0:
            return super()(member)
        else:
            member = self.__class__.FINISHED
            member.actual_place = value
            return member

This kinda works but I have to make the call on an member to make it work. Is there a cleaner way using e.g. a custom metaclass?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It sounds like the best solution would be a combination of Enum and something else -- maybe a namedtuple (example code using NamedTuple from aenum:

class Status(aenum.IntEnum):
    FINISHED = 0
    DID_NOT_FINISH = -1
    DID_NOT_ATTEND = -2
    DISQUALIFIED = -3

class Placement(aenum.NamedTuple):
    race = 0, 'name of race'
    status = 1, 'finished race?'
    placement = 2, 'position when finished'

winner = Placement('2021 Marathon', Status.FINISHED, 1)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...