Explain how can you access a module written in Python from C?
Assesses fundamental understanding of Python conventions, runtime behavior, and memory/performance considerations.
Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.
Python can be embedded inside C/C++ applications using the official Python C API (Python.h).
### Standard Steps to Import and Invoke Python from C:
#include <Python.h>
int main(int argc, char *argv[]) {
// 1. Initialize Python runtime interpreter
Py_Initialize();
// 2. Add current directory to sys.path so the module can be located
PyRun_SimpleString("import sys; sys.path.append('.')");
// 3. Import the Python module (e.g. 'my_math')
PyObject *pName = PyUnicode_DecodeFSDefault("my_math");
PyObject *pModule = PyImport_Import(pName);
Py_DECREF(pName);
if (pModule != NULL) {
// 4. Retrieve a specific function from the module
PyObject *pFunc = PyObject_GetAttrString(pModule, "calculate_tax");
if (pFunc && PyCallable_Check(pFunc)) {
// 5. Call the function with arguments
PyObject *pArgs = PyTuple_Pack(1, PyFloat_FromDouble(50000.0));
PyObject *pValue = PyObject_CallObject(pFunc, pArgs);
Py_DECREF(pArgs);
if (pValue != NULL) {
printf("Result: %f\n", PyFloat_AsDouble(pValue));
Py_DECREF(pValue);
}
}
Py_XDECREF(pFunc);
Py_DECREF(pModule);
}
// 6. Clean up interpreter memory
Py_Finalize();
return 0;
}
Candidate Response Strategy & Interview Tips
- Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
- Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
- Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
- Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.