I sincerely hope, that I followed all the rules and guidelines and that my question/problem is comprehensive enough to find an adequate answer. First, a small intro:
For a current project of mine I want to designate specific types to tree node objects. To keep matters simple here, I will use colours as an analogy.
What I have
Let's suppose I have the following enum, derived from the enum standard library:
from enum import Enum, auto
class Colour(Enum):
CRIMSON = auto()
SCARLET = auto()
RED = auto()
BLUE = auto()
So each member has a different value.
What I want
So far, so good. But what I would like to have is this:
class Colour(Enum):
CRIMSON = auto()
SCARLET = auto()
# RED = CRIMSON or SCARLET
BLUE = auto()
So if I have an object with an attribute like this:
>>> r = Colour.SCARLET
I want the following statements to return True:
>>> type(r) is Colour
True
>>> r is Colour.SCARLET
True
>>> r is Colour.RED
True
and of course this should be False:
>>> r is Colour.CRIMSON
False
>>> r is Colour.BLUE # obviously False...
False
Note that it is not neccessary in my case to be able to assign the type RED, only assigning CRIMSON or SCARLET would be sufficient.
My current (unsatisfying) solution
What I tried so far is the following:
class Colour(Enum):
# ... member definitions ...
def isRed(self):
return self is Colour.SCARLET or self is Colour.CRIMSON
But I find this solution rather inelegant and quite a hassle to use. Also it does not reflect the nature of CRIMSON and SCARLET as shades of RED.
Another solution I implemented involved subcalssing or nesting Colour but in either case I was not able to meet all the criteria above, hence I refrained from posting these here.
Before I used enums, I represented the Node.colour property for each node with integers:
# trees.py
# defining global constants
SCARLET = 1
CRIMSON = 2
BLUE = -1
class Node:
def __init__(self, parent, children, col):
self.parent = parent
self.children = children
self.colour = col # either 1, 2 or -1
So I could do the following:
>>> x = Node(None, None, SCARLET)
>>> y = Node(None, None, BLUE)
>>> If x.colour is > 0:# do stuff...
but I found that way very unpythonic and rather unintutive as well, since testing for RED, SCARLET, BLUE etc. occurs rather often and this makes the code somewhat harder to read.
Also one should not use int data-type if not necessary in my opinion since these "colours" have no natural ordering or other int-like properties.