user2678074 user2678074 - 4 months ago 9
Python Question

Dictionary of directories

I have some paths like (simplified):
/rootFolder/subfolder_1/subsubfolder_1/

paths = {
'rootFolder':'rootFolder/'
'subFolder_1':paths[rootFolder]+'subFolder/'
'subsubFolder_1:paths[subfolder]+'subsubFolder/'
}


Basically, I want a static dictionary of paths, but I also want to keep dependencies so I can make just one change in the future. I am unsure if that's doable, and if, then how? Do you have some better ideas than mine?
Thanks in advance for help.

Answer

You can use functions as values for the keys. Because functions are not called before the dict is constructed, there'll be 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 you don't want do paths['root'](), simply 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) is 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