Add type hints to class instance variables

This commit is contained in:
2Shirt 2023-05-29 16:25:37 -07:00
parent c009ab2d41
commit a5eb64a055
Signed by: 2Shirt
GPG key ID: 152FAC923B0E132C
5 changed files with 38 additions and 39 deletions

View file

@ -29,8 +29,8 @@ class NonBlockingStreamReader():
## https://stackoverflow.com/a/4896288 ## https://stackoverflow.com/a/4896288
def __init__(self, stream: BufferedReader | TextIOWrapper): def __init__(self, stream: BufferedReader | TextIOWrapper):
self.stream = stream self.stream: BufferedReader | TextIOWrapper = stream
self.queue = Queue() self.queue: Queue = Queue()
def populate_queue(stream: BufferedReader | TextIOWrapper, queue: Queue) -> None: def populate_queue(stream: BufferedReader | TextIOWrapper, queue: Queue) -> None:
"""Collect lines from stream and put them in queue.""" """Collect lines from stream and put them in queue."""

View file

@ -82,15 +82,15 @@ PLATFORM = std.PLATFORM
class State(): class State():
"""Object for tracking hardware diagnostic data.""" """Object for tracking hardware diagnostic data."""
def __init__(self, test_mode=False): def __init__(self, test_mode=False):
self.disks = [] self.disks: list[hw_disk.Disk] = []
self.log_dir = None self.log_dir: pathlib.Path | None = None
self.progress_file = None self.progress_file: pathlib.Path | None = None
self.system = None self.system: hw_system.System | None = None
self.test_groups = [] self.test_groups: list[TestGroup] = []
self.title_text = ansi.color_string('Hardware Diagnostics', 'GREEN') self.title_text: str = ansi.color_string('Hardware Diagnostics', 'GREEN')
if test_mode: if test_mode:
self.title_text += ansi.color_string(' (Test Mode)', 'YELLOW') self.title_text += ansi.color_string(' (Test Mode)', 'YELLOW')
self.ui = tui.TUI(f'{self.title_text}\nMain Menu') self.ui: tui.TUI = tui.TUI(f'{self.title_text}\nMain Menu')
def abort_testing(self) -> None: def abort_testing(self) -> None:
"""Set unfinished tests as aborted and cleanup panes.""" """Set unfinished tests as aborted and cleanup panes."""

View file

@ -7,6 +7,7 @@ import pathlib
import re import re
from subprocess import CalledProcessError from subprocess import CalledProcessError
from threading import Thread
from typing import Any from typing import Any
from wk.cfg.hw import CPU_CRITICAL_TEMP, SMC_IDS, TEMP_COLORS from wk.cfg.hw import CPU_CRITICAL_TEMP, SMC_IDS, TEMP_COLORS
@ -37,9 +38,9 @@ class ThermalLimitReachedError(RuntimeError):
class Sensors(): class Sensors():
"""Class for holding sensor specific data.""" """Class for holding sensor specific data."""
def __init__(self): def __init__(self):
self.background_thread = None self.background_thread: Thread | None = None
self.data = get_sensor_data() self.data: dict[Any, Any] = get_sensor_data()
self.out_path = None self.out_path: pathlib.Path | str | None = None
def clear_temps(self) -> None: def clear_temps(self) -> None:
"""Clear saved temps but keep structure""" """Clear saved temps but keep structure"""

View file

