Updated doc strings and added type hints

This commit is contained in:
Sebastian Kloth 2023-12-26 11:29:21 +01:00
parent 2615798088
commit aca9ba0723

View File

@ -1,31 +1,33 @@
import os
import numpy as np
import functools
import inspect
from typing import Optional, Callable
import numpy as np
from .checksum import checksum
from .logging import logger
autosave_directory = None
autosave_directory: Optional[str] = None
load_autosave_data = False
verbose_print = True
user_autosave_directory = os.path.join(os.environ["HOME"], ".mdevaluate/autosave")
def notify(msg):
def notify(msg: str):
if verbose_print:
logger.info(msg)
else:
logger.debug(msg)
def enable(dir, load_data=True, verbose=True):
def enable(dir: str, load_data: bool = True, verbose: bool = True):
"""
Enable auto saving results of functions decorated with :func:`autosave_data`.
Enable auto saving results of functions decorated with: func: `autosave_data`.
Args:
dir: Directory where the data should be saved.
load_data (opt., bool): If data should also be loaded.
verbose (opt., bool): If autosave should be verbose.
"""
global autosave_directory, load_autosave_data, verbose_print
verbose_print = verbose
@ -79,9 +81,8 @@ def get_directory(reader):
if not os.access(savedir, os.W_OK):
savedir = os.path.join(user_autosave_directory, savedir.lstrip("/"))
logger.info(
"Switched autosave directory to {}, since original location is not writeable.".format(
savedir
)
"Switched autosave directory to {}, "
"since original location is not writeable.".format(savedir)
)
os.makedirs(savedir, exist_ok=True)
return savedir
@ -140,20 +141,24 @@ def load_data(filename):
return data
def autosave_data(nargs, kwargs_keys=None, version=None):
def autosave_data(
nargs: int, kwargs_keys: Optional[list[str]] = None, version: Optional[int] = None
) -> Callable:
"""
Enable autosaving of results for a function.
Args:
nargs: Number of args which are relevant for the calculation.
kwargs_keys (opt.): List of keyword arguments which are relevant for the calculation.
kwargs_keys (opt.):
List of keyword arguments which are relevant for the calculation.
version (opt.):
An optional version number of the decorated function, which replaces the checksum of
the function code, hence the checksum does not depend on the function code.
An optional version number of the decorated function, which replaces the
checksum of the function code, hence the checksum does not depend on the
function code.
"""
def decorator_function(function):
# make sure too include names of positional arguments in kwargs_keys,
# make sure to include names of positional arguments in kwargs_keys,
# sice otherwise they will be ignored if passed via keyword.
# nonlocal kwargs_keys
posargs_keys = list(inspect.signature(function).parameters)[:nargs]