I know of base classes Enum
and IntEnum
. Both are very helpful but I miss features for flag operations. I don't expect that these two classes implement my wished feature.
Let's construct an example:
class NetlistKind(IntEnum):
Unknown = 0
LatticeNetlist = 1
QuartusNetlist = 2
XSTNetlist = 4
CoreGenNetlist = 8
All = 15
As you can see, I'm already using IntEnum
to get arithmetic features for this enum. It would be nice to have something like @unique
to ensure all values are a power of two. I can do this by forking enum.unique for my needs. (I'm aware that All
is an exception from that rule.)
How is such an enum used?
filter = NetlistKind.LatticeNetlist | NetlistKind.QuartusNetlist
Thanks to the underlaying int bit operations are possible and filter has an internal value of 3.
If would be nice to have a "is flag X set in filter Y" function or even better an operator. I add a magic function for x in y
:
@unique
class NetlistKind(IntEnum):
Unknown = 0
LatticeNetlist = 1
QuartusNetlist = 2
XSTNetlist = 4
CoreGenNetlist = 8
All = 15
def __contains__(self, item):
return (self.value & item.value) == item.value
Usage example:
....
def GetNetlists(self, filter=NetlistKind.All):
for entity in self._entities:
for nl in entity.GetNetlists():
if (nl.kind in filter):
yield nl
def GetXilinxNetlists(self):
return self.GetNetlists(NetlistKind.XSTNetlist | NetlistKind.CoreGenNetlist)
So the questions are:
- Are there better ways to implement bit fields?
- Are thete better ways to implement such an 1-D filter? I don't want to use lamdas for such a simple filter condition?
- Is such solution already included in the Python standard library?
- How to add this enum extension to the next Python version? :)
Open features:
- return a list of all active flags in
__str__
- ...?
TextStyle('TextStyle.bold')
. I thinkbold
is enough, because the namespace is already restricted toTextStyle
, because you pass it into its constructor.str()
of the enum can be used in other context not only in case of serialization, this is why__str__
returns fqdn. I thinkstr()
should be interpretable even without the flags class in context. Actually for the purpose of custom serialization I've provided ato_simple_str()
besides the standard__str__
. In this caseto_simple_str()
would emit simply'bold'
andTextStyle('bold')
would also work. Actually the pickle serializer support of flags saves only the flags class name and the output ofto_simple_str()
.str()
. I had the idea of returning a non-fqdn fromstr()
and returning fqdn only as part ofrepr()
and maybe with a utility function but finally I decided to go with fqdn to behave the same way as thestr()
of the standardenum
module.