An idiom for code generation with exec

Raymond Hettinger python at
Fri Jun 20 15:36:48 CEST 2008

On Jun 20, 5:03 am, eliben <eli... at> wrote:
> I've rewritten it using a dynamically generated procedure
> for each field, that does hard coded access to its data. For example:
> def get_counter(packet):
>   data = packet[2:6]
>   data.reverse()
>   return data
> This gave me a huge speedup, because each field now had its specific
> function sitting in a dict that quickly extracted the field's data
> from a given packet.
> Now I'm rewriting this program in Python and am wondering about the
> idiomatic way to use exec (in Perl, eval() replaces both eval and exec
> of Python).

FWIW, when I had a similar challenge for dynamic coding, I just
generated a py file and then imported it.  This technique was nice
because can also work with Pyrex or Psyco.

Also, the code above can be simplified to:  get_counter = lambda
packet: packet[5:1:-1]

Since function calls are expensive in python, you can also gain speed
by parsing multiple fields at a time:

   header, timetag, counter = parse(packet)


More information about the Python-list mailing list