Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hot swapping python code (duck type functions?)

I've been thinking about this far too long and haven't gotten any idea, maybe some of you can help.

I have a folder of python scripts, all of which have the same surrounding body (literally, I generated it from a shell script), but have one chunk that's different than all of them. In other words:

Top piece of code (always the same)
Middle piece of code (changes from file to file)
Bottom piece of code (always the same)

And I realized today that this is a bad idea, for example, if I want to change something from the top or bottom sections, I need to write a shell script to do it. (Not that that's hard, it just seems like it's very bad code wise).

So what I want to do, is have one outer python script that is like this:

Top piece of code
Dynamic function that calls the middle piece of code (based on a parameter)
Bottom piece of code

And then every other python file in the folder can simply be the middle piece of code. However, normal module wouldn't work here (unless I'm mistaken), because I would get the code I need to execute from the arguement, which would be a string, and thus I wouldn't know which function to run until runtime.

So I thought up two more solutions:

  1. I could write up a bunch of if statements, one to run each script based on a certain parameter. I rejected this, as it's even worse than the previous design.
  2. I could use:

    os.command(sys.argv[0] scriptName.py)

    which would run the script, but calling python to call python doesn't seem very elegant to me.

So does anyone have any other ideas? Thank you.

like image 373
Leif Andersen Avatar asked Dec 28 '22 09:12

Leif Andersen


2 Answers

If you know the name of the function as a string and the name of module as a string, then you can do

mod = __import__(module_name)
fn = getattr(mod, fn_name)
fn()
like image 177
aaronasterling Avatar answered Dec 31 '22 14:12

aaronasterling


Another possible solution is to have each of your repetitive files import the functionality from the main file

from topAndBottom import top, bottom
top()
# do middle stuff
bottom()
like image 34
cobbal Avatar answered Dec 31 '22 13:12

cobbal