viff

changeset 1034:1a9cfb730bc1

New decorator for faking functions.
author Martin Geisler <mg@daimi.au.dk>
date Sun, 30 Nov 2008 23:13:12 +0100
parents dcb0e2794219
children f7d1f7cd3dda
files viff/util.py
diffstat 1 files changed, 22 insertions(+), 0 deletions(-) [+]
line diff
     1.1 --- a/viff/util.py	Sun Nov 30 17:36:39 2008 +0100
     1.2 +++ b/viff/util.py	Sun Nov 30 23:13:12 2008 +0100
     1.3 @@ -88,6 +88,28 @@
     1.4              return f
     1.5          return decorator
     1.6  
     1.7 +def fake(replacement):
     1.8 +    """Replace a function with a fake version.
     1.9 +
    1.10 +    This decorator is meant to be used for profiling where specific
    1.11 +    functions can be replaced with fake versions that are faster. The
    1.12 +    fake version should take the same input as the original function
    1.13 +    and deliver output of the correct type.
    1.14 +
    1.15 +    The environment variable :envvar:`VIFF_FAKE` must be set to enable
    1.16 +    this decorator. The variable is treated as a list of function
    1.17 +    names, separated on whitespace. Setting :envvar:`VIFF_FAKE` to the
    1.18 +    special value ``*`` will enable all fake replacements known.
    1.19 +    """
    1.20 +
    1.21 +    def decorator(func):
    1.22 +        fakes = os.environ.get('VIFF_FAKE', '')
    1.23 +        if fakes == '*' or func.__name__ in fakes.split():
    1.24 +            return replacement
    1.25 +        else:
    1.26 +            return func
    1.27 +
    1.28 +    return decorator
    1.29  
    1.30  def deprecation(message):
    1.31      """Issue a deprecation warning."""