Skip to content

Instantly share code, notes, and snippets.

@jasongrout
Created September 29, 2012 17:46
Show Gist options
  • Save jasongrout/3804691 to your computer and use it in GitHub Desktop.
Save jasongrout/3804691 to your computer and use it in GitHub Desktop.
run once decorator
# from http://stackoverflow.com/questions/4103773/efficient-way-of-having-a-function-only-execute-once-in-a-loop
from functools import wraps
def run_once(f):
"""Runs a function (successfully) only once.
The running can be reset by setting the `has_run` attribute to False
"""
@wraps(f)
def wrapper(*args, **kwargs):
if not wrapper.has_run:
result = f(*args, **kwargs)
wrapper.has_run = True
return result
wrapper.has_run = False
return wrapper
@run_once
def load_ipython_extension(ip):
"""Load the extension in IPython."""
# do work
pass
@drunkpig
Copy link

drunkpig commented Dec 1, 2020

it has something wrong when reload or restart app

@wraps(f)
    def wrapper(*args, **kwargs):
        if not f.has_run:
            result = f(*args, **kwargs)
            f.has_run = True
            return result
    f.has_run = False
    return wrapper

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment