Skip to main content

Ralsina.Me — Roberto Alsina's website

Python Trick: the Fundict (or the Diction)

Sup­pose you have made the choice in the past of ex­pos­ing a dic­tio­nary as part of an ob­jec­t's in­ter­face. So, peo­ple are do­ing 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 with­out break­ing the old code:

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

That's a dic­tio­nary that's al­so a callable, and thus in­dis­tin­guish­able from a func­tion. A func­tion-­dic­tionary. A fun­dic­t. And of couse, you could al­so do it the oth­er way around, and im­ple­ment a func­tion that works as a dic­tio­nary. A dic­tio­nary-­func­tion, a dic­tio­n. But since that's more work, I used this one.