katja
katja

Reputation: 137

python: is there anyway to initialize a variable only one time?

I want to do matching my time-series data to meta data from a given file.

In my code, main function calls "create_match()" function every 1 minute. Inside "create_match(), there is a "list_from_file()" function to read data from file and store in lists to perform matching.

The problem is that my code is not effective since every 1 minute, it reads the file and rewrite in the same lists. I want to read file only one time (to initialize lists only one time), and after that ignoring the "list_from_file()" function. I do not want to just move this task to main function and pass lists through function.

Does python have a special variable like static variable in c programming?

Upvotes: 7

Views: 27413

Answers (3)

Mike Müller
Mike Müller

Reputation: 85482

You can use a class:

class Match (object):
    def __init__(self):
        self.data = list_from_file()
    def create_match(self):
        # do something with `self.data` here

Make an instance:

match = Match()

This calls list_from_file().

Now, you can call create_match() repeatedly with access to self.data

import time
for x in range(10):
    match.create_match()
    time.sleep(60)

Upvotes: 3

Mark Ransom
Mark Ransom

Reputation: 308206

There are lots of ways.

You can make a variable part of a class - not a member of the object, but of the class itself. It is initialized when the class is defined.

Similarly you can put a variable at the outer level of a module. It will belong to the module, and will be initialed when the module is imported the first time.

Finally there's the hack of defining an object as a default parameter to a function. The variable will be initialized when the function is defined, and will belong to the function. You will only be able to access it with the parameter name, and it can be overridden by the caller.

Upvotes: 2

Brendan Abel
Brendan Abel

Reputation: 37539

Python does not have a static variable declaration; however, there are several fairly standard programming patterns in python to do something similar. The easiest way is to just use a global variable.

Global Variables

Define a global variable and check it before running your initialize function. If the global variable has already been set (ie. the lists you're reading in), just return them.

CACHE = None

def function():
    global CACHE
    if CACHE is None:
        CACHE = initialize_function()
    return CACHE

Upvotes: 16

Related Questions