How to compile a multi-line function definition ?

Jerome ALET alet at unice.fr
Thu May 13 13:08:48 EDT 1999


Hi there,

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 ----------

Nota Bene: here the exec is on 2 lines but in reality it's on a single
line.

This sample code adds a method my_function to MyClass.

I want to do this for a more complicated function.

Any help is welcome.

PS: a CC would be greatly appreciated.

Thanks in advance.

-- 
Jerome ALET




More information about the Python-list mailing list