1

With Python dicts, you can do the following:

thing = {} # or dict()
thing['this'] = "is"
thing["is"] = "sparta"

method(**thing)

which the method receives as

method(this="is", is="sparta")

I have a class very similar to a dict, but with a bunch of extra helper methods. I have defined __iter__ with it so that I can do "attr" in thing. My question is, what "magic method" do I have to define (if there is one) to be able to use **?

By the way, I would prefer not to subclass from dict.

The way I am making it behave like a dict is by manipulating the internal __dict__.

Aristides
  • 3,805
  • 7
  • 34
  • 41
  • Note that to support `"attr" in thing` you should *not* define `__iter__` but `__contains__`! Using `__iter__` python will provide a default implementation that simply scans all the values, but you can generally do much better then that in a custom implementation. – Bakuriu Feb 23 '14 at 15:43
  • I defined `__iter__` with an actual implementation, and it worked fine. – Aristides Feb 23 '14 at 21:35
  • What I meant is that defining `__iter__` *in order to support `in`* results in an *inefficient* solution. [`__contains__`](http://docs.python.org/2/reference/datamodel.html#object.__contains__) is the *specific* method that gets called when using `in` and is the one you should use to support that behaviour. If you *also* want to allow `for element in my_object` *then* you should implement `__iter__`. – Bakuriu Feb 23 '14 at 21:43
  • @Bakuriu Well, I wanted both. So two birds with one stone. – Aristides Feb 23 '14 at 22:31

0 Answers0