Home > Software engineering >  Rename a variable each time the code is run (python)?
Rename a variable each time the code is run (python)?

Time:10-26

I have a bit of python code that's set to run on a schedule. (I think my problem is the same as if it were within a loop.)

Let's say that in its most basic form, the code snippet looks something like this:

A = 1
B = 2
renameMe = A   B

Let's say the scheduler runs the same snippet of code every 5 minutes. The values of variables A & B are different each time the code is run, but the operation renameMe = A B is always the same.

The values for A & B are grabbed out of a dataframe that's updated every 5 minutes, so I don't know what they are in advance, but if I need to do something with them beforehand instead of assigning them to A & B right away, I can.

I recently found out that for other things to work, I need to be able to rename the variable renameMe every time that snippet of code runs. In other words, I want the variable's name to be renameMe1 the first time the code snippet runs, then renameMe2 when it runs 5 minutes later, and so on.

It doesn't really matter in which way the variable's name changes (ints, strs, whatever) as long as I'm able to find out what the new variable name is, and use it elsewhere.

CodePudding user response:

Do NOT use a variable variable name, you will have problems, use a container:

a list:

# first time
container = []

# each loop/run
container.append(A B)

## last value
container[-1]

a dictionary:

# first time
container = {}

# each loop/run
container['new_id'] = A B

# access arbitrary value
container['my_previous_id']

If you need persistence, use a flat file or a database.

CodePudding user response:

I think it is suitable to use a class so that setattr can be used:

class newVal:
    def __init__(self):
        self.n = 1

    def addVal(self, a, b):
        setattr(self, f”val{self.n}”, a b)
        self.n  = 1

Values = newVal()
Values.addVal(a, b)

Values.val1 would now be assigned

  • Related