0

I've read this post How to call a function from another file in Python to see how a function can be loaded from another file. I have production code that runs all day and I want to be able to change only one function in that code to test/change output. I don't want to restart the program each time I need to verify my changes were successful.

Is there a mechanism to load the function each time it's called instead of importing the function at the beginning of the program and using the same code throughout the life of that particular instance? I moved the import statement from the beginning of the program into a loop, and the same output is observed no matter how much I change the function in the accompanying file.

A similar analogy would be HTML and CSS styling. I can have separate files there and change the CSS to change the output of the HTML without actually touching the HTML.

Community
  • 1
  • 1
user208145
  • 369
  • 4
  • 13

2 Answers2

1

There is indeed a way to make the changes made to an external module reflected in a program/python session without having to restart the program . We can use the reload() method (or importlib.reload() for Python 3.x, if anyone is interested) . Example -

...
import <module>
reload(<module>)         

But please note, you would need to do this whenever you want to reload the module.

I would say it would not be a good design to have a python program run for a long time, if it keeps repeating itself in specific iterval . It would be a better design to have a cron job or external scheduler run the python program when needed. In case the complete python program is restarted, reloading the module would not be needed, since Python would always take load the module again for each run.

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
0

You can use the importlib.reload function instead if you're using Python 3. For Python 2, use just reload.

import MyModuleWithAFunction
import importlib
...
importlib.reload(MyModuleWithAFunction)

Read more here.

Ownaginatious
  • 787
  • 4
  • 14