UniCoreFW

once()

Ensure a function is only called once, returning None on subsequent calls. Thread-safe implementation that matches your test expectations.

Implementation

Args: func: The function to wrap Returns: A function that will only execute once, then return None

Example

wrapped_func = once(lambda: "called") wrapped_func() # Returns "called"

Expected output: 'called'

Alternative usage:

wrapped_func() # Returns None

Expected output: None

Source Code

def once(func: Callable) -> Callable: result = [None] has_been_called = [False] lock = threading.Lock() def once_func(*args, **kwargs): with lock: # Thread-safe check-and-set if not has_been_called[0]: result[0] = func(*args, **kwargs) has_been_called[0] = True return result[0] # Return the actual result on first call else: return None # Return None on subsequent calls return once_func