@ -9,7 +9,6 @@ import subprocess
import sys import sys
import traceback import traceback
from collections import OrderedDict
from typing import Any, Callable, Iterable from typing import Any, Callable, Iterable
from prompt_toolkit import prompt from prompt_toolkit import prompt
@ -40,8 +39,8 @@ PLATFORM = platform.system()
class InputChoiceValidator(Validator): class InputChoiceValidator(Validator):
"""Validate that input is one of the provided choices.""" """Validate that input is one of the provided choices."""
def __init__(self, choices: Iterable[str], allow_empty: bool = False): def __init__(self, choices: Iterable[str], allow_empty: bool = False):
self.allow_empty = allow_empty self.allow_empty: bool = allow_empty
self.choices = [str(c).upper() for c in choices] self.choices: list[str] = [str(c).upper() for c in choices]
super().__init__() super().__init__()
def validate(self, document: Document) -> None: def validate(self, document: Document) -> None:
@ -70,7 +69,7 @@ class InputNotEmptyValidator(Validator):
class InputTicketIDValidator(Validator): class InputTicketIDValidator(Validator):
"""Validate that input resembles a ticket ID.""" """Validate that input resembles a ticket ID."""
def __init__(self, allow_empty: bool = False): def __init__(self, allow_empty: bool = False):
self.allow_empty = allow_empty self.allow_empty: bool = allow_empty
super().__init__() super().__init__()
def validate(self, document: Document) -> None: def validate(self, document: Document) -> None:
@ -89,7 +88,7 @@ class InputTicketIDValidator(Validator):
class InputYesNoValidator(Validator): class InputYesNoValidator(Validator):
"""Validate that input is a yes or no.""" """Validate that input is a yes or no."""
def __init__(self, allow_empty: bool = False): def __init__(self, allow_empty: bool = False):
self.allow_empty = allow_empty self.allow_empty: bool = allow_empty
super().__init__() super().__init__()
def validate(self, document: Document) -> None: def validate(self, document: Document) -> None:
@ -108,20 +107,18 @@ class InputYesNoValidator(Validator):
class Menu(): class Menu():
"""Object for tracking menu specific data and methods. """Object for tracking menu specific data and methods.
Menu items are added to an OrderedDict so the order is preserved.
ASSUMPTIONS: ASSUMPTIONS:
1. All entry names are unique. 1. All entry names are unique.
2. All action entry names start with different letters. 2. All action entry names start with different letters.
""" """
def __init__(self, title: str = '[Untitled Menu]'): def __init__(self, title: str = '[Untitled Menu]'):
self.actions = OrderedDict() self.actions: dict[str, dict[Any, Any]] = {}
self.options = OrderedDict() self.options: dict[str, dict[Any, Any]] = {}
self.sets = OrderedDict() self.sets: dict[str, dict[Any, Any]] = {}
self.toggles = OrderedDict() self.toggles: dict[str, dict[Any, Any]] = {}
self.disabled_str = 'Disabled' self.disabled_str: str = 'Disabled'
self.separator = '' self.separator: str = ''
self.title = title self.title: str = title
def _generate_menu_text(self) -> str: def _generate_menu_text(self) -> str:
"""Generate menu text, returns str.""" """Generate menu text, returns str."""
@ -450,14 +447,14 @@ class TryAndPrint():
based on exception names. based on exception names.
""" """
def __init__(self, msg_bad: str = 'FAILED', msg_good: str = 'SUCCESS'): def __init__(self, msg_bad: str = 'FAILED', msg_good: str = 'SUCCESS'):
self.catch_all = True self.catch_all : bool = True
self.indent = INDENT self.indent: int = INDENT
self.list_errors = ['GenericError'] self.list_errors: list[str] = ['GenericError']
self.list_warnings = ['GenericWarning'] self.list_warnings: list[str] = ['GenericWarning']
self.msg_bad = msg_bad self.msg_bad: str = msg_bad
self.msg_good = msg_good self.msg_good: str = msg_good
self.verbose = False self.verbose : bool = False
self.width = WIDTH self.width: int = WIDTH
def _format_exception_message(self, _exception: Exception) -> str: def _format_exception_message(self, _exception: Exception) -> str:
"""Format using the exception's args or name, returns str.""" """Format using the exception's args or name, returns str."""

View file

@ -7,6 +7,7 @@ import time
from copy import deepcopy from copy import deepcopy
from os import environ from os import environ
from typing import Any
from wk.exe import start_thread from wk.exe import start_thread
from wk.std import sleep from wk.std import sleep
@ -30,11 +31,11 @@ TMUX_LAYOUT = { # NOTE: This needs to be in order from top to bottom
class TUI(): class TUI():
"""Object for tracking TUI elements.""" """Object for tracking TUI elements."""
def __init__(self, title_text: str | None = None): def __init__(self, title_text: str | None = None):
self.layout = deepcopy(TMUX_LAYOUT) self.layout: dict[str, dict[str, Any]] = deepcopy(TMUX_LAYOUT)
self.side_width = TMUX_SIDE_WIDTH self.side_width: int = TMUX_SIDE_WIDTH
self.title_text = title_text if title_text else 'Title Text' self.title_text: str = title_text if title_text else 'Title Text'
self.title_text_line2 = '' self.title_text_line2: str = ''
self.title_colors = ['BLUE', None] self.title_colors: list[str | None] = ['BLUE', None]
# Init tmux and start a background process to maintain layout # Init tmux and start a background process to maintain layout
self.init_tmux() self.init_tmux()