An idiom for code generation with exec

eliben eliben at gmail.com
Sat Jun 21 02:14:06 EDT 2008


On Jun 20, 2:44 pm, Peter Otten <__pete... at web.de> wrote:
> eliben wrote:
> > Additionally, I've found indentation to be a problem in such
> > constructs. Is there a workable way to indent the code at the level of
> > build_func, and not on column 0 ?
>
> exec"if 1:" + code.rstrip()
>
> Peter

Why is the 'if' needed here ? I had .strip work for me:

def make_func():
    code = """
        def foo(packet):
            return ord(packet[3]) + 256 * ord(packet[4])
        """

    d = {}
    exec code.strip() in globals(), d
    return d['foo']

Without .strip this doesn't work:

Traceback (most recent call last):
  File "exec_code_generation.py", line 25, in <module>
    foo = make_func()
  File "exec_code_generation.py", line 20, in make_func
    exec code in globals(), d
  File "<string>", line 2
    def foo(packet):
    ^
IndentationError: unexpected indent




More information about the Python-list mailing list