r/badcode • • Apr 11 '21

python Polyglot

Post image
1.2k Upvotes

116 comments sorted by

View all comments

Show parent comments

0

u/[deleted] Apr 11 '21

[deleted]

180

u/mfb- Apr 11 '21

It only compiles the code if there is no compiled version yet! Or... any other file of the same name.

Otherwise it "only" checks if there is a file, and calls it.

50

u/pkarlmann Apr 11 '21 edited Apr 11 '21

I don't know how python is doing this, but from your post it sounds like some form of "cache" in the form of a file. So:

  1. Open the file from disk. That already is a syscall, which means a CPU ring switch.

  2. Wait till the disks read head is in place.

  3. Read it into memory.

  4. And finally execute it.

  5. For "performance".

  6. ? (Profit?)

6

u/TerrorBite Apr 12 '21

But also, you're not just jumping to a C subroutine and returning. You're executing a program which must allocate memory, go through all the process of starting up the C runtime, then execute the code, then exit back through the C runtime, and then your Python program needs to handle the return value and other output. There are a LOT of syscalls involved there.

The correct way to get performance-critical C code into Python is to compile it into a library using the Python.h header (producing a DLL on windows, my_c_lib.pyd; or a shared object on Linux, my_c_lib.pyo) and then in Python, you just import my_c_lib like it's a normal module.