code blocks in Python

John Roth newsgroups at jhrothjr.com
Sat Nov 22 16:02:33 EST 2003


"Hung Jung Lu" <hungjunglu at yahoo.com> wrote in message
news:8ef9bea6.0311221215.804bdb3 at posting.google.com...
> 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?

Just some random observations. First, I'm not at all clear on
what you want it to do. Some examples would be helpful. There
are entirely too many different ways I could interpret your reference
to metaprogramming for me to understand the usage you have in
mind.

If you want it as a replacement for the badly crippled lambda statement,
then I think there's quite a bit of interest. What's holding that up is
syntax, and an appropriate syntax isn't entirely obvious.

If you want it to do something else, like act like it was actually
compiled where it will be invoked, with identifier resolution
and all, then that's a completely different subject.

John Roth


>
> regards,
>
> Hung Jung






More information about the Python-list mailing list