Python Trick: the Fundict (or the Diction)

Suppose you have made the choice in the past of exposing a dictionary as part of an object's interface. So, people are doing things like:[foo]['bar']

And now you want people to not have to specify foo because it can be obtained from somewhere else. In fact, what you want now is to expose something like this:, foo='foo')

Here's an idea on how to do that without breaking the old code:

class fundict(dict):
    def __call__(self, bar, foo='foo'):
        return self[foo][bar]

That's a dictionary that's also a callable, and thus indistinguishable from a function. A function-dictionary. A fundict. And of couse, you could also do it the other way around, and implement a function that works as a dictionary. A dictionary-function, a diction. But since that's more work, I used this one.


Comments powered by Disqus