Last active
October 30, 2021 23:01
-
-
Save ArjixWasTaken/3b80857fbc83268e13aa62c10479a6eb to your computer and use it in GitHub Desktop.
A decorator that saves and loads config.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import click | |
import json | |
import sys | |
import os | |
class Configurer: | |
executable = os.path.abspath(sys.argv[0]) | |
def save(func, *args, **kwargs): | |
del kwargs["save"] | |
if "load" in kwargs: | |
del kwargs["load"] | |
try: | |
with open(f"{Configurer.executable}.conf", "w") as f: | |
json.dump(kwargs, f, indent=2, ensure_ascii=False) | |
func(*args, **kwargs) | |
except (OSError) as e: | |
print("OSError: Failed to save config data: {}".format(str(e))) | |
def load(func, *args, **kwargs): | |
del kwargs["load"] | |
if "save" in kwargs: | |
del kwargs["save"] | |
try: | |
with open(f"{Configurer.executable}.conf", "r") as f: | |
config = json.load(f) | |
for key, value in config.items(): | |
kwargs[key] = value | |
func(*args, **kwargs) | |
except (OSError) as e: | |
print("OSError: Failed to load config data: {}".format(str(e))) | |
def main(func): | |
def inner(*args, **kwargs): | |
if (os.path.isfile(f"{Configurer.executable}.conf")) and \ | |
("load" in kwargs) and kwargs["load"]: | |
Configurer.load(func, *args, **kwargs) | |
elif "save" in kwargs and kwargs["save"]: | |
Configurer.save(func, *args, **kwargs) | |
else: | |
if "save" in kwargs: | |
del kwargs["save"] | |
if "load" in kwargs: | |
del kwargs["load"] | |
func(*args, **kwargs) | |
return inner |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment