This is my first post, so please let me know if I do it wrong. I tried to find an existing answer, but was not sure what to look for.
Consider the following simple example: a python module named mymath.py that uses only built-in operations and python modules. This custom module is portable, so anyone can execute code without installing any other than python.
Note that main() only calls sum_series() , which in turn calls plus() . Other functions may be required elsewhere in this fictitious code base, but we are only concerned about main() .
Now I would like to copy only the corresponding source code into another object as a text string. In other words, compile main() and all its dependencies (recursively), resulting in a line of executable code.
My current solution:
import inspect import mymath
This works by creating a local copy of the module as a string that can run main() without requiring import of mymath . The problem is that knob now bloated with all the extra unused functions, although it is able to pick up any changes I make for mymath.py , reusing my current solution.
So the question is is there a way to make an equivalent:
source = getFunctionSourcerRecursively(mymath.main) source += "\nmain()"
whereby source =
# mymath.py import sys def plus(a, b): return a+b def sum_series(int_list): sum = 0 for i in int_list: sum = plus(sum, i) return sum def main(): my_list = [2, 4, 6] sys.stdout.write("your list total = {}".format(sum_series(my_list))) main()
Thus, basically the “source” now contains only the corresponding code and is portable, without requiring people outside my site to install mymath.
If you're interested, in my real case, I use the Foundry Nuke application (the build application), which has an internal callback system that can run code when callback events are knob on knob (property). I want to be able to share these saved Nuke files ( .nk or .nknc ) with remote clients, without requiring them to modify their system.