Import dynamic library by path

I sometimes import *.py files by path:

def _import_by_path(path, name=None):
    spec = importlib.util.spec_from_file_location(name, path)
    mod = importlib.util.module_from_spec(spec)
    sys.modules[spec.name] = mod
    spec.loader.exec_module(mod)
    return mod

Is there a way to import *.so file by path?

My understanding was that the code should work for everything that has a proper loader installed; what error does the code raise for .so files?

ImportError: dynamic module does not define module export function (PyInit_cpython_312_darwin)

I am trying to do this on “cythonized” module, which loads perfectly well in a standard manner.

AFAIK this function is looked up only by the module name and it doesn’t look like you are providing one/the correct one. It shouldn’t include a version or platform.

So I have files:

/some_dir/some_script.py
/some_dir/some_script.cpython-312-darwin.so

What would be the correct way to load .so file by path?

got it working. Thanks