Still the __new__ hell ...

Arnaud Delobelle arnodel at googlemail.com
Sat Mar 17 18:08:03 EDT 2007


On Mar 17, 9:31 pm, Paulo da Silva <psdasil... at esotericaX.ptX> wrote:
> Sorry to put here too many questions about __init__ __new__
> stuff but I always found a new problem when using them.
> I have searched for simple __new__ docs on how to do the
> basic things but find none.
>
> After trying the solutions people gently posted here
> (thanks) I run into new trouble when I go with further
> development.
>
> Here is the new situation.
>
> As suggested in a previous post, I used __new__ to
> subclass date class but now cPickle/pickle loads
> does not work.
>
> from datetime import date
> import cPickle,string
>
> class MyDate(date):
>         def __new__(cls,year,month=None,day=None):
>                 if type(year) is str:
>                         year,month,day=map(int,string.split(year,'-'))
>                 if year<100:
>                         year+=2000
>                 return date.__new__(cls,year,month,day)
>
> class C1(object):
>         def __init__(self):
>                 self.x=MyDate("2007-3-15")
>
>         def f(self):
>                 print self.x
>
> c1=C1()
>
> d=cPickle.dumps(c1)
> c2=cPickle.loads(d)
> c2.f()

I haven't tried your code but I think that you may need to define a
__reduce__ method in your MyDate class in order to give a clue to the
python as to how to pickle its instances.  For more details see:

http://docs.python.org/lib/node321.html

Something like:

class MyDate(date):
    ...
    def __reduce__(self):
        return type(self), (self.year, self.month, self.day)

might solve your problem.

HTH

--
Arnaud




More information about the Python-list mailing list