Keyword arguments and user-defined dictionaries

Christopher T King squirrel at WPI.EDU
Thu Jun 24 16:33:48 CEST 2004

> My question is, what methods do I need to implement to make ** work on
> a custom dictionary-like object, or is it not possible?

As far as I can tell, it's not possible - Python seems to shortcut the 
standard dictionary operators while retrieving the items in the 
dictionary (this is possible since dictionaries are built-in, and Python 
knows their structure). According to the language reference:

> If the syntax "**expression" appears in the function call, "expression" 
> must evaluate to a (subclass of) dictionary

which seems pretty indicative that Python's shortcutting function calls
for efficiency reasons: if you implement every single dictionary method in
a class that's _not_ a subclass of dictionary, **mydict will fail because
Python can't access its values directly.

Your best bet is probably to call the function as func(**dict(mydict)). 
dict() doesn't shortcut custom methods, so this should act as expected.

More information about the Python-list mailing list