python - Dictionary of directories -
i have paths (simplified): /rootfolder/subfolder_1/subsubfolder_1/
paths = { 'rootfolder':'rootfolder/' 'subfolder_1':paths[rootfolder]+'subfolder/' 'subsubfolder_1:paths[subfolder]+'subsubfolder/' }
basically, want static dictionary of paths, want keep dependencies can make 1 change in future. unsure if that's doable, , if, how? have better ideas mine? in advance help.
you can use functions values keys. because functions not called before dict
constructed, there'll no nameerror
.
in [320]: paths = { 'root': lambda: '/', 'usr': lambda: os.path.join(paths['root'](), 'usr')} in [321]: paths['root']() out[321]: '/' in [322]: paths['usr']() out[322]: '/usr' in [323]: paths['root'] = lambda: '//' in [324]: paths['usr']() out[324]: '//usr'
if don't want paths['root']()
, subclass dict
.
from types import functiontype import os class dyndict(dict): def __getitem__(self, key): val = dict.__getitem__(self, key) return val() if type(val) functiontype else val paths = dyndict(root='/', tmp=lambda: os.path.join(paths['root'], 'tmp')) print(paths['root'], paths['tmp']) paths['root'] = '/var/' print(paths['root'], paths['tmp'])
output;
/ /tmp /var/ /var/tmp
Comments
Post a Comment