Skip to content

Instantly share code, notes, and snippets.

@a-recknagel
Created April 24, 2023 12:12
Show Gist options
  • Save a-recknagel/8e91236d1bd0b2b1e38190d52279113f to your computer and use it in GitHub Desktop.
Save a-recknagel/8e91236d1bd0b2b1e38190d52279113f to your computer and use it in GitHub Desktop.
Scoped decorator
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