• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2017 The Chromium Authors
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5import functools
6import logging
7
8
9def Memoize(f):
10  """Decorator to cache return values of function."""
11  memoize_dict = {}
12  @functools.wraps(f)
13  def wrapper(*args, **kwargs):
14    key = repr((args, kwargs))
15    if key not in memoize_dict:
16      memoize_dict[key] = f(*args, **kwargs)
17    return memoize_dict[key]
18  return wrapper
19
20
21def NoRaiseException(default_return_value=None, exception_message=''):
22  """Returns decorator that catches and logs uncaught Exceptions.
23
24  Args:
25    default_return_value: Value to return in the case of uncaught Exception.
26    exception_message: Message for uncaught exceptions.
27  """
28  def decorator(f):
29    @functools.wraps(f)
30    def wrapper(*args, **kwargs):
31      try:
32        return f(*args, **kwargs)
33      except Exception:  # pylint: disable=broad-except
34        logging.exception(exception_message)
35        return default_return_value
36    return wrapper
37  return decorator
38