Programming in Python with a view to extending in C at a later date.

Carl Banks pavlovevidence at gmail.com
Tue Apr 21 04:07:12 EDT 2009


On Apr 20, 11:57 am, "dug.armad... at googlemail.com"
<dug.armad... at googlemail.com> wrote:
> Say you set out to program in Python knowing that you will be
> converting parts of it into C ( or maybe C++) at a later date, but you
> do not know which parts.
>
> Can you give any general Python structure / syntax advice that if
> implemented from the start, will make this future task less painful.
> In addition, advice that will make this easier for automatic tools
> will be good too.

I'd just avoid things that don't have a straightforward translation to
C (such as clever metaprogramming, overdependence on keyword
arguments, nested scopes and closures, and yes, generators).  Most
things in Python do correspond pretty well to things in C.

However, don't avoid objects that might be difficult to implement in C
(such as dicts and sets); fact is, code that uses these objects a lot
probably won't benefit much from translation to C.  OTOH, if you need
dict-like behavior in an otherwise static computation, it's probably
because there's no other easy way to do the computation, so you'll
have to tackle the problem in C anyway.

Also, don't avoid regular exception handling.  When you rewrite
something in C you'll find that it is farily obvious how to write the
C code so that it returns errors in a similar way.

If you do a lot of OO stuff I strongly recommend that you study up on
the right way to implement new-style types from C, such that they can
serve as a base for Python classes.  That way, if you have a class and
you want to implement a few methods in C while leaving the rest in
Python, you can factor out all the C methods into a base class written
in C.


Carl Banks



More information about the Python-list mailing list