once_()
Creates a function that is restricted to execute `func` once. Subsequent calls return the value of the first invocation.
Implementation
Args: func: The function to execute. Returns: A new function that wraps `func`, ensuring it is only called once.
Example
def greet():
return "Hello!"
greet_once = once_(greet)
greet_once() # "Hello!"
greet_once() # "Hello!"
Expected output:
Source Code
def once_(func):
called = False
result = None
def wrapper(*args, **kwargs):
nonlocal called, result
if not called:
result = func(*args, **kwargs)
called = True
return result
return wrapper