I’m implementing a Fenwick tree class in python.
Basically I have an internal list and two methods, get(key) and increase(key, inc), to handle reading and updating this list.
Mapping f[5] to f.get(5) is easy with __getitem__, but is there any way to make f[5] += 2 mean f.increase(5, 2)?
I found a relevant mailing list thread that says it can’t be done unless you wrap the results from __getitem__ in a proxy-class that implements __iadd__, but that’s not an option. So I’ll probably have to accept that I’ll have to use the increase-method, just thought I’d ask here just in case some genius has the solution.
I’m using python3.2 by the way.
No, the approach you described is pretty much the only option. There may be minor variations, but there’s no (sane, at least) way around the fact that
f[5] += 2will call__getitem__, then__setitem__, and do the+part only on the object retrieved, without considering the container.