[Python 2.x] Pickling a datetime.tzinfo subclass instance?

Cong Ma cma at mail.bnu.edu.cn
Tue Dec 9 10:56:37 CET 2008

Gabriel Genellina wrote:
> En Mon, 08 Dec 2008 12:34:03 -0200, Cong Ma <cma at mail.bnu.edu.cn> escribió:
>> I'm writing a program that pickles an instance of a custom subclass of
>> datetime.tzinfo. I followed the guides given in the Library Reference
>> (version
>> 2.5.2, chapter 5.1.6), which contain the note:
>> "Special requirement for pickling: A tzinfo subclass must have an
>> __init__
>> method that can be called with no arguments, else it can be pickled
>> but possibly
>> not unpickled again. This is a technical requirement that may be
>> relaxed in the
>> future."
>> I tried this with an example "FixedOffset" subclass instance given in the
>> Example section in the manual. It indeed failed to unpickle. To work
>> around
>> this, I found two possible solutions:
>> 1. Modify the __init__ method so that it takes optional arguments with
>> default
>> values;
> Doing that still works with 2.6 and 3.0
>> 2. Implement the __getinitargs__ method so that it does the opposite of
>> __init__: returning a tuple from the instance's internal state that
>> can be used
>> to re-initialize an instance, retaining the old value.
> In fact, it doesn't matter *what* it returns, as far as they're valid
> arguments to __init__
>> My questions:
>> 1. Is the "technical limitation" fixed in version 2.6 or 3.0? I can't
>> check it
>> for myself now... Python.org seems down and I can't find the docs.
> No, they behave the same (odd) way.
>> 2. To stick with version 2.5, which of the above 2 methods is better?
>> Both seems
>>  to unpickle to the correct result, but are there subtle side-effects?
>> Or there
>> are better solutions?
> I'd use method 1, just because the __getinitargs__ are useless.


Thank you so much for your great explanations. Had you not told me this, I would
hardly be able to find it out by myself :)


More information about the Python-list mailing list