Sentinel values for special cases

Gabriel Genellina gagsl-py at yahoo.com.ar
Fri Oct 27 15:41:27 EDT 2006


At Friday 27/10/2006 11:40, Aahz wrote:

> >    GLOBAL = object()
> >
> >    def insert_ids(ids=GLOBAL):
> >        if ids is GLOBAL:
> >            ids = get_global_ids()
>
>The one disadvantage of this approach is that it complicates pickling
>if/when you store the stentinel in an instance.  There are ways of
>working around that, but none are pleasant.

But why should you store the sentinel in an instance? It's only 
purpose is to detect a special case in the parameter, when None is 
not appropiate.
Even if you were assigning instance attributes, you can use the 
sentinel as a default class attribute (which are not pickled).

 >>> GLOBAL = object()
 >>> class A(object):
...     x = GLOBAL
...     def __init__(self, x=GLOBAL):
...         if x is not GLOBAL:
...             self.x = x
...
 >>> a = A(1)
 >>> a.x
1
 >>> vars(a)
{'x': 1}
 >>> b = A()
 >>> b.x
<object object at 0x00B8B438>
 >>> vars(b)
{}
 >>>
 >>> from cPickle import loads,dumps
 >>> s=dumps(b)
 >>> b2=loads(s)
 >>> b2.x
<object object at 0x00B8B438>
 >>> vars(b2)
{}



-- 
Gabriel Genellina
Softlab SRL 

__________________________________________________
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis! 
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar



More information about the Python-list mailing list