Parse Python file and evaluate selected functions
Question: I have a file that contains several python functions, each with some
statements.

    
    
    def func1():
        codeX...
    def func2():
        codeY...
    

codeX and codeY can be multiple statements. I want to be able to parse the
file, find a function by name, then evaluate the code in that function.

With the ast module, I can parse the file, find the FunctionDef objects, and
get the list of Stmt objects, but how do I turn this into bytecode that I can
pass to eval? Should I use the compile module, or the parser module instead?

Basically, the function defs are just used to create separate blocks of code.
I want to be able to grab any block of code given the name and then execute
that code in eval (providing my own local/global scope objects). If there is a
better way to do this than what I described that would be helpful too.

Thanks


Answer: > I want to be able to grab any block of code given the name and then execute
> that code ... (providing my own local/global scope objects).

A naive solution looks like this. This is based on the assumption that the
functions don't all depend on global variables.

    
    
    from  file_that_contains_several_python_functions import *
    Direction = some_value
    func1()
    func2()
    func3()
    

That _should_ do exactly what you want.

However, if all of your functions rely on global variables -- a design that
calls to mind 1970's-era FORTRAN -- then you have to do something slightly
more complex.

    
    
     from  file_that_contains_several_python_functions import *
     Direction = some_value
     func1( globals() )
     func2( globals() )
     func3( globals() )
    

And you have to rewrite all of your global-using functions like this.

    
    
     def func1( context )
         globals().update( context )
         # Now you have access to all kinds of global variables
    

This seems ugly because it is. Functions which rely entirely on global
variables are not really the best idea.

