switching an instance variable between a property and a normal value

Nick Coghlan ncoghlan at iinet.net.au
Sat Jan 8 07:38:04 CET 2005

Steven Bethard wrote:
> I'd like to be able to have an instance variable that can sometimes be 
> accessed as a property, and sometimes as a regular value, e.g. something 
> like:

If you want the behaviour to be switchable per-instance, you have to go the 
route of always running through the property machinery, since property() creates 
a descriptor on the class, not the instance.

On the other hand, if you want to switch the behaviour of every instance, then 
making usevalue and usefunc class methods may give you some mileage.

I'm rather curious about your use case, though. . .

Here's a different way of using the property machinery, too:

Py> class C(object):
...   def __init__(self):
...     self._use_val = None
...   def useval(self, x):
...     self._val = x
...     self._use_val = True
...   def usefunc(self, func, *args, **kwds):
...     self._func, self._args, self._kwds = (func, args, kwds)
...   def _get(self):
...     use_val = self._use_val
...     if use_val is None:
...       raise AttributeError('x')
...     if use_val:
...       return self._val
...     else:
...       return self._func(*self._args, **self._kwds)
...   x = property(_get)
Py> c = C()
Py> c.useval(4)
Py> c.x
Py> c.usefunc(list)
Py> c.x

Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia

More information about the Python-list mailing list