MCPcopy Create free account
hub / github.com/numpy/numpy / build_and_import_extension

Function build_and_import_extension

numpy/testing/_private/extbuild.py:17–77  ·  view source on GitHub ↗

Build and imports a c-extension module `modname` from a list of function fragments `functions`. Parameters ---------- functions : list of fragments Each fragment is a sequence of func_name, calling convention, snippet. prologue : string Code to precede the

(
        modname, functions, *, prologue="", build_dir=None,
        include_dirs=[], more_init="")

Source from the content-addressed store, hash-verified

15
16
17def build_and_import_extension(
18 modname, functions, *, prologue="", build_dir=None,
19 include_dirs=[], more_init=""):
20 """
21 Build and imports a c-extension module `modname` from a list of function
22 fragments `functions`.
23
24
25 Parameters
26 ----------
27 functions : list of fragments
28 Each fragment is a sequence of func_name, calling convention, snippet.
29 prologue : string
30 Code to precede the rest, usually extra ``#include`` or ``#define``
31 macros.
32 build_dir : pathlib.Path
33 Where to build the module, usually a temporary directory
34 include_dirs : list
35 Extra directories to find include files when compiling
36 more_init : string
37 Code to appear in the module PyMODINIT_FUNC
38
39 Returns
40 -------
41 out: module
42 The module will have been loaded and is ready for use
43
44 Examples
45 --------
46 >>> functions = [("test_bytes", "METH_O", \"\"\"
47 if ( !PyBytesCheck(args)) {
48 Py_RETURN_FALSE;
49 }
50 Py_RETURN_TRUE;
51 \"\"\")]
52 >>> mod = build_and_import_extension("testme", functions)
53 >>> assert not mod.test_bytes(u'abc')
54 >>> assert mod.test_bytes(b'abc')
55 """
56 body = prologue + _make_methods(functions, modname)
57 init = """PyObject *mod = PyModule_Create(&moduledef);
58 """
59 if not build_dir:
60 build_dir = pathlib.Path('.')
61 if more_init:
62 init += """#define INITERROR return NULL
63 """
64 init += more_init
65 init += "\nreturn mod;"
66 source_string = _make_source(modname, init, body)
67 try:
68 mod_so = compile_extension_module(
69 modname, build_dir, include_dirs, source_string)
70 except Exception as e:
71 # shorten the exception chain
72 raise RuntimeError(f"could not compile in {build_dir}:") from e
73 import importlib.util
74 spec = importlib.util.spec_from_file_location(modname, mod_so)

Callers

nothing calls this directly

Calls 3

_make_methodsFunction · 0.85
_make_sourceFunction · 0.85
compile_extension_moduleFunction · 0.85

Tested by

no test coverage detected