How to return enum from property in enum

Viewed 58

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'>
# I want this to be <enum 'Letters'> instead

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

1 Answers

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))
Related