Seems that some are written in C and others are written in python? Correct. How does that work? The Python interpreter itself is written in C, so all entities within a Python program are ultimately represented internally by C-level data structures, anyway. You can therefore quite naturally write C-extensions for Python. How did they decide which is which. Performance reasons, primarily. What's implemented directly in C is going to be a lot faster, so anything for which that speed-up matters is going to be. And also, what if you want to extend a built in python class that is written in C? It works much the same as with any other class. While there's some differences between built-in and custom classes, they aren't fundamental. How is a class even created in C which is not an OOP language? You don't need an OOP language to implement an OOP language. In fact, all OOP languages must be implemented by a non-OOP language somewhere along the chain. All code is eventually translated to machine code, as that's the only language the CPU speaks. Machine code does not even really have a notion of variables or functions, much less higher-level concepts like classes. Those features do not make a language inherently more expressive than lower-level ones. It takes very little to create a language that can compute anything that can be computed. Everything else is just there to make the life of programmers easier. In the case of C, it does have structs, which are kind of proto-classes. However, Python classes are actually represented as instances of C structs. You need to remember that Python classes on the C level don't fulfill the function of classes, that's where they are given the function of classes. Edit: But I can't find others like for example the sys module, which I believe is written in C. Where can I find that? You can find the C source code on the CPython GitHub: https://github.com/python/cpython The sys module is here, specifically: https://github.com/python/cpython/blob/main/Python/sysmodule.c Answer from Spataner on reddit.com
🌐
Python
docs.python.org › 3 › extending › extending.html
1. Extending Python with C or C++ — Python 3.14.4 documentation
Let’s create an extension module called spam (the favorite food of Monty Python fans…) and let’s say we want to create a Python interface to the C library function system() [1]. This function takes a null-terminated character string as argument and returns an integer.
🌐
Reddit
reddit.com › r/learnpython › python standard library modules, some written in c some python?
r/learnpython on Reddit: Python standard library modules, some written in C some python?
September 22, 2021 -

Hi. I'm trying to understand the python standard library modules. Seems that some are written in C and others are written in python? How does that work? How did they decide which is which. And also, what if you want to extend a built in python class that is written in C? How is a class even created in C which is not an OOP language? I know that's a lot of questions, but thanks if you can help me understand.

