Improved functions' docs

This commit is contained in:
Profitroll 2022-09-15 12:30:25 +02:00
parent a238c31f8a
commit 7f3b5174ff
2 changed files with 58 additions and 27 deletions

View File

@ -4,13 +4,14 @@
from os import sep, stat, makedirs, kill
from os import name as osname
from datetime import datetime
from typing import Union
from ujson import loads, dumps
from shutil import copyfileobj
from gzip import open as gzipopen
from psutil import Process
def nowtimeGet(format="%H:%M:%S | %d.%m.%Y"):
def nowtimeGet(format="%H:%M:%S | %d.%m.%Y") -> str:
"""Return current local time formatted as arg.
### Args:
@ -22,7 +23,7 @@ def nowtimeGet(format="%H:%M:%S | %d.%m.%Y"):
return datetime.now().strftime(format)
def checkSize(logs_folder=f"logs{sep}", log_size=1024):
def checkSize(logs_folder=f"logs{sep}", log_size=1024) -> None:
"""Checks latest log file size and rotates it if needed.
### Args:
@ -53,7 +54,7 @@ def checkSize(logs_folder=f"logs{sep}", log_size=1024):
i += 1
def logWrite(message, logs_folder=f"logs{sep}", level="INFO"):
def logWrite(message: str, logs_folder=f"logs{sep}", level="INFO") -> None:
"""Append some message to latest log file.
### Args:
@ -81,26 +82,26 @@ def logWrite(message, logs_folder=f"logs{sep}", level="INFO"):
log.close()
def jsonSave(filename, value):
def jsonSave(filename: str, value: Union[list, dict]) -> None:
"""Save some list or dict as json file.
Args:
### Args:
* filename (str): File to which value will be written.
* value (list or dict): Some object that will be written to filename.
* value (Union[list, dict]): Some object that will be written to filename.
"""
with open(filename, 'w', encoding="utf-8") as f:
f.write(dumps(value, indent=4, ensure_ascii=False))
f.close()
def jsonLoad(filename):
def jsonLoad(filename: str) -> any:
"""Load json file and return python dict or list.
Args:
### Args:
* filename (str): File which should be loaded.
Returns:
* list or dict: Content of json file provided.
### Returns:
* any: Content of json file provided.
"""
with open(filename, 'r', encoding="utf-8") as f:
value = loads(f.read())
@ -108,10 +109,10 @@ def jsonLoad(filename):
return value
def killProc(pid: int):
def killProc(pid: int) -> None:
"""Kill the process by its PID
Args:
### Args:
* pid (int): Process ID to be killed
"""
if osname == "posix":

View File

@ -1,15 +1,17 @@
# -*- coding: utf-8 -*-
"""Essential set of functions needed for discord/telegram bots and other types of apps"""
from types import NoneType
from typing import Union
from modules.functions import jsonLoad, jsonSave
from os import sep
def configGet(key: str, *args: str):
def configGet(key: str, *args: str) -> any:
"""Get value of the config key
Args:
### Args:
* key (str): The last key of the keys path.
* *args (str): Path to key like: dict[args][key].
Returns:
### Returns:
* any: Value of provided key
"""
this_dict = jsonLoad("config.json")
@ -18,11 +20,11 @@ def configGet(key: str, *args: str):
this_key = this_key[dict_key]
return this_key[key]
def configAppend(key: str, value, *args: str):
def configAppend(key: str, value: Union[str, float, int, bool, dict, list, NoneType], *args: str) -> None:
"""Set key to a value
Args:
### Args:
* key (str): The last key of the keys path.
* value (str/int/float/list/dict/None): Some needed value.
* value (Union[str, float, int, bool, dict, list, NoneType]): Some needed value.
* *args (str): Path to key like: dict[args][key].
"""
this_dict = jsonLoad("config.json")
@ -37,19 +39,25 @@ def configAppend(key: str, value, *args: str):
jsonSave(this_dict, "config.json")
return
def configRemove(key, value):
def configRemove(key: str, value: Union[str, float, int, bool, dict, list, NoneType]) -> None:
"""Remove value from config's list key
### Args:
* key (str): The last key of the keys path.
* value (Union[str, float, int, bool, dict, list, NoneType]): Some needed value.
"""
config = jsonLoad("config.json")
config[key].remove(value)
jsonSave("config.json", config)
def locale(key: str, *args: str, locale=configGet("locale")):
def locale(key: str, *args: str, locale=configGet("locale")) -> str:
"""Get value of locale string
Args:
### Args:
* key (str): The last key of the locale's keys path.
* *args (list): Path to key like: dict[args][key].
* locale (str): Locale to looked up in. Defaults to config's locale value.
Returns:
### Returns:
* any: Value of provided locale key
"""
if (locale == None):
@ -61,7 +69,7 @@ def locale(key: str, *args: str, locale=configGet("locale")):
try:
this_dict = jsonLoad(f'locale{sep}{configGet("locale")}.json')
except FileNotFoundError:
return f' Locale in config is invalid: could not get "{key}" in {str(args)} from locale "{locale}"'
return f' Locale in config is invalid: could not get "{key}" in {str(args)} from locale "{locale}"'
this_key = this_dict
for dict_key in args:
@ -70,15 +78,31 @@ def locale(key: str, *args: str, locale=configGet("locale")):
try:
return this_key[key]
except KeyError:
return f' Locale in config is invalid: could not get "{key}" in {str(args)} from locale "{locale}"'
return f' Locale in config is invalid: could not get "{key}" in {str(args)} from locale "{locale}"'
def userSet(userid, key, value):
def userSet(userid: Union[str, int], key: str, value: Union[str, float, int, bool, dict, list, NoneType]) -> None:
"""Set user's variable
### Args:
* userid (Union[str, int]): ID of a user.
* key (str): Key of a user's variable.
* value (Union[str, float, int, bool, dict, list, NoneType]): Some needed value.
"""
user = jsonLoad(f"data{sep}users{sep}{userid}.json")
user[key] = value
jsonSave(f"data{sep}users{sep}{userid}.json", user)
def userGet(userid, key):
def userGet(userid: Union[str, int], key: str) -> any:
"""Get user's variable
### Args:
* userid (Union[str, int]): ID of a user.
* key (str): Key of a user's variable.
### Returns:
* any: Value of requested key or None
"""
try:
return jsonLoad(f"data{sep}users{sep}{userid}.json")[key]
except KeyError:
@ -86,7 +110,13 @@ def userGet(userid, key):
except FileNotFoundError:
return None
def userClear(userid, key):
def userClear(userid: Union[str, int], key: str) -> None:
"""Clear user's variable
### Args:
* userid (Union[str, int]): ID of a user.
* key (str): Key of a user's variable.
"""
try:
user = jsonLoad(f"data{sep}users{sep}{userid}.json")
del user[key]