Rename a variable each time the code is run (python)?

Question:

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.

Asked By: Elena House

||

Answers:

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.

Answered By: mozway

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

Answered By: Kosmos

I aggree with Mozway when saying variables names are likely to cause problems, but this is also something you could strictly manage.

globals() stores all variables names and values in the form of a collection of 2-tuples, like this one :

dict_items([('__name__', '__main__'), ..., ('thisName', 'renaMe1'), ('renaMe18', 10)])

So you should register your new variable name but not forget to delete the previous one in order to avoid overloading.

If you follow a natural law of equal births and deaths, you will avoid overpopulation.

I propose you this bunch of code (with comments inside) :

basename = 'renaMe'

def varUpdate():
    # Get previous variable name
    thisName = [i for i, j in globals().items() if i[:len(basename)] == basename][0]
    # Define the new variable name
    newName = basename + '%d'%sum([int(thisName[len(basename):]), 1])
    # Register the new variable name
    globals()[newName] = globals()[thisName]
    # Delete previous variable name from global
    del globals()[thisName]

def process(i):
    # Isolate from process content for readibility
    varUpdate()
    # PROCESS BELOW
    # ....
    newVar = [i for i, j in globals().items() if i[:len(basename)] == basename][0]
    print(newVar, " : ", globals()[newVar])

    
# With this for` loop we simulate 4 entries in process
for i in range(4):
    ### we enter in the process
    process(i)

Test in the shell

First restart your shell and let’s suppose we have at the beginning renaMe12 = 12 :

>>> renaMe12 = 12
>>> Proposed Script ...

Result

Variable increments it’s proper name at each iteration.

renaMe13  :  12
renaMe14  :  12
renaMe15  :  12
renaMe16  :  12

If you check in the shell now, you could see at the end of iteration, renaMe12 to renaMe15 no longer exist.

Only the variable renaMe16 exists with value 12.

>>> renaMe16
12
>>>> renaMe15
Retraçage (dernier appel le plus récent) : 
  Shell Python, prompt 4, line 1
builtins.NameError: name 'renaMe15' is not defined

Conclusion

This discussion is just for the sake of experimentation, but if I were you I would do my possible to avoid such code complexification unless it’s necessary.
I agree Mozway when thinking you should avoid pain headaches…

Answered By: Laurent B.
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.