8 Mar 2013 ralsina   » (Master)

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:

object.data[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:

object.data(bar, 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.

Syndicated 2013-03-08 18:13:41 from Lateral Opinion

Latest blog entries     Older blog entries

New Advogato Features

New HTML Parser: The long-awaited libxml2 based HTML parser code is live. It needs further work but already handles most markup better than the original parser.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!