Recursion in compile()

  • Thread starter Narendra C. Tulpule
  • Start date
N

Narendra C. Tulpule

Hi,
is there any way to allow recusrion in compile()? Something like:

src_code = 'def fact(n):\n\tif n <= 1:\n\t\treturn 1\n\telse:' + \
'\n\t\treturn n * fact(n-1)\n\nprint fact(12)\n'
cobj = compile(src_code, 'myfile', 'exec')
eval(cobj)

I did a search on 'recursion' in comp.lang.python but didn't turn up
anything relevant. Maybe I've highhhhhh expectations :)
-- Naren.
 
S

Steven Taschuk

Quoth Narendra C. Tulpule:
is there any way to allow recusrion in compile()? Something like:

src_code = 'def fact(n):\n\tif n <= 1:\n\t\treturn 1\n\telse:' + \
'\n\t\treturn n * fact(n-1)\n\nprint fact(12)\n'
cobj = compile(src_code, 'myfile', 'exec')
eval(cobj)

This works fine for me -- it prints 479001600 as expected, on both
2.2.2 and 2.3b1. What is the problem you're seeing?
 
B

Bengt Richter

Quoth Narendra C. Tulpule:

This works fine for me -- it prints 479001600 as expected, on both
2.2.2 and 2.3b1. What is the problem you're seeing?

It works for me too. But the OP is saying "recursion *in* compile()" [my emphasis and spelling],
and the recursion of fact doesn't involve recursion of compiler calls (at least not in the
fact code). Maybe he is after something else?

BTW, (to the OP), using triple quotes makes things more readable sometimes:
... def fact(n):
... if n <= 1:
... return 1
... else:
... return n * fact(n-1)
...
... print fact(12)
... """ 479001600

(For yet another readability improvement, leaving out the backslash would make
a blank line that's not in the OP's string, but wouldn't hurt the compilation).

Regards,
Bengt Richter
 
N

Narendra C. Tulpule

Steven Taschuk said:
Quoth Narendra C. Tulpule:

This works fine for me -- it prints 479001600 as expected, on both
2.2.2 and 2.3b1. What is the problem you're seeing?

Sorry, you're right, it does work for me.
I was trying something like
cobj = compile('eval(src_code)', ...)
eval(cobj)
And that complains about syntax error (because I am trying to define a
function within eval string?)
 
S

Steven Taschuk

Quoth Narendra C. Tulpule:
[...]
I was trying something like
cobj = compile('eval(src_code)', ...)
eval(cobj)
And that complains about syntax error (because I am trying to define a
function within eval string?)

That would do it -- with a string argument, eval only does
expressions, not statements (and so in particular, not def
statements).

Try
compile('exec src_code')
instead.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,079
Messages
2,570,574
Members
47,206
Latest member
Zenden

Latest Threads

Top