An idiom for code generation with exec

Fuzzyman fuzzyman at gmail.com
Mon Jun 23 15:39:23 EDT 2008


On Jun 21, 7:52 am, Peter Otten <__pete... at web.de> wrote:
> 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.
>


textwrap.dedent will do all that for you...

Michael Foord
http://www.ironpythoninaction.com/

> Peter




More information about the Python-list mailing list