Improved type annotations and linting using TypedDicts

This commit is contained in:
Emma Nora Theuer 2024-12-31 02:26:53 +01:00
parent 5e84b81c7f
commit f005a6fb50

View file

@ -1,25 +1,23 @@
from sys import exit from sys import exit
from os import chdir, getenv, system from os import chdir, getenv, system
from typing import List, Dict, Union
import logging import logging
import tomllib import tomllib
from datetime import datetime, time from datetime import datetime, time
from apscheduler.schedulers.background import BackgroundScheduler, BlockingScheduler from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger from apscheduler.triggers.cron import CronTrigger
from wallman_classes import *
# Setup Logging. NOTE: Declaration as a global variable is necessary to ensure correct functionality across multiple modules. # Setup Logging. NOTE: Declaration as a global variable is necessary to ensure correct functionality across multiple modules.
global logger global logger
logger = logging.getLogger("wallman") logger = logging.getLogger("wallman")
class ConfigError(Exception):
pass
class _ConfigLib: class _ConfigLib:
# Initializes the most important config values. TODO: Add handling for the empty config edge case # Initializes the most important config values. TODO: Add handling for the empty config edge case
def __init__(self) -> None: def __init__(self) -> None:
self.config_file: Dict[str, Dict[str, Union[int, str, bool, List[str]]]] = self._initialize_config() # Full config self.config_file: ConfigFile = self._initialize_config() # Full config
# Dictionaries # Dictionaries
self.config_general: Dict[str, Union[int, str, bool, List[str]]] = self.config_file["general"] self.config_general: ConfigGeneral = self.config_file["general"]
self.config_changing_times: Dict[str, str] = self.config_file["changing_times"] self.config_changing_times: Dict[str, str] = self.config_file["changing_times"]
# Values in Dicts # Values in Dicts
self.config_wallpaper_sets_enabled: bool = self.config_general["enable_wallpaper_sets"] self.config_wallpaper_sets_enabled: bool = self.config_general["enable_wallpaper_sets"]
@ -47,16 +45,16 @@ class _ConfigLib:
self._initialize_systray() self._initialize_systray()
# Read config. TODO: Add error handling for the config not found case. # Read config. TODO: Add error handling for the config not found case.
def _initialize_config(self) -> Dict[str, Dict[str, Union[int, str, bool, List[str]]]]: def _initialize_config(self) -> ConfigFile:
chdir(str(getenv("HOME")) + "/.config/wallman/") chdir(str(getenv("HOME")) + "/.config/wallman/")
with open("wallman.toml", "rb") as config_file: with open("wallman.toml", "rb") as config_file:
data: Dict[str, Dict[str, Union[int, str, bool, List[str]]]] = tomllib.load(config_file) data: ConfigFile = tomllib.load(config_file) #pyright:ignore
return data return data
# HACK on this to avoid double importing of wallman_systray due to variable scope. Idea: Global variable or Variable that is inherited? # HACK on this to avoid double importing of wallman_systray due to variable scope. Idea: Global variable or Variable that is inherited?
def _initialize_systray(self): def _initialize_systray(self):
try: try:
import wallman_systray import wallman_systray as _
except (ImportError, FileNotFoundError): except (ImportError, FileNotFoundError):
self.config_systray = False self.config_systray = False
@ -117,6 +115,7 @@ class ConfigValidity(_ConfigLib):
super().__init__() super().__init__()
def _check_fallback_wallpaper(self) -> bool: def _check_fallback_wallpaper(self) -> bool:
# TODO: Make self.config_general["fallback_wallpaper"] a class-wide variable in ConfigLib
if self.config_general["fallback_wallpaper"]: if self.config_general["fallback_wallpaper"]:
logger.debug("A fallback wallpaper has been defined.") logger.debug("A fallback wallpaper has been defined.")
return True return True
@ -213,7 +212,7 @@ class WallpaperLogic(_ConfigLib):
def __init__(self) -> None: def __init__(self) -> None:
super().__init__() super().__init__()
# NOTE: This looks a bit ugly. Consider pros and cons of adding this into _ConfigLib # NOTE: This looks a bit ugly. Consider pros and cons of adding this into _ConfigLib
self.chosen_wallpaper_set: Union[bool, List[str]] = False self.chosen_wallpaper_set: str = "fFTojkvCLIkGVlC6vUo4701djCZczmJDiyHKj4Qdj0zwkLyETsPxP88DLmY9In0I"
# NOTE: This function could be in a different file because it's not needed in the case only 1 wallpaper per set is needed. # NOTE: This function could be in a different file because it's not needed in the case only 1 wallpaper per set is needed.
# Returns a list of a split string that contains a changing time from the config file # Returns a list of a split string that contains a changing time from the config file
@ -222,7 +221,6 @@ class WallpaperLogic(_ConfigLib):
return unclean_times.split(":") return unclean_times.split(":")
# NOTE: This could be in a different file because it's not needed in the "Only one wallpaper set" case. # NOTE: This could be in a different file because it's not needed in the "Only one wallpaper set" case.
# FIXME: Use a TypedDict here
def _choose_wallpaper_set(self) -> None: def _choose_wallpaper_set(self) -> None:
from random import choice as choose_from from random import choice as choose_from
self.chosen_wallpaper_set = choose_from(self.config_used_sets) self.chosen_wallpaper_set = choose_from(self.config_used_sets)
@ -264,7 +262,7 @@ class WallpaperLogic(_ConfigLib):
# TODO: Add an way for the user to choose if the wallpaper should scale, fill or otherwise. This needs to be editable in the config file. # TODO: Add an way for the user to choose if the wallpaper should scale, fill or otherwise. This needs to be editable in the config file.
def set_wallpaper_by_time(self) -> bool: def set_wallpaper_by_time(self) -> bool:
# Ensure use of a consistent wallpaper set # Ensure use of a consistent wallpaper set
if self.chosen_wallpaper_set is False: if self.chosen_wallpaper_set != "fFTojkvCLIkGVlC6vUo4701djCZczmJDiyHKj4Qdj0zwkLyETsPxP88DLmY9In0I":
self._choose_wallpaper_set() self._choose_wallpaper_set()
for time_range in range(self.config_total_changing_times - 1): for time_range in range(self.config_total_changing_times - 1):
self.current_time_range = time_range # Store current time for better debugging output self.current_time_range = time_range # Store current time for better debugging output