Python Medium technical 1 views 1 min read

Explain how can you access a module written in Python from C?

Peer-reviewed by HireXTech Technical Panel Updated for 2025/2026 hiring Editorial standards
Practise this track
Interviewer Expectations for this Question
01
Core Competency

Assesses fundamental understanding of Python conventions, runtime behavior, and memory/performance considerations.

02
Evaluation Criteria

Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.

Comprehensive Model Answer Verified Solution

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

  1. Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
  2. Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
  3. Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
  4. Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.
Related Topics & Skills
Spotted an error or have an alternative solution?