Welcome to the Monastery | |
PerlMonks |
Making a reloadable module, allowing "live" editsby pryrt (Abbot) |
on Apr 09, 2022 at 22:44 UTC ( [id://11142879]=CUFP: print w/replies, xml ) | Need Help?? |
I was recently watching this youtube video on a simple PID controller implemented in Python (it was in a watchlist of math-related videos, though his PID was more math-adjacent than math-focused). But instead of focusing on the controller algorithm, I was intrigued by his demo environment, where he was able to update his python code live, and have the demo program automatically incorporate the changes immediately, without reloading the demo program. I followed his link to the repo for his demo, where he explains his reloadable.py module and how that portion works. "That should be doable in Perl," said I. "And I might even be able to do it." And indeed, after some effort, I could. He basically used a class variable to store the state of the module-under-development ("mod"), then used a loop in his demo program that every loop would check the timestamp on the mod's file, and if it was newer, he would store the state, then reload the mod and return a new instance of the mod object initialized to the stored state. In my example, which I will replicate in the spoiler, I did something similar, but I just stored the state in the instance of my reloadable object, and had the loop read the state from there and pass it as an option when creating the instance from the reloaded package. (My implementation isn't clean enough for CPAN or anything like that, but as toy, I thought it was a pretty cool usage of Perl, and is good enough for a proof-of-concept.)
My implementation maps his parent class in reloadable.py to Reloadable.pm; his intersin.py is the example wrapper that contains the loop calling the function(s) in his module under development, which maps to my tryReload.pl; his module under development, which is a subclass of Reloadable, was sinecalc.py, which I have mapped to SineCalculatorReloadable.pm.
Reloadable.pm
SineCalculatorReloadable.pm
tryReload.pl
The funny thing is, a few days after I implemented it, as I was finishing up debug of something or other, where I was reloading my program quite frequently, I realized just as I was finishing up, "that would have been a perfect time to use Reloadoadable. DOH!". If this has piqued your interest, I would love to see, and learn from, how some of the other monks would implement this. You don't have to use the sine calculator as your example; I just thought it was a simple enough example for the proof of concept. If you wanted to do all the graphics to replicate his PID ship controller instead, by all means... ;-)
Back to
Cool Uses for Perl
|
|