tags:

views:

27

answers:

1

So I have a class that will have a lot of attributes. Is there a way to make this class behave in a way that I can pass it as a **kwarg to a function?

class Foo ( object ) :
    def __init__( self ) :
         self.a = 'a'
         self.b = 'b'

foo = Foo()
somefunc(**foo)

I cannot find the right operator to overload.

Thanks a lot!

+2  A: 

**kwargs expects a dictionary; the easiest way to make your class support dict operations (ed: apart from directly inheriting from dict, which also works) is to inherit from the collections.MutableMapping mixin, which will need you to define __setitem__, __getitem__ and __delitem__ and give you the rest of the dict interface for free.

You can keep an internal dict of attributes, pass those three functions through to it, and additionally implement __setattr__ and __getattr__ to support attribute-style access. Here's a recipe that does something like what you're looking for - you need to be careful about messing with those two.

tzaman