Chromium Code Reviews| OLD | NEW |
|---|---|
| (Empty) | |
| 1 # Copyright 2017 The Chromium Authors. All rights reserved. | |
|
jbudorick
2017/01/31 16:11:53
python_utils doesn't really say anything as a name
| |
| 2 # Use of this source code is governed by a BSD-style license that can be | |
| 3 # found in the LICENSE file. | |
| 4 | |
| 5 import functools | |
| 6 import logging | |
| 7 | |
| 8 | |
| 9 def Memoize(f): | |
|
jbudorick
2017/01/31 16:11:53
I could've sworn that we had this somewhere, but I
mikecase (-- gone --)
2017/01/31 23:08:25
A slightly different implementation of this existe
| |
| 10 """Decorator to cache return values of function.""" | |
| 11 | |
| 12 memoize_dict = {} | |
| 13 @functools.wraps(f) | |
| 14 def wrapper(*args, **kwargs): | |
| 15 key = repr((args, kwargs)) | |
|
jbudorick
2017/01/31 16:11:53
4 space indents...? Did you lift this from somewhe
mikecase (-- gone --)
2017/01/31 23:08:25
...
| |
| 16 if key not in memoize_dict: | |
| 17 try: | |
| 18 memoize_dict[key] = f(*args, **kwargs) | |
| 19 except Exception as e: # pylint: disable=broad-except | |
| 20 memoize_dict[key] = e | |
| 21 raise | |
| 22 return_value = memoize_dict[key] | |
| 23 if isinstance(return_value, Exception): | |
| 24 raise return_value | |
| 25 return return_value | |
| 26 return wrapper | |
| 27 | |
| 28 | |
| 29 def NoRaiseException(default_return_value=None): | |
| 30 """Returns decorator that catches and logs uncaught Exceptions. | |
| 31 | |
| 32 Args: | |
| 33 default_return_value: Value to return in the case of uncaught Exception. | |
| 34 """ | |
| 35 def decorator(f): | |
| 36 @functools.wraps(f) | |
| 37 def wrapper(*args, **kwargs): | |
| 38 try: | |
| 39 return f(*args, **kwargs) | |
| 40 except Exception: # pylint: disable=broad-except | |
| 41 logging.exception('message') | |
|
jbudorick
2017/01/31 16:11:53
You're just going to log 'message'?
mikecase (-- gone --)
2017/01/31 23:08:25
I mean, logging.exception will log the exception.
jbudorick
2017/01/31 23:15:12
Can it be an additional argument to NoRaiseExcepti
| |
| 42 return default_return_value | |
| 43 return wrapper | |
| 44 return decorator | |
| OLD | NEW |