[SciPy-user] __setstate__ of TimeSeries subclass
Pierre GM
pgmdevlist at gmail.com
Thu Apr 24 21:01:29 EDT 2008
On Thursday 24 April 2008 18:36:29 Pijus Virketis wrote:
> Pierre,
>
> I suspected that would be the first question.
Eh...
> What's really going on is
> that I am building my subclass via multiple inheritance. As is the case
> with most vanilla Python, the other superclass is instantiated only with a
> non-trivial __init__, and I would like to be able to do the same
> "downstream" as well. I am trying to put all of the heavy lifting into
> __init__, and have a __new__ that is just a step above "pass". It won't
> come as a big surprise to me if I learn here that this is anywhere between
> ill-advised and totally dumb. ;)
The pb w/ this approach (and the example you give) is that __init__ is never
called for ndarrays and their subclasses: instead, you need __new__ and
__array_finalize__. You'll find more info here:
http://www.scipy.org/Subclasses
So, what to do (following the nomenclature of your example)?
A possibility would be to reproduce most of the PlainSuperClass.__init__ in
your Test.__new__, and make sure that the attributes of an instance of
PlainSuperClass are dealt with properly in Test.__array_finalize__, something
along those lines:
class PlainSuperClass(object):
def __init__(self, color):
self.color = color
def echocolor(self):
print str(self.color).upper()
class Test(TimeSeries, PlainSuperClass):
def __new__(cls, color, *args, **kwargs):
data = TimeSeries.__new__(cls, [], date_array([]))
data.color = color
return data
def __array_finalize__(self,obj):
TimeSeries.__array_finalize__(self,obj)
self.color = getattr(obj,'color',YourDefaultColor)
Now, I guess that this won't suit you if your PlainSuperClass.__init__ is
relatively complex. Maybe you could try a method similar to the old
implementation of MaskedArray, using containers: don't inherit from ndarray,
but define a __array__ method that could translate part of your data to a
ndarray (in that case, a TimeSeries). You should find some info in
numpy.lib.user_array. That solution might be quite clunky, however... That's
why why we developed TimeSeries as subclasses of ndarrays in the first
place...
Still: why are you trying to pass the pickling state of a TimeSeries to your
Test object ?
In any case, let me know how it goes, and don't hesitate to contact me
off-list if you need more help/info.
More information about the SciPy-User
mailing list