code blocks in Python

Florian Reiser florian.reiser at
Tue Nov 25 15:39:24 CET 2003

Hi folks,

I have read your thread about code blocks.
When reading it, a problem that I have came to my mind.
I have a module ZReportLab. This module defines a class for Zope
( for using the reportlab library.
The actual code I want the object to execute is stored in three string
variables, compiled at change time with compile()
and executed, when the object is called. So I can use a different content
code for each object I have created in the object database
of Zope.
But no one programs without errors, so every time I've made an error, I get
a traceback holding the information that there's an error,
inside my code object.
It would be nice if I could debug it with pdb. But at the moment I have to
guess where the error is, or step towards it, through inserting
a raise and trying if it runs to the position of the raise. This is really
hard work.
How can I compile my code object, so that I can debug it when I do the exec

Florian Reiser

"Hung Jung Lu" <hungjunglu at> schrieb im Newsbeitrag
news:8ef9bea6.0311221215.804bdb3 at
> 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, '', '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