How to Use Static Variables in Python Functions?

Recently someone asked me how to use static variables in Python functions. After researching various methods I found three important methods to implement static variables in Python. In this tutorial, I will explain all important methods and real-world examples with screenshots of executed example code.

Static Variables in Python

Static variables in Python are variables that retain their value between function calls. Unlike regular local variables, which are re-initialized every time a function is called, static variables maintain their state. This is particularly useful in scenarios where you need to keep track of information across multiple invocations of a function.

Read How to Use Python Functions with Optional Arguments?

Use Static Variables in Python Functions

Python does not have a built-in static keyword like some other programming languages. However, there are several ways to achieve similar functionality. Let’s explore these methods in detail.

1. Use Default Mutable Arguments

One way to create static variables is by using default mutable arguments, such as lists or dictionaries. This method leverages the fact that default arguments are evaluated only once when the function is defined, not each time it is called.

def track_visits(visitor_log={}):
    visitor_log['count'] = visitor_log.get('count', 0) + 1
    return visitor_log['count']

# Example usage
print(track_visits()) 
print(track_visits())  
print(track_visits())  

Output:

1
2
3

You can refer to the screenshot below to see the output.

Use Static Variables in Python Functions

In this example, the visitor_log dictionary retains its state between function calls, effectively acting as a static variable.

Check out How to Use Lambda Functions in Python?

2. Use Function Attributes

Another way to implement static variables is by using function attributes. This method involves attaching attributes directly to the function object.

def track_sales():
    if not hasattr(track_sales, "total_sales"):
        track_sales.total_sales = 0  # Initialize the static variable
    track_sales.total_sales += 1
    return track_sales.total_sales

# Example usage
print(track_sales())
print(track_sales())  
print(track_sales()) 

Output:

1
2
3

You can refer to the screenshot below to see the output.

How to Use Static Variables in Python Functions

Here, the total_sales attribute of the track_sales function retains its value across calls, functioning as a static variable.

Read How to Use the Python Main Function with Arguments?

3. Use a Class

A more structured approach to using static variables is by encapsulating the function within a class and using class variables.

class VisitorCounter:
    count = 0  # Class variable acting as a static variable

    @staticmethod
    def increment():
        VisitorCounter.count += 1
        return VisitorCounter.count

# Example usage
print(VisitorCounter.increment()) 
print(VisitorCounter.increment())
print(VisitorCounter.increment())  

Output:

1
2
3

You can refer to the screenshot below to see the output.

Use Static Variables in Python Functions use a class

In this example, the count variable is shared among all instances of the VisitorCounter class, making it a static variable.

Check out How to Use Exponential Functions in Python?

Example: Track Website Visits

Let’s consider a real-world scenario where we want to track the number of visits to different sections of a website. We’ll use the function attribute method to implement this.

def track_section_visits(section):
    if not hasattr(track_section_visits, "visits"):
        track_section_visits.visits = {}  # Initialize the static variable
    if section not in track_section_visits.visits:
        track_section_visits.visits[section] = 0
    track_section_visits.visits[section] += 1
    return track_section_visits.visits[section]

# Example usage
print(track_section_visits("home"))  # Output: 1
print(track_section_visits("about"))  # Output: 1
print(track_section_visits("home"))  # Output: 2
print(track_section_visits("contact"))  # Output: 1
print(track_section_visits("about"))  # Output: 2

In this example, we track visits to different sections of a website, such as “home,” “about,” and “contact.” The visits dictionary retains its state between function calls, allowing us to accumulate visit counts for each section.

Read How to Use Counter Function in Python?

Performance Considerations

While static variables can be incredibly useful, it’s important to be mindful of their impact on performance and memory usage. Since static variables retain their state, they can potentially consume more memory, especially if they store large amounts of data. Always consider the specific requirements of your application and use static variables judiciously.

Raad How to Use wait() Function in Python?

Best Practices

  1. Initialization: Ensure that static variables are properly initialized before use.
  2. Documentation: Document the use of static variables to make your code more readable and maintainable.
  3. Encapsulation: Consider using classes to encapsulate static variables, especially for more complex use cases.
  4. Thread Safety: Be cautious when using static variables in multithreaded applications, as they can lead to race conditions. Use synchronization mechanisms like locks if necessary.

Check out How to Create a Square Function in Python?

Conclusion

I have explained how to use static variables in Python functions. I discussed using default mutable arguments , using function attributes , and using a class. I also covered real-world examples, performance considerations, and some best practices.

You may read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.