Chapter 25. Extending and Embedding Classic Python

The content of this chapter has been abbreviated for the print edition of this book. The full content is available online, as described in “Online Material”.

CPython runs on a portable, C-coded virtual machine. Python’s built-in objects—such as numbers, sequences, dictionaries, sets, and files—are coded in C, as are several modules in Python’s standard library. Modern platforms support dynamically loaded libraries, with file extensions such as .dll on Windows, .so on Linux, and .dylib on Mac: building Python produces such binary files. You can code your own extension modules for Python in C (or any language that can produce C-callable libraries), using the Python C API covered in this chapter. With this API, you can produce and deploy dynamic libraries that Python scripts and interactive sessions can later use with the import statement, covered in “The import Statement”.

Extending Python means building modules that Python code can import to access the features the modules supply. Embedding Python means executing Python code from an application coded in another language. For such execution to be useful, Python code must in turn be able to access some of your application’s functionality. In practice, therefore, embedding implies some extending, as well as a few embedding-specific operations. The three main reasons for wishing to extend Python can be summarized as follows:

  • Reimplementing some functionality (originally coded in ...

Get Python in a Nutshell, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.