use enum module instead or usertypes.enum

Remove the usertypes.enum from the source and use
the standard enum module instead.
Enum start number is available since python 3.5
This commit is contained in:
Gyorgy Orban 2017-10-23 11:42:28 +02:00
parent c0eae5d4e4
commit 98c6b49cde
19 changed files with 68 additions and 141 deletions

View File

@ -19,6 +19,7 @@
"""Base class for a wrapper over QWebView/QWebEngineView.""" """Base class for a wrapper over QWebView/QWebEngineView."""
import enum
import itertools import itertools
import attr import attr
@ -74,7 +75,7 @@ class UnsupportedOperationError(WebTabError):
"""Raised when an operation is not supported with the given backend.""" """Raised when an operation is not supported with the given backend."""
TerminationStatus = usertypes.enum('TerminationStatus', [ TerminationStatus = enum.Enum('TerminationStatus', [
'normal', 'normal',
'abnormal', # non-zero exit status 'abnormal', # non-zero exit status
'crashed', # e.g. segfault 'crashed', # e.g. segfault

View File

@ -27,6 +27,7 @@ import collections
import functools import functools
import pathlib import pathlib
import tempfile import tempfile
import enum
import sip import sip
from PyQt5.QtCore import (pyqtSlot, pyqtSignal, Qt, QObject, QModelIndex, from PyQt5.QtCore import (pyqtSlot, pyqtSignal, Qt, QObject, QModelIndex,
@ -38,8 +39,7 @@ from qutebrowser.utils import (usertypes, standarddir, utils, message, log,
qtutils) qtutils)
ModelRole = usertypes.enum('ModelRole', ['item'], start=Qt.UserRole, ModelRole = enum.IntEnum('ModelRole', ['item'], start=Qt.UserRole)
is_int=True)
# Remember the last used directory # Remember the last used directory

View File

@ -24,6 +24,7 @@ import functools
import math import math
import re import re
import html import html
import enum
from string import ascii_lowercase from string import ascii_lowercase
import attr import attr
@ -37,10 +38,9 @@ from qutebrowser.commands import userscripts, cmdexc, cmdutils, runners
from qutebrowser.utils import usertypes, log, qtutils, message, objreg, utils from qutebrowser.utils import usertypes, log, qtutils, message, objreg, utils
Target = usertypes.enum('Target', ['normal', 'current', 'tab', 'tab_fg', Target = enum.Enum('Target', ['normal', 'current', 'tab', 'tab_fg', 'tab_bg',
'tab_bg', 'window', 'yank', 'yank_primary', 'window', 'yank', 'yank_primary', 'run', 'fill',
'run', 'fill', 'hover', 'download', 'hover', 'download', 'userscript', 'spawn'])
'userscript', 'spawn'])
class HintingError(Exception): class HintingError(Exception):

View File

@ -24,6 +24,7 @@ Module attributes:
SELECTORS: CSS selectors for different groups of elements. SELECTORS: CSS selectors for different groups of elements.
""" """
import enum
import collections.abc import collections.abc
from PyQt5.QtCore import QUrl, Qt, QEvent, QTimer from PyQt5.QtCore import QUrl, Qt, QEvent, QTimer
@ -35,7 +36,7 @@ from qutebrowser.mainwindow import mainwindow
from qutebrowser.utils import log, usertypes, utils, qtutils, objreg from qutebrowser.utils import log, usertypes, utils, qtutils, objreg
Group = usertypes.enum('Group', ['all', 'links', 'images', 'url', 'inputs']) Group = enum.Enum('Group', ['all', 'links', 'images', 'url', 'inputs'])
SELECTORS = { SELECTORS = {

View File

@ -19,6 +19,7 @@
"""Base class for vim-like key sequence parser.""" """Base class for vim-like key sequence parser."""
import enum
import re import re
import unicodedata import unicodedata
@ -75,8 +76,8 @@ class BaseKeyParser(QObject):
do_log = True do_log = True
passthrough = False passthrough = False
Match = usertypes.enum('Match', ['partial', 'definitive', 'other', 'none']) Match = enum.Enum('Match', ['partial', 'definitive', 'other', 'none'])
Type = usertypes.enum('Type', ['chain', 'special']) Type = enum.Enum('Type', ['chain', 'special'])
def __init__(self, win_id, parent=None, supports_count=None, def __init__(self, win_id, parent=None, supports_count=None,
supports_chains=False): supports_chains=False):

View File

@ -24,6 +24,7 @@ Module attributes:
""" """
import traceback import traceback
import enum
from PyQt5.QtCore import pyqtSlot, Qt from PyQt5.QtCore import pyqtSlot, Qt
@ -34,7 +35,7 @@ from qutebrowser.utils import usertypes, log, message, objreg, utils
STARTCHARS = ":/?" STARTCHARS = ":/?"
LastPress = usertypes.enum('LastPress', ['none', 'filtertext', 'keystring']) LastPress = enum.Enum('LastPress', ['none', 'filtertext', 'keystring'])
class NormalKeyParser(keyparser.CommandKeyParser): class NormalKeyParser(keyparser.CommandKeyParser):

View File

@ -19,6 +19,7 @@
"""The main statusbar widget.""" """The main statusbar widget."""
import enum
import attr import attr
from PyQt5.QtCore import pyqtSignal, pyqtSlot, pyqtProperty, Qt, QSize, QTimer from PyQt5.QtCore import pyqtSignal, pyqtSlot, pyqtProperty, Qt, QSize, QTimer
from PyQt5.QtWidgets import QWidget, QHBoxLayout, QStackedLayout, QSizePolicy from PyQt5.QtWidgets import QWidget, QHBoxLayout, QStackedLayout, QSizePolicy
@ -46,7 +47,7 @@ class ColorFlags:
passthrough: If we're currently in passthrough-mode. passthrough: If we're currently in passthrough-mode.
""" """
CaretMode = usertypes.enum('CaretMode', ['off', 'on', 'selection']) CaretMode = enum.Enum('CaretMode', ['off', 'on', 'selection'])
prompt = attr.ib(False) prompt = attr.ib(False)
insert = attr.ib(False) insert = attr.ib(False)
command = attr.ib(False) command = attr.ib(False)

View File

@ -19,10 +19,12 @@
"""Text displayed in the statusbar.""" """Text displayed in the statusbar."""
import enum
from PyQt5.QtCore import pyqtSlot from PyQt5.QtCore import pyqtSlot
from qutebrowser.mainwindow.statusbar import textbase from qutebrowser.mainwindow.statusbar import textbase
from qutebrowser.utils import usertypes, log from qutebrowser.utils import log
class Text(textbase.TextBase): class Text(textbase.TextBase):
@ -37,7 +39,7 @@ class Text(textbase.TextBase):
available. If not, the permanent text is shown. available. If not, the permanent text is shown.
""" """
Text = usertypes.enum('Text', ['normal', 'temp']) Text = enum.Enum('Text', ['normal', 'temp'])
def __init__(self, parent=None): def __init__(self, parent=None):
super().__init__(parent) super().__init__(parent)

View File

@ -19,6 +19,8 @@
"""URL displayed in the statusbar.""" """URL displayed in the statusbar."""
import enum
from PyQt5.QtCore import pyqtSlot, pyqtProperty, Qt, QUrl from PyQt5.QtCore import pyqtSlot, pyqtProperty, Qt, QUrl
from qutebrowser.mainwindow.statusbar import textbase from qutebrowser.mainwindow.statusbar import textbase
@ -27,8 +29,8 @@ from qutebrowser.utils import usertypes, urlutils
# Note this has entries for success/error/warn from widgets.webview:LoadStatus # Note this has entries for success/error/warn from widgets.webview:LoadStatus
UrlType = usertypes.enum('UrlType', ['success', 'success_https', 'error', UrlType = enum.Enum('UrlType', ['success', 'success_https', 'error', 'warn',
'warn', 'hover', 'normal']) 'hover', 'normal'])
class UrlText(textbase.TextBase): class UrlText(textbase.TextBase):

View File

@ -20,6 +20,7 @@
"""The tab widget used for TabbedBrowser from browser.py.""" """The tab widget used for TabbedBrowser from browser.py."""
import functools import functools
import enum
import attr import attr
from PyQt5.QtCore import (pyqtSignal, pyqtSlot, Qt, QSize, QRect, QPoint, from PyQt5.QtCore import (pyqtSignal, pyqtSlot, Qt, QSize, QRect, QPoint,
@ -34,8 +35,8 @@ from qutebrowser.config import config
from qutebrowser.misc import objects from qutebrowser.misc import objects
PixelMetrics = usertypes.enum('PixelMetrics', ['icon_padding'], PixelMetrics = enum.IntEnum('PixelMetrics', ['icon_padding'],
start=QStyle.PM_CustomBase, is_int=True) start=QStyle.PM_CustomBase)
class TabWidget(QTabWidget): class TabWidget(QTabWidget):

View File

@ -25,6 +25,7 @@ import functools
import html import html
import ctypes import ctypes
import ctypes.util import ctypes.util
import enum
import attr import attr
from PyQt5.QtCore import Qt from PyQt5.QtCore import Qt
@ -37,10 +38,10 @@ from qutebrowser.utils import usertypes, objreg, version, qtutils, log, utils
from qutebrowser.misc import objects, msgbox from qutebrowser.misc import objects, msgbox
_Result = usertypes.enum( _Result = enum.IntEnum(
'_Result', '_Result',
['quit', 'restart', 'restart_webkit', 'restart_webengine'], ['quit', 'restart', 'restart_webkit', 'restart_webengine'],
is_int=True, start=QDialog.Accepted + 1) start=QDialog.Accepted + 1)
@attr.s @attr.s

View File

@ -27,6 +27,7 @@ import getpass
import fnmatch import fnmatch
import traceback import traceback
import datetime import datetime
import enum
import pkg_resources import pkg_resources
from PyQt5.QtCore import pyqtSlot, Qt, QSize from PyQt5.QtCore import pyqtSlot, Qt, QSize
@ -35,13 +36,13 @@ from PyQt5.QtWidgets import (QDialog, QLabel, QTextEdit, QPushButton,
QDialogButtonBox, QApplication, QMessageBox) QDialogButtonBox, QApplication, QMessageBox)
import qutebrowser import qutebrowser
from qutebrowser.utils import version, log, utils, objreg, usertypes from qutebrowser.utils import version, log, utils, objreg
from qutebrowser.misc import (miscwidgets, autoupdate, msgbox, httpclient, from qutebrowser.misc import (miscwidgets, autoupdate, msgbox, httpclient,
pastebin) pastebin)
from qutebrowser.config import config, configfiles from qutebrowser.config import config, configfiles
Result = usertypes.enum('Result', ['restore', 'no_restore'], is_int=True, Result = enum.IntEnum('Result', ['restore', 'no_restore'],
start=QDialog.Accepted + 1) start=QDialog.Accepted + 1)

View File

@ -24,9 +24,10 @@ import sys
import inspect import inspect
import os.path import os.path
import collections import collections
import enum
import qutebrowser import qutebrowser
from qutebrowser.utils import usertypes, log, utils from qutebrowser.utils import log, utils
def is_git_repo(): def is_git_repo():
@ -75,7 +76,7 @@ class DocstringParser:
arg_descs: A dict of argument names to their descriptions arg_descs: A dict of argument names to their descriptions
""" """
State = usertypes.enum('State', ['short', 'desc', 'desc_hidden', State = enum.Enum('State', ['short', 'desc', 'desc_hidden',
'arg_start', 'arg_inside', 'misc']) 'arg_start', 'arg_inside', 'misc'])
def __init__(self, func): def __init__(self, func):

View File

@ -24,17 +24,18 @@ import sys
import shutil import shutil
import os.path import os.path
import contextlib import contextlib
import enum
from PyQt5.QtCore import QStandardPaths from PyQt5.QtCore import QStandardPaths
from PyQt5.QtWidgets import QApplication from PyQt5.QtWidgets import QApplication
from qutebrowser.utils import log, debug, usertypes, message, utils from qutebrowser.utils import log, debug, message, utils
# The cached locations # The cached locations
_locations = {} _locations = {}
Location = usertypes.enum('Location', ['config', 'auto_config', Location = enum.Enum('Location', ['config', 'auto_config',
'data', 'system_data', 'data', 'system_data',
'cache', 'download', 'runtime']) 'cache', 'download', 'runtime'])

View File

@ -25,7 +25,7 @@ Module attributes:
import operator import operator
import collections.abc import collections.abc
import enum as pyenum import enum
from PyQt5.QtCore import pyqtSignal, pyqtSlot, QObject, QTimer from PyQt5.QtCore import pyqtSignal, pyqtSlot, QObject, QTimer
@ -35,22 +35,6 @@ from qutebrowser.utils import log, qtutils, utils
_UNSET = object() _UNSET = object()
def enum(name, items, start=1, is_int=False):
"""Factory for simple enumerations.
Args:
name: Name of the enum
items: Iterable of items to be sequentially enumerated.
start: The number to use for the first value.
We use 1 as default so enum members are always True.
is_init: True if the enum should be a Python IntEnum
"""
enums = [(v, i) for (i, v) in enumerate(items, start)]
base = pyenum.IntEnum if is_int else pyenum.Enum
base = pyenum.unique(base)
return base(name, enums)
class NeighborList(collections.abc.Sequence): class NeighborList(collections.abc.Sequence):
"""A list of items which saves its current position. """A list of items which saves its current position.
@ -65,7 +49,7 @@ class NeighborList(collections.abc.Sequence):
_mode: The current mode. _mode: The current mode.
""" """
Modes = enum('Modes', ['edge', 'exception']) Modes = enum.Enum('Modes', ['edge', 'exception'])
def __init__(self, items=None, default=_UNSET, mode=Modes.exception): def __init__(self, items=None, default=_UNSET, mode=Modes.exception):
"""Constructor. """Constructor.
@ -221,45 +205,46 @@ class NeighborList(collections.abc.Sequence):
# The mode of a Question. # The mode of a Question.
PromptMode = enum('PromptMode', ['yesno', 'text', 'user_pwd', 'alert', PromptMode = enum.Enum('PromptMode', ['yesno', 'text', 'user_pwd', 'alert',
'download']) 'download'])
# Where to open a clicked link. # Where to open a clicked link.
ClickTarget = enum('ClickTarget', ['normal', 'tab', 'tab_bg', 'window', ClickTarget = enum.Enum('ClickTarget', ['normal', 'tab', 'tab_bg', 'window',
'hover']) 'hover'])
# Key input modes # Key input modes
KeyMode = enum('KeyMode', ['normal', 'hint', 'command', 'yesno', 'prompt', KeyMode = enum.Enum('KeyMode', ['normal', 'hint', 'command', 'yesno', 'prompt',
'insert', 'passthrough', 'caret', 'set_mark', 'insert', 'passthrough', 'caret', 'set_mark',
'jump_mark', 'record_macro', 'run_macro']) 'jump_mark', 'record_macro', 'run_macro'])
# Exit statuses for errors. Needs to be an int for sys.exit. # Exit statuses for errors. Needs to be an int for sys.exit.
Exit = enum('Exit', ['ok', 'reserved', 'exception', 'err_ipc', 'err_init', Exit = enum.IntEnum('Exit', ['ok', 'reserved', 'exception', 'err_ipc',
'err_config', 'err_key_config'], is_int=True, start=0) 'err_init', 'err_config', 'err_key_config'],
start=0)
# Load status of a tab # Load status of a tab
LoadStatus = enum('LoadStatus', ['none', 'success', 'success_https', 'error', LoadStatus = enum.Enum('LoadStatus', ['none', 'success', 'success_https',
'warn', 'loading']) 'error', 'warn', 'loading'])
# Backend of a tab # Backend of a tab
Backend = enum('Backend', ['QtWebKit', 'QtWebEngine']) Backend = enum.Enum('Backend', ['QtWebKit', 'QtWebEngine'])
# JS world for QtWebEngine # JS world for QtWebEngine
JsWorld = enum('JsWorld', ['main', 'application', 'user', 'jseval']) JsWorld = enum.Enum('JsWorld', ['main', 'application', 'user', 'jseval'])
# Log level of a JS message. This needs to match up with the keys allowed for # Log level of a JS message. This needs to match up with the keys allowed for
# the content.javascript.log setting. # the content.javascript.log setting.
JsLogLevel = enum('JsLogLevel', ['unknown', 'info', 'warning', 'error']) JsLogLevel = enum.Enum('JsLogLevel', ['unknown', 'info', 'warning', 'error'])
MessageLevel = enum('MessageLevel', ['error', 'warning', 'info']) MessageLevel = enum.Enum('MessageLevel', ['error', 'warning', 'info'])
class Question(QObject): class Question(QObject):

View File

@ -27,6 +27,7 @@ import platform
import subprocess import subprocess
import importlib import importlib
import collections import collections
import enum
import pkg_resources import pkg_resources
import attr import attr
@ -63,7 +64,7 @@ class DistributionInfo:
pretty = attr.ib() pretty = attr.ib()
Distribution = usertypes.enum( Distribution = enum.Enum(
'Distribution', ['unknown', 'ubuntu', 'debian', 'void', 'arch', 'Distribution', ['unknown', 'ubuntu', 'debian', 'void', 'arch',
'gentoo', 'fedora', 'opensuse', 'linuxmint', 'manjaro']) 'gentoo', 'fedora', 'opensuse', 'linuxmint', 'manjaro'])

View File

@ -20,15 +20,15 @@
"""Tests for qutebrowser.commands.argparser.""" """Tests for qutebrowser.commands.argparser."""
import inspect import inspect
import enum
import pytest import pytest
from PyQt5.QtCore import QUrl from PyQt5.QtCore import QUrl
from qutebrowser.commands import argparser, cmdexc from qutebrowser.commands import argparser, cmdexc
from qutebrowser.utils import usertypes
Enum = usertypes.enum('Enum', ['foo', 'foo_bar']) Enum = enum.Enum('Enum', ['foo', 'foo_bar'])
class TestArgumentParser: class TestArgumentParser:

View File

@ -25,6 +25,7 @@ import sys
import logging import logging
import types import types
import typing import typing
import enum
import pytest import pytest
@ -243,7 +244,7 @@ class TestRegister:
else: else:
assert pos_args == [('arg', 'arg')] assert pos_args == [('arg', 'arg')]
Enum = usertypes.enum('Test', ['x', 'y']) Enum = enum.Enum('Test', ['x', 'y'])
@pytest.mark.parametrize('typ, inp, choices, expected', [ @pytest.mark.parametrize('typ, inp, choices, expected', [
(int, '42', None, 42), (int, '42', None, 42),

View File

@ -1,74 +0,0 @@
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2014-2017 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
#
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# qutebrowser is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with qutebrowser. If not, see <http://www.gnu.org/licenses/>.
"""Tests for the Enum class."""
from qutebrowser.utils import usertypes
import pytest
@pytest.fixture
def enum():
return usertypes.enum('Enum', ['one', 'two'])
def test_values(enum):
"""Test if enum members resolve to the right values."""
assert enum.one.value == 1
assert enum.two.value == 2
def test_name(enum):
"""Test .name mapping."""
assert enum.one.name == 'one'
assert enum.two.name == 'two'
def test_unknown(enum):
"""Test invalid values which should raise an AttributeError."""
with pytest.raises(AttributeError):
_ = enum.three # flake8: disable=F841
def test_start():
"""Test the start= argument."""
e = usertypes.enum('Enum', ['three', 'four'], start=3)
assert e.three.value == 3
assert e.four.value == 4
def test_exit():
"""Make sure the exit status enum is correct."""
assert usertypes.Exit.ok == 0
assert usertypes.Exit.reserved == 1
def test_is_int():
"""Test the is_int argument."""
int_enum = usertypes.enum('Enum', ['item'], is_int=True)
no_int_enum = usertypes.enum('Enum', ['item'])
assert isinstance(int_enum.item, int)
assert not isinstance(no_int_enum.item, int)
def test_unique():
"""Make sure elements need to be unique."""
with pytest.raises(TypeError):
usertypes.enum('Enum', ['item', 'item'])