Skip to content

Commit

Permalink
[util] Add a decorators utility module.
Browse files Browse the repository at this point in the history
  • Loading branch information
ChrisCummins committed Mar 19, 2021
1 parent 6fcd2af commit 50b9ac1
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
1 change: 1 addition & 0 deletions compiler_gym/util/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ py_library(
"__init__.py",
"capture_output.py",
"debug_util.py",
"decorators.py",
"download.py",
"logs.py",
"minimize_trajectory.py",
Expand Down
29 changes: 29 additions & 0 deletions compiler_gym/util/decorators.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import functools
from typing import Any, Callable


def memoized_property(func: Callable[..., Any]) -> Callable[..., Any]:
"""A property decorator that memoizes the result.
This is used to memoize the results of class properties, to be used when
computing the property value is expensive.
:param func: The function which should be made to a property.
:returns: The decorated property function.
"""
attribute_name = "_memoized_property_" + func.__name__

@property
@functools.wraps(func)
def decorator(self):
if not hasattr(self, attribute_name):
setattr(self, attribute_name, func(self))

return getattr(self, attribute_name)

return decorator

0 comments on commit 50b9ac1

Please sign in to comment.