Skip to content Skip to sidebar Skip to footer

Python: Pickle.loads Failed For Class Instance

I need tzinfo class for datetime object in my class. I need to pickle my class. But pickle.loads(obj) failed. What's wrong with mytz class? If I do not use mytz class everything wo

Solution 1:

We should add __getinitargs__() method to our custom class. And dump our arguments somewhere:

self.args = offset, dst

tzinfo is abstract class with __reduce__ method. __reduce__ trying to invoke __getinitars__() method. But always stuck with None value.

classmytz (tzinfo):
    def__init__(self, offset, dst):
        self.args = offset, dst
        self._tzname = offset + ' ' + dst
        self._offset = timedelta(
            hours=int(offset[0:3]), minutes=int(offset[0:1] + offset[3:]))
        self._dst = timedelta(
            hours=int(dst[0:3]), minutes=int(dst[0:1] + dst[3:]))

    defutcoffset(self, dt):
        return self._offset + self.dst(dt)

    deftzname(self, dt):
        return self._tzname

    defdst(self, dt):
        return self._dst

    def__getinitargs__(self):
        return self.args

Post a Comment for "Python: Pickle.loads Failed For Class Instance"