blob: dca5a1800b95540f36c9167dd87ccc79b228a4a9 [file] [log] [blame]
# Copyright 2020 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Helper functions for common boilerplate tasks.
Top-level functions can be imported and used directly (without needing a
`RecipeApi` object) using `RECIPE_MODULES` imports. E.g.:
```
from RECIPE_MODULES.fuchsia.utils.api import memoize
@memoize
def expensive_computation(inputs):
return do_work(inputs)
def RunSteps(api, ...):
expensive_computation(...)
```
"""
import functools
from recipe_engine import recipe_api
def memoize(func):
"""A decorator to cache the return values of a function by args/kwargs."""
cache = {}
@functools.wraps(func)
def wrapper(*args, **kwargs):
key = (args, frozenset(kwargs.iteritems()))
if key not in cache:
cache[key] = func(*args, **kwargs)
return cache[key]
return wrapper
class CodeUtilsApi(recipe_api.RecipeApi):
memoize = staticmethod(memoize)