Python becoming less Lisp-like

Jeremy Bowers jerf at
Wed Mar 16 03:18:25 CET 2005

On Tue, 15 Mar 2005 03:21:48 -0800, Paul Boddie wrote:
> Well, I've been using Python for almost ten years, and I've managed to
> deliberately ignore descriptors and metaclasses quite successfully. I get
> the impression that descriptors in particular are a detail of the
> low-level implementation that get a disproportionate level of coverage
> because of the "hack value" they can provide (albeit with seemingly
> inappropriate application to certain problem areas).

I kept playing with descriptors, and tearing them out of production code,
but I finally figured out how to "think" of them, I think. 

You want to create a descriptor for a type of "property()" that you keep
using over and over again. If it's a one-off, use a property and be done
with it. If you find yourself writing the same property over and over
again, having access to the descriptor itself lets you factor it out so
you can write it Once and Only Once (IMHO the highest of all programming
laws^H^H^H^H^H rules of thumb).

I went a long time before I came up with a use case for that, but now I
have one where I want an attribute to fire an event in a particular manner
every time it is changed. Rather than write a read function and a write
function for each attribute (or try to hack it with closures or other
arcane enchantments), it was easy to pack it up as a descriptor. It's a
little too large to just copy and paste, but the upshot is that I can use
it just like this:

class Whatever(object):
    name = EmitOnChange("nameChange", "_name")

and that will fire a "nameChange" event into my event system every time
someone modifies "name", and the "real" value is stored in _name.
(Obviously, I use it more than this once in the real code.)

This may not be the best way to look at it from the C point of view, but I
think it's a good way to look at it from the Python point of view. It
probably is pretty rare that you need this, but it's there.

More information about the Python-list mailing list