Properties for modules?

James Stroud jstroud at mbi.ucla.edu
Tue Jun 12 00:06:29 CEST 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?
> 
> -- Ed Leafe
> -- http://leafe.com
> -- http://dabodev.com


Most pythonic and recommended would be to create a class inside 
moduleFoo that has the functionality you describe, instantiate an 
instance, and then import reference to the instance into the local 
namespace. This will be essentially equivalent to "module level 
properties" as you describe them.


# moduleFoo.py

def get_setting(self, name):
   return do_whatever(name)

def set_setting(self, name, arg):
   return do_whatever_else(name, arg)

class Foo(object):
   someSetting = property(set_setting, get_setting)

foo = Foo()


# program.py

from moduleFoo import foo

foo.someSetting = some_value

# etc.


Of course, its probably better to move the getters and setters into Foo 
if they will only be used in foo context.

James



More information about the Python-list mailing list