Transliterating C code to Python

Peter Hansen peter at engcorp.com
Wed Jul 11 17:42:50 EDT 2001


- RZ wrote [regarding translating one-liners from C]:
> 
> Given a little context, the answers could vary considerably from the
> line-at-a-time approach. There's a difference between transliteration
> and translation. It might well be more educational to learn the best
> Pythonic way to accomplish a task than to learn how to write C in
> Python.

A case in point: one of my junior developers was "left unattended"
for a while, during which time he wrote an impressive quantity of
Python code which among other things did conversion of S19 files
(Motorola format for binary data usually to be programmed as firmware)
and placed the resulting information in a dual-port memory eight
bytes at a time for sending to another processor.

He complained of "poor performance with Python" so I took a look
at the code to see if maybe I could help.  In the end, after much
time spent grokking the code to figure out what it was really 
trying to do, I realized he was essentially writing C code in
Python.  His code was probably about 100 lines of Python code.
My "optimized" version rewrote the code in real Python -- in about
six lines as I recall.  Mostly he'd missed dictionaries, for 
loops that iterate over sequences and other useful Python 
idioms, and spent a lot of time manipulating 16-bit values as 
individual bytes with bitwise anding and oring and shifting... 

Very nice and efficient if it were coded in C.

-- 
----------------------
Peter Hansen, P.Eng.
peter at engcorp.com



More information about the Python-list mailing list