Edit: Also, I can find certain modules like os by looking in the directory /usr/lib/python3.9 (I'm on linux). The os module is in that directory named os.py. But I can't find others like for example the sys module, which I believe is written in C. Where can I find that?

Top answer
1 of 2
7
Seems that some are written in C and others are written in python? Correct. How does that work? The Python interpreter itself is written in C, so all entities within a Python program are ultimately represented internally by C-level data structures, anyway. You can therefore quite naturally write C-extensions for Python. How did they decide which is which. Performance reasons, primarily. What's implemented directly in C is going to be a lot faster, so anything for which that speed-up matters is going to be. And also, what if you want to extend a built in python class that is written in C? It works much the same as with any other class. While there's some differences between built-in and custom classes, they aren't fundamental. How is a class even created in C which is not an OOP language? You don't need an OOP language to implement an OOP language. In fact, all OOP languages must be implemented by a non-OOP language somewhere along the chain. All code is eventually translated to machine code, as that's the only language the CPU speaks. Machine code does not even really have a notion of variables or functions, much less higher-level concepts like classes. Those features do not make a language inherently more expressive than lower-level ones. It takes very little to create a language that can compute anything that can be computed. Everything else is just there to make the life of programmers easier. In the case of C, it does have structs, which are kind of proto-classes. However, Python classes are actually represented as instances of C structs. You need to remember that Python classes on the C level don't fulfill the function of classes, that's where they are given the function of classes. Edit: But I can't find others like for example the sys module, which I believe is written in C. Where can I find that? You can find the C source code on the CPython GitHub: https://github.com/python/cpython The sys module is here, specifically: https://github.com/python/cpython/blob/main/Python/sysmodule.c
2 of 2
1
How is a class even created in C which is not an OOP language? How does a computer understand classes when all it can execute are hex instructions? A class is a concept that can be implemented in any language, some with more ease than others. With C you can mimic a class behavior by having a data structure that gets passed as first argument to all the functions that "belong" to the class.
Discussions

how do i use python libraries in C++? - Stack Overflow
I want to use the nltk libraries in c++. Is there a glue language/mechanism I can use to do this? Reason: I havent done any serious programming in c++ for a while and want to revise NLP concepts at the same time. ... Although calling c++ libs from python is more normal - you can call a python ... More on stackoverflow.com
🌐 stackoverflow.com
Wrapping a C library in Python: C, Cython or ctypes? - Stack Overflow
I want to call a C library from a Python application. I don't want to wrap the whole API, only the functions and datatypes that are relevant to my case. As I see it, I have three choices: Create an More on stackoverflow.com
🌐 stackoverflow.com
How can a Python package use C, like NumPy?
You can write and create a C program, that has interfaces that allows it to be used from python. It's written in C code, implements specific functions, exports them, and can use special c helper functions created by python developers to work with data that python understands. https://docs.python.org/3/extending/extending.html More on reddit.com
🌐 r/learnpython
4
6
February 9, 2023
How can I make a library in C++ for Python
I wrote a simple example a while back. More on reddit.com
🌐 r/learnpython
8
2
March 3, 2022
🌐
Real Python
realpython.com › build-python-c-extension-module
Building a Python C Extension Module – Real Python
June 27, 2023 - To write Python modules in C, you’ll need to use the Python API, which defines the various functions, macros, and variables that allow the Python interpreter to call your C code.
🌐
Python Tips
book.pythontips.com › en › latest › python_c_extension.html
22. Python C extensions — Python Tips 0.1 documentation
In this example the C file is self explanatory - it contains two functions, one to add two integers and another to add two floats. In the python file, first the ctypes module is imported. Then the CDLL function of the ctypes module is used to load the shared lib file we created.
🌐
Cython
cython.readthedocs.io › en › latest › src › tutorial › clibraries.html
Using C libraries — Cython 3.3.0a0 documentation
To make use of C data types in Python syntax, you need to import the special cython module in the Python module that you want to compile, e.g. ... If you use the pure Python syntax we strongly recommend you use a recent Cython 3 release, since significant improvements have been made here compared ...
🌐
Medium
medium.com › delta-force › extending-python-with-c-f4e9656fbf5d
Extending Python with C
January 7, 2020 - So some of the things we need to do in this step is, convert between C datatypes, functions etc to things that Python can use; in our case, convert everything to PyObjects. The above C code can be a little daunting if you are unfamiliar with a strongly typed language such as C++ or Java but it’s quite simple really. As mentioned before, everything is a PyObject. At line 5, we define a static function which returns a pointer to a PyObject. This is the function that CPython will call when we import our library and call the kthprime function.
Find elsewhere
🌐
Readthedocs
reptate.readthedocs.io › developers › python_c_interface.html
Tutorial: Interfacing Python and C code — RepTate 1.3.15 documentation
We use the basic_function.so library via Ctypes. In a new file, write the following and save it as, for example, basic_function_helper.py · 1""" 2Define the C-variables and functions from the C-files that are needed in Python 3""" 4from ctypes import c_double, c_int, CDLL 5import sys 6 7lib_path = 'theories/basic_function_%s.so' % (sys.platform) 8try: 9 basic_function_lib = CDLL(lib_path) 10except: 11 print('OS %s not recognized' % (sys.platform)) 12 13python_c_square = basic_function_lib.c_square 14python_c_square.restype = None
🌐
Python
docs.python.org › 3 › extending › building.html
4. Building C and C++ Extensions — Python 3.14.4 documentation
A C extension for CPython is a shared library (for example, a .so file on Linux, .pyd on Windows), which exports an initialization function.
Top answer
1 of 12
183

Warning: a Cython core developer's opinion ahead.

I almost always recommend Cython over ctypes. The reason is that it has a much smoother upgrade path. If you use ctypes, many things will be simple at first, and it's certainly cool to write your FFI code in plain Python, without compilation, build dependencies and all that. However, at some point, you will almost certainly find that you have to call into your C library a lot, either in a loop or in a longer series of interdependent calls, and you would like to speed that up. That's the point where you'll notice that you can't do that with ctypes. Or, when you need callback functions and you find that your Python callback code becomes a bottleneck, you'd like to speed it up and/or move it down into C as well. Again, you cannot do that with ctypes. So you have to switch languages at that point and start rewriting parts of your code, potentially reverse engineering your Python/ctypes code into plain C, thus spoiling the whole benefit of writing your code in plain Python in the first place.

With Cython, OTOH, you're completely free to make the wrapping and calling code as thin or thick as you want. You can start with simple calls into your C code from regular Python code, and Cython will translate them into native C calls, without any additional calling overhead, and with an extremely low conversion overhead for Python parameters. When you notice that you need even more performance at some point where you are making too many expensive calls into your C library, you can start annotating your surrounding Python code with static types and let Cython optimise it straight down into C for you. Or, you can start rewriting parts of your C code in Cython in order to avoid calls and to specialise and tighten your loops algorithmically. And if you need a fast callback, just write a function with the appropriate signature and pass it into the C callback registry directly. Again, no overhead, and it gives you plain C calling performance. And in the much less likely case that you really cannot get your code fast enough in Cython, you can still consider rewriting the truly critical parts of it in C (or C++ or Fortran) and call it from your Cython code naturally and natively. But then, this really becomes the last resort instead of the only option.

So, ctypes is nice to do simple things and to quickly get something running. However, as soon as things start to grow, you'll most likely come to the point where you notice that you'd better used Cython right from the start.

2 of 12
131

ctypes is your best bet for getting it done quickly, and it's a pleasure to work with as you're still writing Python!

I recently wrapped an FTDI driver for communicating with a USB chip using ctypes and it was great. I had it all done and working in less than one work day. (I only implemented the functions we needed, about 15 functions).

We were previously using a third-party module, PyUSB, for the same purpose. PyUSB is an actual C/Python extension module. But PyUSB wasn't releasing the GIL when doing blocking reads/writes, which was causing problems for us. So I wrote our own module using ctypes, which does release the GIL when calling the native functions.

One thing to note is that ctypes won't know about #define constants and stuff in the library you're using, only the functions, so you'll have to redefine those constants in your own code.

Here's an example of how the code ended up looking (lots snipped out, just trying to show you the gist of it):

from ctypes import *

d2xx = WinDLL('ftd2xx')

OK = 0
INVALID_HANDLE = 1
DEVICE_NOT_FOUND = 2
DEVICE_NOT_OPENED = 3

...

def openEx(serial):
    serial = create_string_buffer(serial)
    handle = c_int()
    if d2xx.FT_OpenEx(serial, OPEN_BY_SERIAL_NUMBER, byref(handle)) == OK:
        return Handle(handle.value)
    raise D2XXException

class Handle(object):
    def __init__(self, handle):
        self.handle = handle
    ...
    def read(self, bytes):
        buffer = create_string_buffer(bytes)
        count = c_int()
        if d2xx.FT_Read(self.handle, buffer, bytes, byref(count)) == OK:
            return buffer.raw[:count.value]
        raise D2XXException
    def write(self, data):
        buffer = create_string_buffer(data)
        count = c_int()
        bytes = len(data)
        if d2xx.FT_Write(self.handle, buffer, bytes, byref(count)) == OK:
            return count.value
        raise D2XXException

Someone did some benchmarks on the various options.

I might be more hesitant if I had to wrap a C++ library with lots of classes/templates/etc. But ctypes works well with structs and can even callback into Python.

🌐
Python
docs.python.org › 3 › library › index.html
The Python Standard Library — Python 3.14.4 documentation
The library contains built-in modules (written in C) that provide access to system functionality such as file I/O that would otherwise be inaccessible to Python programmers, as well as modules written in Python that provide standardized solutions for many problems that occur in everyday programming.
🌐
Python modules in C
dfm.io › posts › python-c-extensions
Python modules in C | Dan Foreman-Mackey
August 3, 2012 - Any communication between the Python interpreter and your C code will be done by passing PyObjects so any function that you want to be able to call from Python must return one. Under the hood, PyObject is just a struct with a reference count and a pointer to the data contained within the object.
🌐
Stav Shamir
stavshamir.github.io › python › making-your-c-library-callable-from-python-by-wrapping-it-with-cython
Making your C library callable from Python by wrapping it with Cython - Stav Shamir
May 3, 2018 - If you want, it is interesting to take a peek at the generated C file! Again, writing a makefile is recommended. We can use the makefile we made earlier to build everything with one simple command: LIB_DIR = lib default: pyexamples pyexamples: setup.py pyexamples.pyx $(LIB_DIR)/libexamples.a python3 setup.py build_ext --inplace && rm -f pyexamples.c && rm -Rf build $(LIB_DIR)/libexamples.a: make -C $(LIB_DIR) libexamples.a clean: rm *.so
🌐
NAPALM
saidvandeklundert.net › learn › 2022-06-02-extending-python-with-c
Extending Python with C
June 2, 2022 - A good deal of Python, or at least CPython, is written in C. The language and the interpreter are implemented in C and in addition to this, you can also find a lot of modules in the Python standard library powered by C.
🌐
Quora
quora.com › What-is-the-best-way-to-use-a-Python-library-in-C
What is the best way to use a Python library in C++? - Quora
Answer: In order to use a Python library in C++, I have created a child process running Python and used inter-process communication to pass requests down to the child process and results back to the parent. In other situations where the requirement seemed to be using a Python library from C++, I...
🌐
Opensource.com
opensource.com › article › 22 › 11 › extend-c-python
Write a C++ extension module for Python | Opensource.com
November 24, 2022 - On most systems, the CPython interpreter is the default, and also the poll in my last article showed that CPython is the most popular one. Specific to CPython is the ability to write Python modules in C using CPythons extensions API.
🌐
Real Python
realpython.com › python-bindings-overview
Python Bindings: Calling C or C++ From Python – Real Python
August 17, 2023 - A C++ library installed and knowledge of the path for command-line invocation ... For Linux, this is the python3-dev or python3-devel package, depending on your distro.
🌐
ActiveState
activestate.com › home › blog › how to build and install c libraries in python
How to Build and Install C Libraries in Python
March 10, 2025 - While installing pre-built wheels is a convenient shortcut, they raise two concerns: Availability – Unfortunately, not all packages are pre-compiled for all platforms. If your platform is unsupported, you’ll need to build the C libraries yourself. Security – PyPI does not provide guarantees as to the security of the packages they offer. With pure Python packages, you at least have the option to read the code and see what they’re doing, but precompiled binaries require other methods to determine whether they contain malware.