user2678074 user2678074 - 1 year ago 63
Python Question

Dictionary of directories

I have some paths like (simplified):

paths = {

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 Source

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'])


/ /tmp
/var/ /var/tmp
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download