Created
April 24, 2023 12:12
-
-
Save a-recknagel/8e91236d1bd0b2b1e38190d52279113f to your computer and use it in GitHub Desktop.
Scoped decorator
This file contains hidden or 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
from functools import wraps | |
SENTINEL = object() | |
def run_once(func): | |
"""Decorator which ensures that a function is only executed a single time.""" | |
class Scope: | |
locals = {"result": SENTINEL} | |
@staticmethod | |
@wraps(func) | |
def wrapper(*args, **kwargs): | |
if Scope.locals["result"] is SENTINEL: | |
Scope.locals["result"] = func(*args, **kwargs) | |
return Scope.locals["result"] | |
Scope.wrapper.__scope__ = Scope.locals # so I can overwrite at runtime | |
return Scope.wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment