code blocks in Python

Hung Jung Lu hungjunglu at yahoo.com
Sat Nov 22 21:15:37 CET 2003


Hi,

I know people have talked about it before, but I am still really
confused from reading the old messages.

When I talk about code blocks, I am not talking about Lisp/Ruby/Perl,
so I am not making comparisons.

If you have a file, in Python you could do:

code = compile(code_string, 'FileName.py', 'exec')

and obtain a code object, which later on you can execute. That's the
kind of code block I have in mind. That is, no parameters, no
specification of scopes, no nothing else. Just a plain block of code
lines compiled into a code object.

It's not too much work to write a code string like:

my_codeblock = '''
x = x + 1
y = y + 2
'''

and then use compile() to turn it into a code object. But it seems to
me that Python could perfectly allow this syntax directly into the
language, something like:

codeblock my_codeblock:
    x = x + 1
    y = y + 2

so that users won't need to explicitly call the compile() function.
The advantage is that the codeblock is compiled at compile time, not
at run time, even if the codeblock is defined inside something else (a
class, a function, etc.)

Is there something obvious that I am missing here? Why isn't codeblock
part of the language? It seems to be an important building element for
meta-programming. Not only that, it seems to be much more fundamental
than functions. So, why isn't it part of Python? Any intrinsic
difficulties?

regards,

Hung Jung




More information about the Python-list mailing list