Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a method to an enum?

Tags:

python

enums

I would like to add a method to my enum.

class Kerneltype(Enum):
    tube = 0
    subspace_KDE = 1
    deltashift = 2
    dist_sens_via_mass_1 = 3

    def aslist(self):
        return [self.tube, self.subspace_KDE, self.deltashift, self.dist_sens_via_mass_1]

    def fromint(self, int):
        return self.aslist()[int]

does not work. Instead of

Kerneltype.aslist()

I currently have to do

[kt[1] for kt in ob.Kerneltype.__members__.items()]
like image 870
Make42 Avatar asked May 23 '17 16:05

Make42


2 Answers

You created an instance method, so aslist only exists on instances of Kerneltype (i.e. the enum members themselves). You need a classmethod instead:

@classmethod
def aslist(cls):
    return [cls.tube, cls.subspace_KDE, cls.deltashift, cls.dist_sens_via_mass_1]
>>> Kerneltype.aslist()
[<Kerneltype.tube: 0>, <Kerneltype.subspace_KDE: 1>, <Kerneltype.deltashift: 2>, <Kerneltype.dist_sens_via_mass_1: 3>]
like image 140
poke Avatar answered Oct 19 '22 06:10

poke


You should be defining your methods with the classmethod decorator as you are calling them from the class and not the Enum member.

@classmethod
def aslist(cls):
    return [cls.tube, cls.subspace_KDE, cls.deltashift, cls.dist_sens_via_mass_1]

@classmethod
def fromint(cls, int):
    return cls.aslist()[int]

As others have mentioned in comments, your aslist() method is not required and you can directly use list() on it and it by default preserves the order of definition. Only difference is that it doesn't return the aliases.

>>> list(Kerneltype)
[<Kerneltype.tube: 0>, <Kerneltype.subspace_KDE: 1>, <Kerneltype.deltashift: 2>, <Kerneltype.dist_sens_via_mass_1: 3>]
like image 35
Ashwini Chaudhary Avatar answered Oct 19 '22 06:10

Ashwini Chaudhary