An idiom for code generation with exec

Peter Otten __peter__ at web.de
Sat Jun 21 08:52:57 CEST 2008


eliben wrote:

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

A simple .strip() doesn't work if the code comprises multiple lines:

>>> def f():
...     return """
...     x = 42
...     if x > 0:
...             print x
...     """
...
>>> exec "if 1:\n" + f().rstrip()
42
>>> exec f().strip()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 2
    if x > 0:
    ^
IndentationError: unexpected indent

You can of course split the code into lines, calculate the indentation of
the first non-white line, remove that indentation from all lines and then
rejoin.

Peter



More information about the Python-list mailing list