advice needed for lazy evaluation mechanism

MRAB python at mrabarnett.plus.com
Sun Nov 8 19:34:24 EST 2009


markolopa wrote:
> Hi again,
> 
> I put a copy of the message and the tarball of the code here (because
> of the problem of line breaks):
> 
> http://python-advocacy.wikidot.com/comp-lang-python-question
> 
Here's a slightly different approach:

repository.py
=============
class Repository(object):
     def __init__(self):
         self._providers = {}
         self._values = {}

     def add_provider(self, func, keys):
         for k in keys:
             self._providers[k] = func

     def __getitem__(self, key):
         if key not in self._values:
             self._providers[key](self)
         return self._values[key]

     def __setitem__(self, key, value):
         self._values[key] = value

def register(*modules):
     "Register the provider modules and return a repository."
     repo = Repository()
     for mod in modules:
         # Scan the module for providers.
         # A provider is a function which lists what it provides in its __doc__ string.
         for name, value in mod.__dict__.items():
             if callable(value) and value.__doc__:
                 repo.add_provider(value, value.__doc__.split())
     return repo


routines.py
===========
# The providers are functions which list what they provide in their __doc__ strings.

def ReadData(repo):
     'birth_year gender'
     repo['birth_year'] = 1979
     repo['gender'] = 'F'

def YearToAge(repo):
     'age'
     repo['age'] = 2009 - repo['birth_year']

def ComputeMHF(repo):
     'max_heart_frequency'
     gender = repo['gender']
     age = repo['age']
     mhf = 211 - age if gender == 'F' else 205 - age
     repo['max_heart_frequency'] = mhf


test.py
=======
import unittest
import repository
import routines

class Test(unittest.TestCase):
     def test_age(self):
         repo = repository.register(routines)
         self.assertEqual(repo['age'], 30)

     def test_max_heart_frequency(self):
         repo = repository.register(routines)
         self.assertEqual(repo['max_heart_frequency'], 181)

unittest.main()




More information about the Python-list mailing list