diff --git a/EDMCLogging.py b/EDMCLogging.py index 201648a2..a05ad107 100644 --- a/EDMCLogging.py +++ b/EDMCLogging.py @@ -193,7 +193,7 @@ class Logger: self.logger_channel_rotating.setFormatter(self.logger_formatter) self.logger.addHandler(self.logger_channel_rotating) - def get_logger(self) -> 'LoggerMixin': + def get_logger(self) -> LoggerMixin: """ Obtain the self.logger of the class instance. @@ -232,7 +232,7 @@ class Logger: logger.trace("Not changing log level because it's TRACE") # type: ignore -def get_plugin_logger(plugin_name: str, loglevel: int = _default_loglevel) -> 'LoggerMixin': +def get_plugin_logger(plugin_name: str, loglevel: int = _default_loglevel) -> LoggerMixin: """ Return a logger suitable for a plugin. @@ -352,7 +352,7 @@ class EDMCContextFilter(logging.Filter): try: args, _, _, value_dict = inspect.getargvalues(frame) if len(args) and args[0] in ('self', 'cls'): - frame_class: 'object' = value_dict[args[0]] + frame_class: object = value_dict[args[0]] if frame_class: # See https://en.wikipedia.org/wiki/Name_mangling#Python for how name mangling works. @@ -450,7 +450,7 @@ class EDMCContextFilter(logging.Filter): # Go up through stack frames until we find the first with a # type(f_locals.self) of logging.Logger. This should be the start # of the frames internal to logging. - frame: 'FrameType' = getframe(0) + frame: FrameType = getframe(0) while frame: if isinstance(frame.f_locals.get('self'), logging.Logger): frame = cast('FrameType', frame.f_back) # Want to start on the next frame below @@ -518,7 +518,7 @@ class EDMCContextFilter(logging.Filter): return module_name -def get_main_logger(sublogger_name: str = '') -> 'LoggerMixin': +def get_main_logger(sublogger_name: str = '') -> LoggerMixin: """Return the correct logger for how the program is being run.""" if not os.getenv("EDMC_NO_UI"): # GUI app being run @@ -537,4 +537,4 @@ base_logger_name = appcmdname if os.getenv('EDMC_NO_UI') else appname edmclogger = Logger(base_logger_name, loglevel=loglevel) for h in config_logger.handlers[:]: config_logger.removeHandler(h) -logger: 'LoggerMixin' = edmclogger.get_logger() +logger: LoggerMixin = edmclogger.get_logger() diff --git a/EDMarketConnector.py b/EDMarketConnector.py index 122a19dc..762afd41 100644 --- a/EDMarketConnector.py +++ b/EDMarketConnector.py @@ -54,7 +54,7 @@ if __name__ == '__main__': log_file_path.mkdir(exist_ok=True) log_file_path /= f'{appname}.log' - sys.stdout = sys.stderr = open(log_file_path, mode='wt', buffering=1) # Do NOT use WITH here. + sys.stdout = sys.stderr = open(log_file_path, mode='w', buffering=1) # Do NOT use WITH here. # TODO: Test: Make *sure* this redirect is working, else py2exe is going to cause an exit popup @@ -216,7 +216,7 @@ if __name__ == '__main__': # noqa: C901 if args.capi_use_debug_access_token: import config as conf_module - with open(conf_module.config.app_dir_path / 'access_token.txt', 'r') as at: + with open(conf_module.config.app_dir_path / 'access_token.txt') as at: conf_module.capi_debug_access_token = at.readline().strip() level_to_set: int | None = None @@ -476,7 +476,7 @@ class AppWindow: if sys.platform == 'win32' and not bool(config.get_int('no_systray')): from simplesystray import SysTrayIcon - def open_window(systray: 'SysTrayIcon', *args) -> None: + def open_window(systray: SysTrayIcon, *args) -> None: self.w.deiconify() logfile_loc = pathlib.Path(config.app_dir_path / 'logs') @@ -953,7 +953,7 @@ class AppWindow: self.cooldown() - def export_market_data(self, data: 'CAPIData') -> bool: # noqa: CCR001 + def export_market_data(self, data: CAPIData) -> bool: # noqa: CCR001 """ Export CAPI market data. @@ -1872,7 +1872,7 @@ class AppWindow: h.write(str(companion.session.capi_raw_data).encode(encoding='utf-8')) if sys.platform == 'win32': - def exit_tray(self, systray: 'SysTrayIcon') -> None: + def exit_tray(self, systray: SysTrayIcon) -> None: """Tray icon is shutting down.""" exit_thread = threading.Thread( target=self.onexit, diff --git a/companion.py b/companion.py index 19f12a14..2c920144 100644 --- a/companion.py +++ b/companion.py @@ -29,7 +29,8 @@ import webbrowser from email.utils import parsedate from pathlib import Path from queue import Queue -from typing import TYPE_CHECKING, Any, Mapping, TypeVar +from typing import TYPE_CHECKING, Any, TypeVar +from collections.abc import Mapping import requests import config as conf_module import killswitch @@ -69,7 +70,7 @@ class CAPIData(UserDict): def __init__( self, - data: str | dict[str, Any] | 'CAPIData' | None = None, + data: str | dict[str, Any] | CAPIData | None = None, source_host: str | None = None, source_endpoint: str | None = None, request_cmdr: str | None = None @@ -1204,7 +1205,7 @@ def fixup(data: CAPIData) -> CAPIData: # noqa: C901, CCR001 # Can't be usefully if not (config.app_dir_path / 'FDevIDs' / f).is_file(): logger.warning(f'FDevID file {f} not found! Generating output without these commodity name rewrites.') continue - with open(config.app_dir_path / 'FDevIDs' / f, 'r') as csvfile: + with open(config.app_dir_path / 'FDevIDs' / f) as csvfile: reader = csv.DictReader(csvfile) for row in reader: @@ -1325,7 +1326,7 @@ def index_possibly_sparse_list(data: Mapping[str, V] | list[V], key: int) -> V: if isinstance(data, list): return data[key] - if isinstance(data, (dict, dict)): + if isinstance(data, dict): return data[str(key)] raise ValueError(f'Unexpected data type {type(data)}') diff --git a/config/__init__.py b/config/__init__.py index 3fe9a255..3892f3c7 100644 --- a/config/__init__.py +++ b/config/__init__.py @@ -43,7 +43,8 @@ import sys import tomllib import tomli_w from time import gmtime -from typing import Any, Callable, Type, TypeVar +from typing import Any, TypeVar +from collections.abc import Callable import semantic_version from constants import GITVERSION_FILE, applongname, appname @@ -474,7 +475,7 @@ class Config: @staticmethod def _suppress_call( func: Callable[..., _T], - exceptions: Type[BaseException] | list[Type[BaseException]] = Exception, + exceptions: type[BaseException] | list[type[BaseException]] = Exception, *args: Any, **kwargs: Any, ) -> _T | None: diff --git a/config/linux.py b/config/linux.py index 1b5ac924..9fba0ef0 100644 --- a/config/linux.py +++ b/config/linux.py @@ -12,7 +12,7 @@ import sys from config import config_logger if sys.platform != "linux": - raise EnvironmentError("This file is for Linux only.") + raise OSError("This file is for Linux only.") import pathlib diff --git a/config/windows.py b/config/windows.py index 6789bc4e..0f01e681 100644 --- a/config/windows.py +++ b/config/windows.py @@ -21,7 +21,7 @@ if TYPE_CHECKING: from . import Config if sys.platform != "win32": - raise EnvironmentError("This file is for Windows only.") + raise OSError("This file is for Windows only.") REG_RESERVED_ALWAYS_ZERO = 0 diff --git a/debug_webserver.py b/debug_webserver.py index c4be2be3..545e62bd 100644 --- a/debug_webserver.py +++ b/debug_webserver.py @@ -7,7 +7,8 @@ import pathlib import threading import zlib from http import server -from typing import Any, Callable, Literal +from typing import Any, Literal +from collections.abc import Callable from urllib.parse import parse_qs from config import config from EDMCLogging import get_main_logger diff --git a/edshipyard.py b/edshipyard.py index f7bceb75..e1c14e23 100644 --- a/edshipyard.py +++ b/edshipyard.py @@ -189,7 +189,7 @@ def export(data, filename=None) -> None: # noqa: C901, CCR001 raise if filename: - with open(filename, 'wt') as h: + with open(filename, 'w') as h: h.write(string) return @@ -206,5 +206,5 @@ def export(data, filename=None) -> None: # noqa: C901, CCR001 timestamp = time.strftime('%Y-%m-%dT%H.%M.%S', time.localtime(querytime)) filename = pathlib.Path(config.get_str('outdir')) / f'{ship}.{timestamp}.txt' - with open(filename, 'wt') as h: + with open(filename, 'w') as h: h.write(string) diff --git a/hotkey/linux.py b/hotkey/linux.py index 7e4b9862..33e9cd7e 100644 --- a/hotkey/linux.py +++ b/hotkey/linux.py @@ -6,7 +6,7 @@ from EDMCLogging import get_main_logger from hotkey import AbstractHotkeyMgr if sys.platform != 'linux': - raise EnvironmentError("This file is for Linux only.") + raise OSError("This file is for Linux only.") logger = get_main_logger() diff --git a/hotkey/windows.py b/hotkey/windows.py index b292e7a7..9d32edaa 100644 --- a/hotkey/windows.py +++ b/hotkey/windows.py @@ -16,7 +16,7 @@ from EDMCLogging import get_main_logger from hotkey import AbstractHotkeyMgr if sys.platform != 'win32': - raise EnvironmentError("This file is for Windows only.") + raise OSError("This file is for Windows only.") logger = get_main_logger() diff --git a/journal_lock.py b/journal_lock.py index 3e16b309..8d90314e 100644 --- a/journal_lock.py +++ b/journal_lock.py @@ -13,7 +13,7 @@ import tkinter as tk from enum import Enum from os import getpid as os_getpid from tkinter import ttk -from typing import Callable +from collections.abc import Callable from l10n import translations as tr from config import config from EDMCLogging import get_main_logger diff --git a/killswitch.py b/killswitch.py index 22a40049..bec23ba8 100644 --- a/killswitch.py +++ b/killswitch.py @@ -11,9 +11,10 @@ import json import threading from copy import deepcopy from typing import ( - TYPE_CHECKING, Any, Callable, Mapping, MutableMapping, MutableSequence, NamedTuple, Sequence, + TYPE_CHECKING, Any, NamedTuple, TypedDict, TypeVar, cast, Union ) +from collections.abc import Callable, Mapping, MutableMapping, MutableSequence, Sequence import requests import semantic_version from semantic_version.base import Version @@ -217,7 +218,7 @@ class KillSwitchSet: def __init__(self, kill_switches: list[KillSwitches]) -> None: self.kill_switches = kill_switches - def get_disabled(self, id: str, *, version: Union[Version, str] = _current_version) -> DisabledResult: + def get_disabled(self, id: str, *, version: Version | str = _current_version) -> DisabledResult: """ Return whether the given feature ID is disabled by a killswitch for the given version. diff --git a/l10n.py b/l10n.py index 57c8651b..48197592 100755 --- a/l10n.py +++ b/l10n.py @@ -16,7 +16,8 @@ import re import sys from contextlib import suppress from os import listdir, sep -from typing import Iterable, TextIO, cast +from typing import TextIO, cast +from collections.abc import Iterable import pathlib from config import config from EDMCLogging import get_main_logger diff --git a/loadout.py b/loadout.py index 144439c0..c465cdbd 100644 --- a/loadout.py +++ b/loadout.py @@ -33,7 +33,7 @@ def export(data: companion.CAPIData, requested_filename: str | None = None) -> N ) # pretty print if requested_filename is not None and requested_filename: - with open(requested_filename, 'wt') as h: + with open(requested_filename, 'w') as h: h.write(string) return if not requested_filename: @@ -45,7 +45,7 @@ def export(data: companion.CAPIData, requested_filename: str | None = None) -> N regexp = re.compile(re.escape(ship) + r'\.\d\d\d\d-\d\d-\d\dT\d\d\.\d\d\.\d\d\.txt') oldfiles = sorted([x for x in listdir(config.get_str('outdir')) if regexp.match(x)]) if oldfiles: - with open(Path(config.get_str('outdir')) / Path(oldfiles[-1]), 'rU') as h: + with open(Path(config.get_str('outdir')) / Path(oldfiles[-1])) as h: if h.read() == string: return # same as last time - don't write @@ -57,5 +57,5 @@ def export(data: companion.CAPIData, requested_filename: str | None = None) -> N ship_time = time.strftime('%Y-%m-%dT%H.%M.%S', time.localtime(query_time)) file_path = output_directory / f"{ship}.{ship_time}.txt" - with open(file_path, 'wt') as h: + with open(file_path, 'w') as h: h.write(string) diff --git a/monitor.py b/monitor.py index 3df0f85c..c00cfbaf 100644 --- a/monitor.py +++ b/monitor.py @@ -18,7 +18,8 @@ from collections import defaultdict from os import SEEK_END, SEEK_SET, listdir from os.path import basename, expanduser, getctime, isdir, join from time import gmtime, localtime, mktime, sleep, strftime, strptime, time -from typing import TYPE_CHECKING, Any, BinaryIO, MutableMapping +from typing import TYPE_CHECKING, Any, BinaryIO +from collections.abc import MutableMapping import psutil import semantic_version import util_ships @@ -347,7 +348,7 @@ class EDLogs(FileSystemEventHandler): """ return bool(self.thread and self.thread.is_alive()) - def on_created(self, event: 'FileSystemEvent') -> None: + def on_created(self, event: FileSystemEvent) -> None: """Watchdog callback when, e.g. client (re)started.""" if not event.is_directory and self._RE_LOGFILE.search(str(basename(event.src_path))): @@ -2267,7 +2268,7 @@ class EDLogs(FileSystemEventHandler): string = json.dumps(self.ship(False), ensure_ascii=False, indent=2, separators=(',', ': ')) # pretty print if filename: try: - with open(filename, 'wt', encoding='utf-8') as h: + with open(filename, 'w', encoding='utf-8') as h: h.write(string) except UnicodeError: @@ -2276,7 +2277,7 @@ class EDLogs(FileSystemEventHandler): ) try: - with open(filename, 'wt') as h: + with open(filename, 'w') as h: h.write(string) except OSError: @@ -2291,7 +2292,7 @@ class EDLogs(FileSystemEventHandler): ship = util_ships.ship_file_name(self.state['ShipName'], self.state['ShipType']) regexp = re.compile(re.escape(ship) + r'\.\d{4}-\d\d-\d\dT\d\d\.\d\d\.\d\d\.txt') - oldfiles = sorted((x for x in listdir(config.get_str('outdir')) if regexp.match(x))) + oldfiles = sorted(x for x in listdir(config.get_str('outdir')) if regexp.match(x)) if oldfiles: try: with open(join(config.get_str('outdir'), oldfiles[-1]), encoding='utf-8') as h: @@ -2323,13 +2324,13 @@ class EDLogs(FileSystemEventHandler): filename = join(config.get_str('outdir'), f'{ship}.{ts}.txt') try: - with open(filename, 'wt', encoding='utf-8') as h: + with open(filename, 'w', encoding='utf-8') as h: h.write(string) except UnicodeError: logger.exception("UnicodeError writing ship loadout to new filename with utf-8 encoding, trying without...") try: - with open(filename, 'wt') as h: + with open(filename, 'w') as h: h.write(string) except OSError: diff --git a/myNotebook.py b/myNotebook.py index 119f33bb..c28d7873 100644 --- a/myNotebook.py +++ b/myNotebook.py @@ -14,7 +14,7 @@ import tkinter as tk from tkinter import ttk, messagebox from PIL import ImageGrab from l10n import translations as tr -from typing import Callable +from collections.abc import Callable if sys.platform == 'win32': PAGEFG = 'SystemWindowText' diff --git a/outfitting.py b/outfitting.py index 4b014e48..3256da31 100644 --- a/outfitting.py +++ b/outfitting.py @@ -296,7 +296,7 @@ def export(data, filename) -> None: header = 'System,Station,Category,Name,Mount,Guidance,Ship,Class,Rating,FDevID,Date\n' rowheader = f'{data["lastSystem"]["name"]},{data["lastStarport"]["name"]}' - with open(filename, 'wt') as h: + with open(filename, 'w') as h: h.write(header) for v in data["lastStarport"].get("modules", {}).values(): try: diff --git a/plug.py b/plug.py index e573a218..77d73f9e 100644 --- a/plug.py +++ b/plug.py @@ -18,7 +18,8 @@ import tkinter as tk from datetime import datetime, timedelta, timezone from pathlib import Path from tkinter import ttk -from typing import Any, Mapping, MutableMapping +from typing import Any +from collections.abc import Mapping, MutableMapping import companion import myNotebook as nb # noqa: N813 diff --git a/plugins/common_coreutils.py b/plugins/common_coreutils.py index a488de46..2e3b58ae 100644 --- a/plugins/common_coreutils.py +++ b/plugins/common_coreutils.py @@ -22,7 +22,8 @@ referenced in this file (or only in any other core plugin), and if so... # pylint: disable=import-error from __future__ import annotations -from typing import Any, Mapping, cast +from typing import Any, cast +from collections.abc import Mapping import tkinter as tk import base64 import gzip diff --git a/plugins/coriolis.py b/plugins/coriolis.py index 89f128f7..be0bd4be 100644 --- a/plugins/coriolis.py +++ b/plugins/coriolis.py @@ -22,7 +22,8 @@ referenced in this file (or only in any other core plugin), and if so... # pylint: disable=import-error from __future__ import annotations -from typing import Any, Mapping +from typing import Any +from collections.abc import Mapping import tkinter as tk from tkinter import ttk import myNotebook as nb # noqa: N813 # its not my fault. diff --git a/plugins/eddn.py b/plugins/eddn.py index 6410d0b2..8b783c8f 100644 --- a/plugins/eddn.py +++ b/plugins/eddn.py @@ -33,7 +33,8 @@ from tkinter import ttk from platform import system from textwrap import dedent from threading import Lock -from typing import Any, Iterator, Mapping, MutableMapping +from typing import Any +from collections.abc import Iterator, Mapping, MutableMapping import requests import companion import edmc_data @@ -152,7 +153,7 @@ class EDDNSender: r"unable to validate.',\)]$" ) - def __init__(self, eddn: 'EDDN', eddn_endpoint: str) -> None: + def __init__(self, eddn: EDDN, eddn_endpoint: str) -> None: """ Prepare the system for processing messages. diff --git a/plugins/edsm.py b/plugins/edsm.py index 902e248b..46c8ef4e 100644 --- a/plugins/edsm.py +++ b/plugins/edsm.py @@ -29,7 +29,8 @@ from queue import Queue from threading import Thread from time import sleep from tkinter import ttk -from typing import Any, Literal, Mapping, MutableMapping, cast, Sequence +from typing import Any, Literal, cast +from collections.abc import Mapping, MutableMapping, Sequence import requests import killswitch import monitor diff --git a/plugins/edsy.py b/plugins/edsy.py index b1bdbaf1..109bb2f0 100644 --- a/plugins/edsy.py +++ b/plugins/edsy.py @@ -20,7 +20,8 @@ referenced in this file (or only in any other core plugin), and if so... """ from __future__ import annotations -from typing import Any, Mapping +from typing import Any +from collections.abc import Mapping from plugins.common_coreutils import shipyard_url_common # pylint: disable=E0401 diff --git a/plugins/inara.py b/plugins/inara.py index 56df1e0e..8fcf110c 100644 --- a/plugins/inara.py +++ b/plugins/inara.py @@ -31,7 +31,8 @@ from datetime import datetime, timedelta, timezone from operator import itemgetter from threading import Lock, Thread from tkinter import ttk -from typing import Any, Callable, Deque, Mapping, NamedTuple, Sequence, cast, Union +from typing import Any, Deque, NamedTuple, cast, Union +from collections.abc import Callable, Mapping, Sequence import requests import edmc_data import killswitch diff --git a/prefs.py b/prefs.py index 65feb24b..9b82704a 100644 --- a/prefs.py +++ b/prefs.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- """EDMC preferences library.""" from __future__ import annotations @@ -14,7 +13,8 @@ from os import system from tkinter import colorchooser as tkColorChooser # type: ignore # noqa: N812 from tkinter import ttk from types import TracebackType -from typing import Any, Callable, Optional, Type +from typing import Any +from collections.abc import Callable import myNotebook as nb # noqa: N813 import plug from config import appversion_nobuild, config @@ -170,8 +170,8 @@ class AutoInc(contextlib.AbstractContextManager): def __exit__( self, - exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException], traceback: Optional[TracebackType] - ) -> Optional[bool]: + exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None + ) -> bool | None: """Do nothing.""" return None @@ -241,7 +241,7 @@ if sys.platform == 'win32': class PreferencesDialog(tk.Toplevel): """The EDMC preferences dialog.""" - def __init__(self, parent: tk.Tk, callback: Optional[Callable]): + def __init__(self, parent: tk.Tk, callback: Callable | None): super().__init__(parent) self.parent = parent @@ -265,7 +265,7 @@ class PreferencesDialog(tk.Toplevel): self.cmdr: str | bool | None = False # Note if Cmdr changes in the Journal self.is_beta: bool = False # Note if Beta status changes in the Journal - self.cmdrchanged_alarm: Optional[str] = None # This stores an ID that can be used to cancel a scheduled call + self.cmdrchanged_alarm: str | None = None # This stores an ID that can be used to cancel a scheduled call # Set up the main frame frame = ttk.Frame(self) @@ -1136,7 +1136,7 @@ class PreferencesDialog(tk.Toplevel): """Handle preferences active tab changing.""" self.outvarchanged() - def outvarchanged(self, event: Optional[tk.Event] = None) -> None: + def outvarchanged(self, event: tk.Event | None = None) -> None: """Handle Output tab variable changes.""" self.displaypath(self.outdir, self.outdir_entry) self.displaypath(self.logdir, self.logdir_entry) @@ -1240,14 +1240,14 @@ class PreferencesDialog(tk.Toplevel): self.theme_button_0['state'] = state self.theme_button_1['state'] = state - def hotkeystart(self, event: 'tk.Event[Any]') -> None: + def hotkeystart(self, event: tk.Event[Any]) -> None: """Start listening for hotkeys.""" event.widget.bind('', self.hotkeylisten) event.widget.bind('', self.hotkeylisten) event.widget.delete(0, tk.END) hotkeymgr.acquire_start() - def hotkeyend(self, event: 'tk.Event[Any]') -> None: + def hotkeyend(self, event: tk.Event[Any]) -> None: """Stop listening for hotkeys.""" event.widget.unbind('') event.widget.unbind('') @@ -1258,7 +1258,7 @@ class PreferencesDialog(tk.Toplevel): # LANG: No hotkey/shortcut set hotkeymgr.display(self.hotkey_code, self.hotkey_mods) if self.hotkey_code else tr.tl('None')) - def hotkeylisten(self, event: 'tk.Event[Any]') -> str: + def hotkeylisten(self, event: tk.Event[Any]) -> str: """ Hotkey handler. diff --git a/protocol.py b/protocol.py index cec4333a..774a012e 100644 --- a/protocol.py +++ b/protocol.py @@ -12,7 +12,7 @@ import os import sys import threading from urllib import parse -from typing import TYPE_CHECKING, Type +from typing import TYPE_CHECKING from config import config from constants import appname, protocolhandler_redirect from EDMCLogging import get_main_logger @@ -61,7 +61,7 @@ if config.auth_force_edmc_protocol or ( # noqa: C901 ): # This could be false if you use auth_force_edmc_protocol, but then you get to keep the pieces if sys.platform != "win32": - raise EnvironmentError("This code is for Windows only.") + raise OSError("This code is for Windows only.") # spell-checker: words HBRUSH HICON WPARAM wstring WNDCLASS HMENU HGLOBAL from ctypes import ( # type: ignore windll, @@ -434,7 +434,7 @@ else: # Linux / Run from source ) -def get_handler_impl() -> Type[GenericProtocolHandler]: +def get_handler_impl() -> type[GenericProtocolHandler]: """ Get the appropriate GenericProtocolHandler for the current system and config. diff --git a/scripts/find_localised_strings.py b/scripts/find_localised_strings.py index 19a5efb6..02f928e3 100644 --- a/scripts/find_localised_strings.py +++ b/scripts/find_localised_strings.py @@ -188,7 +188,7 @@ class FileLocation: line_end_col: int | None @staticmethod - def from_call(path: pathlib.Path, c: ast.Call) -> "FileLocation": + def from_call(path: pathlib.Path, c: ast.Call) -> FileLocation: """ Create a FileLocation from a Call and Path. diff --git a/stats.py b/stats.py index c16ec880..67fc9379 100644 --- a/stats.py +++ b/stats.py @@ -12,7 +12,8 @@ import json import sys import tkinter as tk from tkinter import ttk -from typing import Any, AnyStr, Callable, NamedTuple, Sequence, cast +from typing import Any, AnyStr, NamedTuple, cast +from collections.abc import Callable, Sequence import companion import EDMCLogging import myNotebook as nb # noqa: N813 diff --git a/td.py b/td.py index 484e8d29..a5f0d6cd 100644 --- a/td.py +++ b/td.py @@ -30,18 +30,18 @@ def export(data: CAPIData) -> None: # required with open(data_path / data_filename, 'wb') as h: # Format described here: https://github.com/eyeonus/Trade-Dangerous/wiki/Price-Data - h.write('#! trade.py import -\n'.encode('utf-8')) + h.write(b'#! trade.py import -\n') this_platform = system() cmdr_name = data['commander']['name'].strip() h.write( - f'# Created by {applongname} {appversion()} on {this_platform} for Cmdr {cmdr_name}.\n'.encode('utf-8') + f'# Created by {applongname} {appversion()} on {this_platform} for Cmdr {cmdr_name}.\n'.encode() ) h.write( - '#\n# \n\n'.encode('utf-8') + b'#\n# \n\n' ) system_name = data['lastSystem']['name'].strip() starport_name = data['lastStarport']['name'].strip() - h.write(f'@ {system_name}/{starport_name}\n'.encode('utf-8')) + h.write(f'@ {system_name}/{starport_name}\n'.encode()) # sort commodities by category by_category = defaultdict(list) @@ -50,7 +50,7 @@ def export(data: CAPIData) -> None: timestamp = time.strftime('%Y-%m-%d %H:%M:%S', time.strptime(data['timestamp'], '%Y-%m-%dT%H:%M:%SZ')) for category in sorted(by_category): - h.write(f' + {format(category)}\n'.encode('utf-8')) + h.write(f' + {format(category)}\n'.encode()) # corrections to commodity names can change the sort order for commodity in sorted(by_category[category], key=itemgetter('name')): h.write( @@ -61,5 +61,5 @@ def export(data: CAPIData) -> None: f"{demandbracketmap[commodity['demandBracket']]:1}" f" {int(commodity['stock']) if commodity['stockBracket'] else '':8}" f"{stockbracketmap[commodity['stockBracket']]:1}" - f" {timestamp}\n".encode('utf-8') + f" {timestamp}\n".encode() ) diff --git a/tests/journal_lock.py/test_journal_lock.py b/tests/journal_lock.py/test_journal_lock.py index 649140c8..438d1dd5 100644 --- a/tests/journal_lock.py/test_journal_lock.py +++ b/tests/journal_lock.py/test_journal_lock.py @@ -5,7 +5,7 @@ import multiprocessing as mp import os import pathlib import sys -from typing import Generator +from collections.abc import Generator import pytest from pytest import MonkeyPatch, TempdirFactory, TempPathFactory from config import config diff --git a/theme.py b/theme.py index d4331291..fe431ebb 100644 --- a/theme.py +++ b/theme.py @@ -15,7 +15,7 @@ import sys import tkinter as tk from tkinter import font as tk_font from tkinter import ttk -from typing import Callable +from collections.abc import Callable from l10n import translations as tr from config import config from EDMCLogging import get_main_logger