An idiom for code generation with exec
eliben
eliben at gmail.com
Sat Jun 21 03:02:05 EDT 2008
On Jun 21, 8: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
>
I see. In my case I only evaluate function definitions with 'exec', so
I only need to de-indent the first line, and the others can be
indented because they're in a new scope anyway. What you suggest works
for arbitrary code and not only function definitions. It's a nice
trick with the "if 1:" :-)
More information about the Python-list
mailing list