switching an instance variable between a property and a normal value

Robert Brewer fumanchu at amor.org
Sat Jan 8 00:14:48 CET 2005


Steven Bethard wrote:
> I'm playing around with a mapping type that uses setdefault 
> as suggested 
> in http://www.python.org/moin/Python3_2e0Suggestions.  The 
> default value 
> for a missing key is either a simple value, or a value 
> generated from a 
> function.  If it's generated from the function, it should be 
> generated 
> new each time so that, for example, if the default is an empty list, 
> d[1] and d[2] don't access the same list.  This is why 'c.x is c.x' 
> should be False if I'm using the function.
> 
> The best option I guess is to rewrite this with a 
> _getdefault() function instead of a property:
> 
> But I was hoping to avoid having two separate attributes (self._value 
> and self._func) when only one should have a value at any given time.

It seems to me like you were using the property as a glorified flag.
Just use a flag.

ftypes = ('BuiltinFunctionType', 'BuiltinMethodType',
          'FunctionType', 'GeneratorType', 'LambdaType',
          'MethodType', 'UnboundMethodType',)

class D(dict):
    def __init__(self):
        self._default = None
        self._call_default = False
    def __getitem__(self, key):
        if not key in self:
            if self._call_default:
                self[key] = self._default()
            else:
                self[key] = self._default
        return dict.__getitem__(self, key)
    def setdefaultvalue(self, value):
        self._default = value
        self._call_default = isinstance(value, ftypes)

...or:

    def setdefaultvalue(self, value, call_callables=True):
        self._default = value
        self._call_default = callable(value) and call_callables


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org



More information about the Python-list mailing list