Use a metaclass for Enums for easier reverse mapping

This commit is contained in:
Florian Bruhin 2014-05-05 10:08:06 +02:00
parent 4ebe643ea6
commit 9cf713cbe4
2 changed files with 14 additions and 5 deletions

View File

@ -226,7 +226,7 @@ class HintManager(QObject):
target = Target.bgtab
else:
target = self._target
self.set_open_target.emit(Target.reverse_mapping[target])
self.set_open_target.emit(Target[target])
point = elem.geometry().topLeft()
scrollpos = self._frame.scrollPosition()
logging.debug("Clicking on \"{}\" at {}/{} - {}/{}".format(

View File

@ -27,7 +27,6 @@ _UNSET = object()
def enum(*items, **named):
"""Factory for simple enumerations.
We really don't need more complex things here, so we don't use python3.4's
@ -40,9 +39,19 @@ def enum(*items, **named):
**named: Items to have a given position/number.
"""
enums = dict(zip(items, range(len(items))), **named)
reverse = dict((v, k) for k, v in enums.items())
enums['reverse_mapping'] = reverse
return type('Enum', (), enums)
return EnumBase('Enum', (), enums)
class EnumBase(type):
"""Metaclass for enums to provide __getitem__ for reverse mapping."""
def __init__(cls, name, base, fields):
super().__init__(name, base, fields)
cls._mapping = dict((v, k) for k, v in fields.items())
def __getitem__(cls, key):
return cls._mapping[key]
class NeighborList: