Skip to content

Commit

Permalink
Merge pull request #260 from ales-erjavec/remove-pkg-resources
Browse files Browse the repository at this point in the history
[ENH] Remove use of pkg_resources
  • Loading branch information
PrimozGodec authored Dec 14, 2023
2 parents 74f4e41 + 1da86a2 commit ea24f52
Show file tree
Hide file tree
Showing 10 changed files with 44 additions and 52 deletions.
4 changes: 2 additions & 2 deletions doc/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@
import os
import shlex

import pkg_resources
dist = pkg_resources.get_distribution("orange-widget-base")
from importlib.metadata import distribution
dist = distribution("orange-widget-base")

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
Expand Down
15 changes: 11 additions & 4 deletions orangewidget/gui.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,6 @@
from types import LambdaType
from collections import defaultdict

import pkg_resources

from AnyQt import QtWidgets, QtCore, QtGui
from AnyQt.QtCore import Qt, QEvent, QObject, QTimer, pyqtSignal as Signal
from AnyQt.QtGui import QCursor, QColor
Expand All @@ -30,6 +28,12 @@
from orangewidget.utils.itemdelegates import text_color_for_state
from orangewidget.utils.itemmodels import PyListModel, signal_blocking


try:
from importlib.resources import files as _resources_files
except ImportError:
from importlib_resources import files as _resources_files

__re_label = re.compile(r"(^|[^%])%\((?P<value>[a-zA-Z]\w*)\)")

log = logging.getLogger(__name__)
Expand Down Expand Up @@ -102,11 +106,14 @@ def sizeHint(self, option, index):
return super().sizeHint(option, index)


def resource_filename(path):
def resource_filename(path: str) -> str: # pragma: no cover
"""
Return a resource filename (package data) for path.
"""
return pkg_resources.resource_filename(__name__, path)
warnings.warn(
"'resource_filename' is deprecated.", DeprecationWarning, stacklevel=2
)
return str(_resources_files(__package__).joinpath(path))


class OWComponent:
Expand Down
24 changes: 9 additions & 15 deletions orangewidget/report/owreport.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,12 @@
import traceback
import warnings
import pickle
import pkgutil
from collections import OrderedDict
from enum import IntEnum

from typing import Optional

import pkg_resources

from AnyQt.QtCore import Qt, QObject, pyqtSlot, QSize
from AnyQt.QtGui import QIcon, QCursor, QStandardItemModel, QStandardItem
from AnyQt.QtWidgets import (
Expand All @@ -20,6 +19,7 @@


from orangewidget import gui
from orangewidget.utils import load_styled_icon
from orangewidget.widget import OWBaseWidget
from orangewidget.settings import Setting

Expand Down Expand Up @@ -51,12 +51,9 @@ def __init__(self, name, html, scheme, module, icon_name, comment=""):
self.icon_name = icon_name
self.comment = comment
try:
path = pkg_resources.resource_filename(module, icon_name)
except ImportError:
path = ""
except ValueError:
path = ""
icon = QIcon(path)
icon = load_styled_icon(module, icon_name)
except (ImportError, FileNotFoundError):
icon = QIcon()
self.id = id(icon)
super().__init__(icon, name)

Expand Down Expand Up @@ -93,10 +90,8 @@ def _icon_item(tooltip):
class ReportTable(QTableView):
def __init__(self, parent):
super().__init__(parent)
self._icon_remove = QIcon(pkg_resources.resource_filename(
__name__, "icons/delete.svg"))
self._icon_scheme = QIcon(pkg_resources.resource_filename(
__name__, "icons/scheme.svg"))
self._icon_remove = load_styled_icon(__package__, "icons/delete.svg")
self._icon_scheme = load_styled_icon(__package__, "icons/scheme.svg")

def mouseMoveEvent(self, event):
self._clear_icons()
Expand Down Expand Up @@ -139,9 +134,8 @@ def __init__(self):
self.report_changed = False
self.have_report_warning_shown = False

index_file = pkg_resources.resource_filename(__name__, "index.html")
with open(index_file, "r") as f:
self.report_html_template = f.read()
index_file = pkgutil.get_data(__name__, "index.html")
self.report_html_template = index_file.decode("utf-8")

def _setup_ui_(self):
self.table_model = ReportItemModel(0, len(Column.__members__))
Expand Down
11 changes: 9 additions & 2 deletions orangewidget/utils/__init__.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import enum
import inspect
from typing import Union, Iterator, Optional

import pkgutil
import sys
import warnings
from operator import attrgetter
from typing import Union, Iterator, Optional

from AnyQt.QtCore import QObject, QRect, QSize, QPoint, QTextBoundaryFinder
from AnyQt.QtGui import QIcon

from orangecanvas.gui.svgiconengine import StyledSvgIconEngine


def progress_bar_milestones(count, iterations=100):
Expand Down Expand Up @@ -195,3 +198,7 @@ def grapheme_slice(text: str, start: int = 0, end: int = None) -> str:
if slice_end is None:
slice_end = len(text)
return text[slice_start: slice_end]


def load_styled_icon(package: str, path: str) -> QIcon:
return QIcon(StyledSvgIconEngine(pkgutil.get_data(package, path)))
4 changes: 0 additions & 4 deletions orangewidget/utils/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@

from AnyQt.QtWidgets import QStyle, QSizePolicy

from orangewidget import gui
from orangewidget.utils.messagewidget import MessagesWidget


Expand Down Expand Up @@ -323,21 +322,18 @@ class WidgetMessagesMixin(MessagesMixin):
class Error(MessageGroup):
"""Base class for groups of error messages in widgets"""
severity = 3
icon_path = gui.resource_filename("icons/error.png")
bar_background = "#ffc6c6"
bar_icon = QStyle.SP_MessageBoxCritical

class Warning(MessageGroup):
"""Base class for groups of warning messages in widgets"""
severity = 2
icon_path = gui.resource_filename("icons/warning.png")
bar_background = "#ffffc9"
bar_icon = QStyle.SP_MessageBoxWarning

class Information(MessageGroup):
"""Base class for groups of information messages in widgets"""
severity = 1
icon_path = gui.resource_filename("icons/information.png")
bar_background = "#ceceff"
bar_icon = QStyle.SP_MessageBoxInformation

Expand Down
4 changes: 2 additions & 2 deletions orangewidget/widget.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@
from orangewidget.gui import OWComponent, VerticalScrollArea
from orangewidget.io import ClipboardFormat, ImgFormat
from orangewidget.settings import SettingsHandler
from orangewidget.utils import saveplot, getdeepattr
from orangewidget.utils import saveplot, getdeepattr, load_styled_icon
from orangewidget.utils.messagewidget import InOutStateWidget
from orangewidget.utils.progressbar import ProgressBarMixin
from orangewidget.utils.messages import (
Expand All @@ -60,7 +60,7 @@


def _load_styled_icon(name):
return QIcon(StyledSvgIconEngine(pkgutil.get_data(__name__, "icons/" + name)))
return load_styled_icon(__package__, "icons/" + name)


class Message:
Expand Down
20 changes: 4 additions & 16 deletions orangewidget/workflow/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@
import itertools
from typing import Dict, Any, Optional, Iterable, List

import pkg_resources
import requests

from AnyQt.QtCore import QStandardPaths, QCoreApplication

from orangecanvas import config
from orangecanvas.utils.pkgmeta import entry_points, EntryPoint


# generated from biolab/orange3-addons repository
Expand All @@ -39,7 +39,7 @@ def widgets_entry_points():
Return an `EntryPoint` iterator for all registered 'orange.widgets'
entry points.
"""
return pkg_resources.iter_entry_points(WIDGETS_ENTRY)
return entry_points(group=WIDGETS_ENTRY)

@staticmethod
def addon_entry_points():
Expand Down Expand Up @@ -70,23 +70,11 @@ def core_packages():

@staticmethod
def examples_entry_points():
# type: () -> Iterable[pkg_resources.EntryPoint]
# type: () -> Iterable[EntryPoint]
"""
Return an iterator over the entry points yielding 'Example Workflows'
"""
# `iter_entry_points` yields them in unspecified order, so we insert
# our first
try:
default_ep = (pkg_resources.EntryPoint(
"Orange3", "Orange.canvas.workflows",
dist=pkg_resources.get_distribution("Orange3")),)
except pkg_resources.DistributionNotFound:
default_ep = tuple()

return itertools.chain(
default_ep,
pkg_resources.iter_entry_points("orange.widgets.tutorials")
)
return entry_points(group="orange.widgets.tutorials")

@staticmethod
def widget_discovery(*args, **kwargs):
Expand Down
2 changes: 1 addition & 1 deletion orangewidget/workflow/discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,6 @@ def widget_description(self, module, widget_name=None, category_name=None,
desc.category = category_name

if distribution is not None:
desc.project_name = distribution.project_name
desc.project_name = distribution.name

return desc
7 changes: 3 additions & 4 deletions orangewidget/workflow/errorreporting.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@
from urllib.request import pathname2url, urlopen, build_opener
from urllib.error import URLError
from unittest.mock import patch

import pkg_resources
from importlib.metadata import distributions

from AnyQt.QtCore import pyqtSlot, QSettings, Qt
from AnyQt.QtGui import QDesktopServices, QFont
Expand All @@ -35,8 +34,8 @@


def get_installed_distributions():
for dist in pkg_resources.working_set: # type: pkg_resources.Distribution
name = dist.project_name
for dist in distributions():
name = dist.name
try:
version = dist.version
except ValueError:
Expand Down
5 changes: 3 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,9 @@
"pyqtgraph",
"AnyQt>=0.1.0",
"typing_extensions>=3.7.4.3",
"orange-canvas-core>=0.1.30,<0.2a",
'appnope; sys_platform=="darwin"'
"orange-canvas-core>=0.2a.dev0,<0.3a",
'appnope; sys_platform=="darwin"',
"importlib_resources; python_version<'3.10'"
]

EXTRAS_REQUIRE = {
Expand Down

0 comments on commit ea24f52

Please sign in to comment.