views:

148

answers:

4

If Python was so fast as C, the latter would be present in python apps/libraries?

Example: if Python was fast as C would PIL be written completely in Python?

+7  A: 

To access "legacy" C libraries and OS facilities.

Ignacio Vazquez-Abrams
+2  A: 

It makes sense to use C modules in Python for:

  • Performance
  • Libraries that won't be ported to Python (because of performance reasons, for example) or that use OS-specific functions
  • Scripting. For example, many games use Python, Lua and other languages as scripting languages. Therefore they expose C/C++ functions to Python.

As to your example: Yes, but Python is inherently slower than C. If both were equally fast, it would make sense to use Python because C code is often more prone to attacks (buffer overflows and stuff).

AndiDog
The first two make sense. The third seems backwards somehow. The third seems to be why a C app would use Python, not why a Python app would use some C module.
S.Lott
+5  A: 

While you can of course use ctypes to access existing C code, you might not necessarily want to, in sufficiently complex cases: when you're coding to an interface designed for (and implemented in) C, not doing compilation can mean that small errors on the caller's side, that would simply refuse to compile properly in C, can result in crashes of the whole application.

So, using C code (rather than ctypes) for the purpose of reusing good existing C code can make a lot of sense (Cython is fine too, of course, since it does generate C code that, in case of caller-side errors, should fail to compile;-).

Recoding everything from scratch, rather than reusing good, existing, solid and finely tuned code, doesn't make much sense either way, of course -- there are so many interesting new problems to conquer, that spending your time just mimicking an existing, just-fine solution to an old and already-conquered problem is likely not going to be the best, most productive, and most satisfactory way to spend your time;-).

Alex Martelli
A: 

To access hardware.

Juanjo Conti
Do you mean to bypass the OS entirely? Or do you mean to use the more obscure OS API methods? What do you mean?
S.Lott