Keyword arguments and user-defined dictionaries

Larry Bates lbates at swamisoft.com
Thu Jun 24 10:07:21 EDT 2004


Remember that ** syntax passes each member of the
dictionary as a separate keyword argument.

I think you meant to write:

def g(**foo):
    print foo


But this seems odd construct.  Telling Python to
split a dictionary into separate arguments and then
telling it to reassemble the into a dictionary in
the function.  You should consider just passing
the instance of the dictionary and skip all the **
(but this might just be a trivial example).

HTH,
Larry Bates
Syscon, Inc.


"G. S. Hayes" <sjdevnull at yahoo.com> wrote in message
news:96c2e938.0406231629.4103ccde at posting.google.com...
> Hi,
>
> I'm implementing a lazy-load dictionary; my implementation basically
> stores keys that are to be loaded lazily internally (in a member
> dictionary) and then in __getitem__ I look to see if the key needs to
> be loaded and if so I load it.  My class inherits from dict and has
> keys(), __contains__, __get/setitem__, items(), etc all properly
> implemented--seems to work fine in most cases.
>
> My question is, what methods do I need to implement to make ** work on
> a custom dictionary-like object, or is it not possible?
>
> Here's how you can see the problem.
>
> Simplified LazyDict (the real one actually stores callbacks to
> generate values, but this is enough to show the problem--my real one
> implements a lot more dict methods, but still doesn't work):
>
> class LazyDict(dict):
>     def __init__(self):
>         dict.__init__(self)
>         self.special_keys={}
>     def addLazy(self, key, val):
>         if dict.has_key(self, key):
>             dict.__delitem__(self, key)
>         self.special_keys[key]=val
>     def has_key(self, key):
>         return self.__contains__(key)
>     def __contains__(self, key):
>         if dict.has_key(self, key):
>             return 1
>         elif dict.has_key(self.special_keys, key):
>             return 1
>         else:
>     def __getitem__(self, key):
>         if dict.has_key(self, key):
>            return dict.__getitem__(self, key)
>         elif key in self.special_keys.keys():
>            self[key]=self.special_keys[key]
>            del self.special_keys[key]
>         return dict.__getitem__(self, key)
>            return 0
>
> e.g. put the above in LSimple.py and:
>
> >>> def g(foo):
> ...   print foo
> ...
> >>> a=LSimple.LazyDict()
> >>> a.addLazy("foo", 2)
> >>> g(**a)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: g() takes exactly 1 argument (0 given)
> >>> a["foo"]
> 2
> >>> g(**a)
> 2
> >>>
>
> Thanks for your time.





More information about the Python-list mailing list