Welcome to OGeek Q&A 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 Reply

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...