Storing empties

Jean-Paul Calderone exarkun at divmod.com
Tue Nov 8 22:37:10 EST 2005


On Tue, 8 Nov 2005 19:28:36 -0800, Alex Martelli <aleax at mail.comcast.net> wrote:
>Aahz <aahz at pythoncraft.com> wrote:
>   ...
>> >For pickling, object() as a unique "nothing here, NOT EVEN a None"
>> >marker (AKA sentinel) works fine.
>>
>> How does that work?  Maybe I'm missing something obvious.
>>
>>     sentinel = object()
>>     class C:
>>         def __init__(self, foo=sentinel):
>>             self.foo = foo
>>         def process(self):
>>             if self.foo is not sentinel:
>>                 ....
>>
>> Now, the way I understand this, when your application restarts and an
>> instance of C is read from a pickle, your sentinel is going to be a
>> different instance of object() and process() will no longer work
>> correctly.  Are you suggesting that you need to pickle the sentinel with
>> the instance?  Or is there some other trick I'm missing?
>
>Yes, I'd set self.sentinel=sentinel (and test wrt that) -- while in the
>abstract it would be better to set sentinel at class level, since
>classes are only pickled "by name" that wouldn't work.
>
>If you don't need the absolute ability to pass ANY argument to C(),
>there are of course all sorts of workaround to save some small amount of
>memory -- any object that's unique and you never need to pass can play
>the same role as a sentinel, obviously.

This is a reasonable trick, though:

    class sentinel:
        pass

Now sentinel pickles and unpickles in a manner which agrees with the above pattern without any extra works.

Jean-Paul



More information about the Python-list mailing list