Externally-defined properties?

Scott David Daniels Scott.Daniels at Acm.Org
Wed Aug 24 13:48:59 EDT 2005


Terry Hancock wrote:
> Frankly, I was surprised this worked at all, but I tried
> creating a property outside of a class (i.e. at the module
> level), and it seems to behave as a property:

Not so surprising.  Making a class begins by making a little namespace,
then using it to build the class.  If you look at how class construction
works, it gets handed the namespace to wrap parts (the originals are
left alone).  After playing with your example for a little, perhaps
the following will illustrate things:

     def get_x(obj):
         return thevar

     def set_x(obj, val):
         global thevar
         thevar = val

     def del_x(obj):
         global thevar
         del thevar

     def textify(obj):
         objid = '%s_%s' % (obj.__class__.__name__, id(obj))
         try:
             return '%s:%r' % (objid, thevar)
         except (NameError, AttributeError):
             return '%s:---' % objid

         prop = property(get_x, set_x, del_x)

     class One(object):
         x = prop
         __repr__ = textify

         class Two(object):
             y = prop
             __str__ = textify

     Class Three(object):
         __repr__ = textify

     a = One()
     b = Two()
     c = Three()
     print a, b, c
     a.x = 5
     print a.x, b.y, a, b, c
     Three.z = One.x
     print c, c.z
     del b.y
     print a, b, c
     print a.x

You may want to raise AttributeError on get_x (you have no name to use):
     def get_x(obj):
         try:
             return thevar
         except NameError:
             raise AttributeError

 > Am I about to shoot myself in the foot?

Well, usually all this playing is good for understanding how Python
works, but makes your connections less than explicit, and we know
that explicit is better than implicit.

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list