advice needed for lazy evaluation mechanism

MRAB python at
Mon Nov 9 01:34:24 CET 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):
Here's a slightly different approach:
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:
         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
# 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):
     repo['age'] = 2009 - repo['birth_year']

def ComputeMHF(repo):
     gender = repo['gender']
     age = repo['age']
     mhf = 211 - age if gender == 'F' else 205 - age
     repo['max_heart_frequency'] = mhf
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)


More information about the Python-list mailing list