Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Shared Libraries

As I understand there are two types of modules in python (CPython): - the .so (C extension) - the .py

The .so are only loaded once even when there are different processes/interpreters importing them.

The .py are loaded once for each process/interpreter (unless reloading explicitly).

Is there a way .py can be shared by multiple processes/interpreters?

One would still need some layer where one could store modifications done to the module. I'm thinking one could embed the interpreter in a .so as the first step. Is there an already developed solution.

I acknowledge i may be very far off in terms of feasible ideas about this. Please excuse my ignorance.

like image 939
primroot Avatar asked Apr 22 '26 23:04

primroot


1 Answers

The reason .so (or .pyd) files take up memory space only once (except for their variables segment) is that they are recognized by the OS kernel as object code. .py files are only recognized as text files/data; it's the Python interpreter that grants them "code" status. Embedding the Python interpreter in a shared library won't resolve this.

Loading .py files only once despite their use in multiple processes would require changes deep inside CPython.

Your best option, if you want to save memory space, is to compile Python modules to .so files using Cython. That may require some changes to the modules.

like image 74
Fred Foo Avatar answered Apr 25 '26 11:04

Fred Foo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!