Reputation: 21
I have a function that changes the module based on a passed function then import that module to use it. but when I change the module once then import it, it's as intended then I changed it again with no time delay the imported module is just it was in the first change
this is the function that creates the module
import sys
from time import sleep
def get_fun(text_fun):
with open('plotFun.py', 'w') as plotFun:
plotFun.write(f'class FunctionObject():\n\tdef function_object(self, x=None):\n\t\ty = {text_fun}\n\t\treturn "{{:.2f}}".format(y)')
# import the created class
if 'plotFun' not in sys.modules:
from plotFun import FunctionObject
else:
del sys.modules["plotFun"]
from plotFun import FunctionObject
# create an instance of the created class
my_fun = FunctionObject()
# check if the function inputted from user is a valid function
try:
my_fun.function_object(3.14)
except NameError:
raise ValueError('Invalid Function')
# pass any other errors, they will be found later when the function is used.
except:
pass
return my_fun
def main():
y1 = get_fun('2*3')
print(y1.function_object())
sleep(1)
y2 = get_fun('3*3')
print(y2.function_object())
main()
with this code the print is 6.00 9.00 but if I removed sleep(1) both print are 6.00 I tried sleep(0.1) but still both are 6.00 but when I tried sleep(0.7) it changed. it's like I have to delay for a specific time for the function to change
Upvotes: 2
Views: 215
Reputation: 40033
Python reuses the byte-compiled version of your module if the source appears to be unmodified. The default mechanism is based on the size and modification time of the file: the size doesn’t change here, and the modification time is stored/checked with a granularity of, often, 1 second.
Upvotes: 1