Home > OS >  How to use a function to re-evaluate a previously evaluated variable in Python?
How to use a function to re-evaluate a previously evaluated variable in Python?

Time:10-20

I have a text file called number.txt. The content of number.txt is a single string "10", is then read into a variable called "data". A new variable "var_to_eval" is then created and data is then assigned to it as its value.

I also have a function "f1" which should receive var_to_eval as its default argument. The role of the function is to add 10 to the value contained in number.txt then save the new value into number.txt.

I am using the schedule library [https://github.com/dbader/schedule][1] to re-run ONLY the function f1 in an endless loop to read the file, add 10 to the content then save the file again.

But because var_to_eval is only evaluated ONCE when the code runs, when schedule runs the function, the value passed in from var_to_eval as the function argument is not the updated value but the initial one.

import schedule
import time

with open ("number.txt", "r") as myfile:
    data = int(myfile.read())
    var_to_eval = data
 
def f1(arg1 = var_to_eval):
    global var_to_eval
    print(arg1)    
    arg1  = 10
    with open("number.txt", "w") as myfile:
        myfile.write(str(arg1))
     
    var_to_eval = arg1
    

schedule.every(3).seconds.do(f1)

while True:
    schedule.run_pending()
    time.sleep(1)

Output:

20
20
20

I could include

with open ("number.txt", "r") as myfile:
    data = int(myfile.read())
    var_to_eval = data

WITHIN the function to solve the problem, however, I would like to find a solution where regardless of how many times the function is re-run by "schedule" there is no more than ONE read operation is performed from the hard drive and the updated data is read from the memory.

When coded correctly the output of the code would be then:

20
30
40
.
.
.

So I would like to reiterate that the accepted solution can only contain ONE initial read operation from the hard drive.

If further clarification is required to answer the question please ask, and I will try my best to describe the problem further.

(for reference concerning how schedule is used please refer to the code snipet below):

import schedule import time

def job(): print("I'm working...")

schedule.every(3).seconds.do(job)

while True: schedule.run_pending() time.sleep(1)

CodePudding user response:

the default parameter of f1 is evaluated only once. So every time you call the function with no further arguments you just tell it to take the first value of var_to_evaluate and add 10. You can do something like that:

def f1(arg1 = None):
    global var_to_eval
    if arg1==None:
        arg1=var_to_eval
    print(arg1)    
    arg1  = 10
    with open("number.txt", "w") as myfile:
        myfile.write(str(arg1))
 
    var_to_eval = arg1
  • Related