From 9cf713cbe48b2e1c71a5a06c1bb7b5599ca835d5 Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Mon, 5 May 2014 10:08:06 +0200 Subject: [PATCH] Use a metaclass for Enums for easier reverse mapping --- qutebrowser/browser/hints.py | 2 +- qutebrowser/utils/usertypes.py | 17 +++++++++++++---- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/qutebrowser/browser/hints.py b/qutebrowser/browser/hints.py index a30f9e179..cb0246691 100644 --- a/qutebrowser/browser/hints.py +++ b/qutebrowser/browser/hints.py @@ -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( diff --git a/qutebrowser/utils/usertypes.py b/qutebrowser/utils/usertypes.py index 407817dba..a67a24e49 100644 --- a/qutebrowser/utils/usertypes.py +++ b/qutebrowser/utils/usertypes.py @@ -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: