One-Shot Property?

John Lenton john at
Tue Jan 18 13:33:10 EST 2005

On Tue, Jan 18, 2005 at 04:54:56PM +0000, Kevin Smith wrote:
> I have many cases in my code where I use a property for calculating a 
> value on-demand.  Quite a few of these only need to be called once.  
> After that the value is always the same.  In these properties, I set a 
> variable in the instance as a cached value and return that value on 
> subsequent calls.  It would be nice if there was a descriptor that would 
> do this automatically.  Actually, what would be really nice is if I 
> could replace the property altogether and put the calculated value in 
> its place after the first call, but the property itself prevents me from 
> doing that.  Is this possible?

consider this:

   1 >>> class C:
   2 ...     x = property(str)
   3 ... 
   4 >>> c = C()
   5 >>> c.x
   6 '<__main__.C instance at 0x4008d92c>'
   7 >>> setattr(c, 'x', c.x)
   8 >>> c.x
   9 '<__main__.C instance at 0x4008d92c>'
  10 >>> C.x
  11 <property object at 0x4009a7ac>
  12 >>> c.x = 2
  13 >>> 

in line 5 you see that the x property so defined works. In line 7 you
remove it, replacing it with the computed value of the property. Line
9 shows that it worked, line 11 shows that it didn't break the class,
and line 13 (through the absence of an exception) shows that it no
longer is 'special' (as it shouldn't be).

John Lenton (john at -- Random fortune:
You can tune a piano, but you can't tuna fish.

You can tune a filesystem, but you can't tuna fish.
		-- from the tunefs(8) man page
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 196 bytes
Desc: Digital signature
URL: <>

More information about the Python-list mailing list