config_keys =[k for k, v inglobals().items()ifnot k.startswith('_')andisinstance(v,(int,float,bool,str))]# overrides from command line or config fileexec(open('configurator.py').read())
config ={k:globals()[k]for k in config_keys}# will be useful for logging
comfigurator.py
import sys
from ast import literal_eval
for arg in sys.argv[1:]:if'='notin arg:# assume it's the name of a config fileassertnot arg.startswith('--')
config_file = arg
print(f"Overriding config with {config_file}:")withopen(config_file)as f:print(f.read())exec(open(config_file).read())else:# assume it's a --key=value argumentassert arg.startswith('--')
key, val = arg.split('=')
key = key[2:]if key inglobals():try:# attempt to eval it it (e.g. if bool, number, or etc)
attempt = literal_eval(val)except(SyntaxError, ValueError):# if that goes wrong, just use the string
attempt = val
# ensure the types match okasserttype(attempt)==type(globals()[key])# cross fingersprint(f"Overriding: {key} = {attempt}")globals()[key]= attempt
else:raise ValueError(f"Unknown config key: {key}")