Is there idiomatic way to reload python modules on edit? I am keeping configuration in my_config_module.py file and want to automatically detect and load config changes. Currently I am trying something like this but I find it ugly and unsafe:
import my_config_module
import importlib
last_modification = os.stat('my_config_module.py').st_mtime
while True:
last_mod = os.stat('my_config_module.py').st_mtime
if last_mod != last_modification:
importlib.raload(my_config_module)
last_modification = last_mod
# main loop, some of my code
asked Oct 28, 2019 at 13:48
bartop
10.5k1 gold badge28 silver badges67 bronze badges
1 Answer 1
You should keep data in a separate file and reload it when it's modified (and thus, avoiding the need of reloading code).
answered Oct 28, 2019 at 13:54
luis.parravicini
1,26711 silver badges20 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
bartop
this is what I wanted to avoid, don't want to parse anything from json or xml
gstukelj
This should be a comment not an "answer".
blubberdiblub
@gst They still have a point, though. Configuration should usually be kept in a format that lends itself well to storing configuration data, not in code. (Also: safety). If OP doesn't like JSON, they can use YAML or TOML or similar that has a friendlier structure. Python modules are not meant to be reloaded on a regular basis.
gstukelj
@blubberdiblub I was not questioning the validity of the raised point and I did not downvote the answer, just voiced my opinion by posting a comment.
lang-py
watchdogmodule might be helpful.