Run a Function only Once in Python

avatar

Borislav Hadzhiev

Last updated: Aug 17, 2022

banner

Photo from Unsplash

Run a Function only Once in Python #

To run a function only once:

  1. Declare a global variable and initialize it to False.
  2. Change the value of the global variable to True in the function.
  3. Only run the code in the function if the global variable is set to False.
main.py
# ✅ Run function only once (using global variable) sum_has_run = False def sum(a, b): global sum_has_run if sum_has_run: return sum_has_run = True return a + b print(sum(100, 100)) # 👉️ 200 print(sum(100, 100)) # 👉️ None # ---------------------------- # ✅ Run function only once (using attribute on the function) def sum(a, b): if getattr(sum, 'has_run', False): return sum.has_run = True return a + b print(sum(100, 100)) # 👉️ 200 print(sum(100, 100)) # 👉️ None

The first example uses a global variable to run a function only once.

We initialize the global variable to False and set its value to True in the function.

If the value of the global variable is equal to True, we return from the function straight away.

main.py
sum_has_run = False def sum(a, b): global sum_has_run if sum_has_run: return sum_has_run = True return a + b print(sum(100, 100)) # 👉️ 200 print(sum(100, 100)) # 👉️ None
If the value of the global variable is not equal to True, we set its value to True and run the function.

This only happens the first time the function is invoked.

Once the global variable is set to True, the function returns None without running any code.

An alternative approach is to use an attribute on the function.

To run a function only once:

  1. Set a has_run attribute on the function to True the first time it runs.
  2. Each time the function is called, check if the has_run attribute is True and return straight away.
  3. The code in the function will only run the first time.
main.py
def sum(a, b): if getattr(sum, 'has_run', False): return sum.has_run = True return a + b print(sum(100, 100)) # 👉️ 200 print(sum(100, 100)) # 👉️ None

We set the has_run attribute to True the first time the function is called.

The getattr function returns the value of the provided attribute of the object.

The function takes the object, the name of the attribute and a default value for when the attribute doesn't exist on the object as parameters.

If the has_run attribute is not set on the function, we return a default value of False.

We check for the value of the has_run attribute each time the function runs and if its value is set to True, we return from the function straight away.

If the has_run attribute is not set, the code in the function runs and sets the attribute to True.

The code in the function is only run once.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.