The need to use extensions

It's not easy to say when it is a reasonable decision to write extensions in C/C++. The general rule of thumb could be, never, unless you have no other choice. But this is a very subjective statement that leaves a lot of place for the interpretation of what is not doable in Python. In fact, it is hard to find a thing that cannot be done using pure Python code. Still, there are some problems where extensions may be especially useful by adding the following benefits:

Of course, for every such problem, there is usually a viable native Python solution. For example, the core CPython interpreter constraints, such as GIL, can easily be overcome with a different approach to concurrencies, such as green threads or multiprocessing instead of a threading model. Third-party libraries can be integrated with theĀ ctypes module. Every datatype can be implemented in Python. Still, the native Python approach may not always be optimal. Python-only integration of an external library may be clumsy and hard to maintain. Implementation of custom datatypes may be suboptimal without access to low-level memory management. So the final decision of what path to take must always be taken very carefully and take many factors into consideration and so on. A good approach is to start with a pure Python implementation first and consider extensions only when the native approach proves to be not good enough.

The next section will help us to improve the performance in critical code sections.