How does Mr. Martelli's Borg recipe work ?

Bengt Richter bokr at oz.net
Thu Jul 24 00:18:39 EDT 2003


On 24 Jul 2003 02:47:02 GMT, bokr at oz.net (Bengt Richter) wrote:

>On Wed, 23 Jul 2003 16:40:00 -0600, Steven Taschuk <staschuk at telusplanet.net> wrote:
>
>>Quoth Bengt Richter:
>>  [borg vs singleton]
>>> How about just
>>> 
>>>     import zerolengthfile as borginstancename
>>> 
>>> and using it? E.g., [...]
>>
>>That would be fine in many cases, I'm sure.
>>
>>Modules don't do properties (or other descriptor magic), though.
>>
>Not insurmountable ;-)
>
>====< propmod.py >==========================================
[...]
>I thought it cute to make a property that is a kind of gateway to
>the class attribute space, so that one can use the .properties attribute
>of the propmod module to list, store, retrieve, and delete properties -- as well
>as arbitrary class variables...

Of course,

     propmod.__class__.xxx = yyy

works as well as

     propmod.properties = 'xxx', yyy

so it's kind of a silly exercise, but it does demo properties for a sharable "module."

A much sparer approach:

 >>> import sys
 >>> sys.modules['simple'] = type('SimpleMod',(),{})()
 >>> import simple
 >>> simple.x = 123
 >>> simple.__class__.hi = property(lambda self:'Hi ho')
 >>> simple.x
 123
 >>> simple.hi
 'Hi ho'
 >>> file('impsimp.py','w').write('import simple as m\n')
 >>> import impsimp
 >>> impsimp.m.hi
 'Hi ho'
 >>> impsimp.m.x
 123

Regards,
Bengt Richter




More information about the Python-list mailing list