How to compile a multi-line function definition ?

Fredrik Lundh fredrik at pythonware.com
Thu May 13 13:57:32 EDT 1999


Jerome ALET <alet at unice.fr> wrote:
> I've just read the complete Python's documentation (well, almost :-) and
> I've found nothing to solve my problem. This doc is very good but lacks
> examples, IMHO.
> 
> Given the following sample of code which works fine in Python 1.5.2, I
> want to know how to define a multi-line "my_function". Every time I try
> something I get a syntaxerror or something similar.
> 
> -------- CUT ------------
> # mytest.py
> # module to do some testing
> class MyClass :
>         loc = locals()
>         def __init__(self) :
>                 exec(compile("def my_function(self, a, b) : print a, b,
> '<==>', b, a""", "<string>", "exec"), self.loc)
> ---------- CUT ----------

use newlines in the string (\n).  however, you must make
sure that the code is valid Python (that is, the identation
must be correct, etc), and that you have a newline or two
at the end.

here's a class that you may find somewhat helpful:

#
# a Python code generator backend
#
# fredrik lundh, march 1998
#
# fredrik at pythonware.com
# http://www.pythonware.com
#

import sys, string

class CodeGeneratorBackend:
    
    def begin(self, tab="\t"):
        self.code = []
        self.tab   = tab
        self.level = 0

    def end(self):
        return string.join(self.code, "\n")

    def compile(self):
        return compile(self.end() + "\n", "<string>", "exec")

    def write(self, string):
        self.code.append(self.tab * self.level + string)

    def indent(self):
        self.level = self.level + 1 

    def dedent(self):
        if self.level == 0:
            raise SyntaxError, "internal error in code generator"
        self.level = self.level - 1 

if __name__ == "__main__":
    c = CodeGeneratorBackend()
    c.begin(tab="    ")
    c.write("for i in range(1000):")
    c.indent()
    c.write("print 'code generation is trivial'")
    c.dedent()
    exec c.compile()

</F>





More information about the Python-list mailing list