I was wondering about ways to add new lines to already running code (it could even be a simple while loop) and run it. But this way of creating and importing a class or functions always runs the first added lines of code even if you have changed the function and imported it again.
I tried adding del main, and replacing the line data = main(data) with data = main(data).copy(), but both haven't given any result. Any error or log does not occur, I added info in the steps for understanding.
CODES:
def applyCommand(data, command):
with open('/$PATH/simple_macro.py', 'w') as file:
file.write(command)
print('[INFO] simple macro has been written- step 1 ✓.')
from simple_macro import main
print('[INFO] simple macro has been imported - step 2 ✓.')
data = main(data)
print('[INFO] data has been updated - step 3 ✓.')
from os import remove
remove('/$PATH/simple_macro.py')
print('[INFO] simple macro file has been deleted - step 4 ✓.')
return data
data = list(range(10))
command = "def main(data):\n return data[:5]"
data = applyCommand(data, command)
print("Updated data:", data)
commandTwo = "def main(data):\n return data[0]"
data = applyCommand(data, commandTwo)
print("Updated data:", data)
OUTPUT:
[INFO] simple macro has been written- step 1 ✓.
[INFO] simple macro has been imported - step 2 ✓.
[INFO] data has been updated - step 3 ✓.
[INFO] simple macro file has been deleted - step 4 ✓.
Updated data: [0, 1, 2, 3, 4]
[INFO] simple macro has been written- step 1 ✓.
[INFO] simple macro has been imported - step 2 ✓.
[INFO] data has been updated - step 3 ✓.
[INFO] simple macro file has been deleted - step 4 ✓.
Updated data: [0, 1, 2, 3, 4]
The first part produces the correct expected output, but the second one's expected output is just 0 but the actual output is [0, 1, 2, 3, 4] as you see.
So the question is what type of addition or change can be done to that code cells to get expected output after the first call?