[SOLVED] How to return enum from property in enum

Issue

This Content is from Stack Overflow. Question asked by Christian Pojoni

I have an enum with a set as value for the items. In a property method I would like to return an intersection of the previous chained enum. But the result type of the property should be the same enum class.

Given this abstract example

from enum import Enum


class Letters(Enum):
    abc = {'a', 'b', 'c'}

    @property
    def a(self):
        """ Returns a subset of a Letters Enum """
        letter = {'a'}
        return letter.intersection(self.value)

The type of an Item is an enum of Letters, which is correct

print(type(Letters.abc))
# prints <enum 'Letters'>

But when I call the property of the resulting enum, it is of type set

print(type(Letters.abc.a))
# prints <class 'set'>

How can I change the code so that the property returns a value of type enum?



Solution

How can I change the code so that the property returns a value of type enum?

Using ‘Enum’, the only way would be to having members for all possible combinations:

class Letters(Enum):
    abc = {'a', 'b', 'c'}
    a = {'a'}
    ab = {'ab'}
    ac = {'ac'}
    # etc.

and then return the correct member in the property:

return self.__class__(letter.intersection(self.value))


This Question was asked in StackOverflow by Christian Pojoni and Answered by Ethan Furman It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?