Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.5k views
Welcome To Ask or Share your Answers For Others

1 Answer

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share

548k questions

547k answers

4 comments

56.5k users

...