Properties for modules?

Steven Bethard steven.bethard at gmail.com
Mon Jun 11 17:55:58 EDT 2007


Ed Leafe wrote:
>     I have a simple module that reads in values from disk when imported, 
> and stores them in attributes, allowing for code like:
> 
>  >>> import moduleFoo
>  >>> print moduleFoo.someSetting
> 'the value'
> 
>     What I'd like to do is have a more property-like behavior, so that 
> if they try to set the value of moduleFoo.someSetting, it also persists 
> it to disk. But properties are really only useful in instances of 
> classes; if I define 'someSetting' as a property at the module level, I 
> get:
> 
>  >>> import moduleFoo
>  >>> print moduleFoo.someSetting
> <property object at 0x78a990>
> 
>     Does anyone know any good tricks for getting property-like behavior 
> here?

I typically define a module wrapping class like::

     class GiveThisModuleProperties(object):
         def __init__(self, module_name):
             self._module = sys.modules[module_name]
             sys.modules[module_name] = self
         # now define whatever behavior you need
         def __getattr__(...):
             ...
         def __setattr__(...):
             ...

Then, in the module you want wrapped, you write::

     GiveThisModuleProperties(__name__)

The trick here is basically that we replace the module object in 
sys.modules with a class instance that wraps the module with whatever 
extra behavior is necessary.

It's not beautiful, but it does seem to work. ;-)

STeVe



More information about the Python-list mailing list