Inexpressible new style with kwargs impossible?

When creating an instance of my class, I initialize some fields that are not matched. Thus, in order to (un) sort my classes correctly, I would like my init method to be called when painting. This seems to be the way he worked with the old classes.

With the new style classes I need to use __new__and __getnewargs__. That's what I'm doing:

import cPickle


class Blubb(object):

  def __init__(self, value):
    self.value = value


class Bla(Blubb):

  def __new__(cls, value):
    instance = super(Bla, cls).__new__(cls)
    instance.__init__(value)
    return instance

  def __getnewargs__(self):
    return self.value,

  def __getstate__(self):
    return {}

  def __setstate__(self, dct):
    pass

x = Bla(2)
print x.value
pickled = cPickle.dumps(x, 2)
x_ = cPickle.loads(pickled)
assert x_.value == 2

It would be nice if not for the fact that obj = C.__new__(C, *args). Now exists **kwargs. Therefore, in my methods __new__, __init__I am limited to arguments without a keyword.

Does anyone know how to solve this? This is really inconvenient.

+3
source share
1 answer

2 cls.__new__(cls, *args), . __reduce__, , __new__. , **kwargs :

import cPickle

class Blubb(object):

    def __init__(self, value, foo=None, bar=None):
        self.value = value
        self.foo = foo
        self.bar = bar

def _new_Bla(cls, value, kw):
    "A function to map kwargs into cls.__new__"
    return cls.__new__(cls, value, **kw)

class Bla(Blubb):

    def __new__(cls, value, **kw):
        instance = super(Bla, cls).__new__(cls)
        instance.__init__(value, **kw)
        return instance

    def __reduce__(self):
        kwargs = {'foo': self.foo, 'bar': self.bar}
        return _new_Bla, (self.__class__, self.value, kwargs), None

x = Bla(2, bar=[1, 2, 3])
pickled = cPickle.dumps(x, 2)
y = cPickle.loads(pickled)
assert y.value == 2
assert y.bar == [1, 2, 3]
+7

All Articles