Python: pickle error: __new__() takes exactly 2 arguments (1 given) -


related: pickle load error "__init__() takes 2 arguments (1 given)"

import cpickle pickle  pklfile = "test.pkl"  all_names = {} class name(object):     def __new__(cls, c, s="", v=""):         name = "%s %s %s" % (c, s, v)         if all_names.has_key(name):             return all_names[name]         else:             self = all_names[name] = object.__new__(cls)             self.c, self.s, self.v = c, s, v          return self  open(pklfile, 'wb') output:     pickle.dump(name("hi"), output, pickle.highest_protocol)  open(pklfile, 'rb') input:     name_obj = pickle.load(input) 

output:

traceback (most recent call last):   file "dopickle.py", line 21, in <module>     name_obj = pickle.load(input) typeerror: __new__() takes @ least 2 arguments (1 given) 

is possible make work without having second argument optional?

use __getnewargs__, called when object pickled , provides tuple of arguments passed __new__ when unpickling.

import cpickle pickle  pklfile = "test.pkl"  all_names = {} class name(object):     def __new__(cls, c, s="", v=""):         name = "%s %s %s" % (c, s, v)         if all_names.has_key(name):             return all_names[name]         else:             self = all_names[name] = object.__new__(cls)             self.c, self.s, self.v = c, s, v          return self      def __getnewargs__(self):         return (name.__repr__(self),)      def __repr__(self):         return '<name %r, %r, %r>' % (self.c, self.s, self.v)      def __str__(self):         return "%s %s %s" % (self.c, self.s, self.v)  open(pklfile, 'wb') output:     pickle.dump(name("hi"), output, pickle.highest_protocol)  open(pklfile, 'rb') input:     name_obj = pickle.load(input)     print name_obj 

Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -