-
Notifications
You must be signed in to change notification settings - Fork 130
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[util] Add a decorators utility module.
- Loading branch information
1 parent
6fcd2af
commit 50b9ac1
Showing
2 changed files
with
30 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |