Reading compiled sources¶
A built extension tells inspect little: often no parameter names, no types, no return type.
When its sources sit beside it, stubpy reads them, without compiling anything, and fills in
what the runtime lacks. This page lists what is read from each kind of source; Compiled modules
covers how compiled modules are stubbed overall.
Cython sources¶
.pyx files are module files: a folder run or an explicit .pyx target stubs them.
A built extension that imports wins and is introspected. The
.pyxfills in what the build lacks: parameter types, defaults (enum members such asTable.DC), docstrings and the types ofcdef public/readonlyfields.An unbuilt
.pyxis stubbed from the source alone (INFOStubbed from the Cython source; no build of it was imported).An extension that cannot be imported falls back to its same-stem
.pyxwith a WARNING.The source is read with Cython’s own parser (
Cython.Compiler) when Cython is installed, otherwise with a built-in reader ofdefandcpdefsignatures (multi-line signatures, decorators,nogil,exceptandnoexceptclauses).cdeffunctions are not visible from Python and are skipped.cpdef enumbecomes anIntEnum. C types map as forembedsignature:doubletofloat,binttobool, typed memoryviews toBuffer.A
def,cpdefor property getter without a declared return type gets one when everyreturnis plain: literals, typed parameters andcdeflocals, the class’scdeffields (self.width),.shape[i], builtin conversions (int(...),len(...)), classes of the module and NumPy factories (np.zeros(..., dtype=np.uint8)givesnumpy.typing.NDArray[numpy.uint8]). A body without a returned value givesNone; generators and anything else stay untyped.
# shapes.pyx
cpdef enum Table:
DC = 0
AC = 1
cdef double _helper(double x):
return x
def scale(double x, int n=2, bint flip=False, *, Table table=Table.DC):
return x * n
cpdef double area(double w, double h=1.0) nogil:
return w * h
cdef class Box:
cdef public double width
cdef readonly int count
stubpy render shapes.pyx:
from enum import IntEnum
from typing import Any
class Table(IntEnum):
DC = 0
AC = 1
DC: Table
AC: Table
class Box:
@property
def width(self) -> float: ...
@width.setter
def width(self, value: Any) -> None: ...
@property
def count(self) -> int: ...
def scale(
x: float,
n: int = 2,
flip: bool = False,
*,
table: Table = Table.DC,
): ...
def area(w: float, h: float = 1.0) -> float: ...
C API sources¶
A C API function registered with METH_VARARGS and no signature docstring has nothing
for inspect to read. When the C sources sit next to the built module, stubpy reads them
(no compiler, no C parser) and fills what the runtime lacks; a text signature, a docstring
line, a .pyx or a sibling .pyi still wins on what it states.
Sources:
_x.c(or.cc/.cpp/.cxx) beside_x.cp312-win_amd64.pyd, in asrc/folder beside it, in asrc/folder beside its package, or in another folder beside it (_ext/); otherwise the file definingPyInit__xthere, with the other C files of that folder. Cython output is ignored. Definitions with the return type on its own line are read.Without the built module (it fails to import, or
--imports none), the stub comes from the sources alone, with a WARNING: the functions with their method-table docstrings and the types below, the classes, constants added withPyModule_AddIntConstant/AddStringConstant/AddObject(typed from the object’s constructor, such asPyDict_New), and exceptions fromPyErr_NewExceptionwith their base class.PyMethodDeftables give the functions; tables named by a type’stp_methods(or aPyType_SlotPy_tp_methods) give its methods, andtp_initits constructor.METH_NOARGSgives no parameters.METH_Ogives one positional-only parameter named after the C argument, typed by its first conversion:PyLong_As*→int,PyFloat_AsDouble→float,PyUnicode_AsUTF8→str,PyObject_GetBuffer→Buffer,PyCapsule_GetPointer→CapsuleType.METH_VARARGSreads thePyArg_ParseTuple/PyArg_ParseTupleAndKeywordscall: names fromkwlist(or the C variables, positional only),|optional (default...),$keyword-only, and types from the units:i/l/n→int,d/f→float,s/U→str,z→str | None,y→bytes,p→bool,(ii)→tuple[int, int],O!with&PyList_Typeor a type of the module → that type,O→Any.PyArg_UnpackTuplegives positional-onlyAnyparameters.Argument Clinic
/*[clinic input]blocks give full signatures: converters as types,/and*, Python defaults, and-> doublestyle return converters.A docstring signature whose names differ from the C ones keeps its names and takes these types by position.
Returns:
Py_RETURN_NONE→None,PyLong_From*→int,PyFloat_FromDouble→float,PyBool_FromLong→bool,PyUnicode_From*→str,PyCapsule_New→CapsuleType,Py_BuildValue("(dd)")→tuple[float, float], andreturn helper(...)the helper’s own return type; when every non-errorreturnagrees (Noneplus one type givesT | None). Anything else stays untyped.PyGetSetDefgetters take the getter’s return type;PyMemberDefT_INT/T_DOUBLE/T_BOOL/T_STRING/T_OBJECTgiveint/float/bool/str/Any.Comments and preprocessor lines are dropped (both
#ifbranches are read); rows, calls and format strings that do not have the expected shape are skipped, as areMETH_FASTCALLfunctions without a clinic block and optional groups ([]).
static PyObject *clamp(PyObject *self, PyObject *args, PyObject *kwds) {
static char *kwlist[] = {"value", "low", "high", "strict", NULL};
...
if (!PyArg_ParseTupleAndKeywords(args, kwds, "d|dd$p:clamp", kwlist, ...)) return NULL;
return PyFloat_FromDouble(...);
}
def clamp(
value: float,
low: float = ...,
high: float = ...,
*,
strict: bool = ...,
) -> float: ...
When the package’s __init__ fails to import, the extension modules in it are still
loaded on their own, under placeholder parent packages, with a WARNING
(...; loaded pkg.sub._ext on its own instead).