Modules/_decimal/_decimal.c
cpython 3.14 @ ab2d84fe1023/Modules/_decimal/_decimal.c
This is the largest single C file in CPython's Modules tree. It implements the
decimal module entirely in C by wrapping the mpdecimal library (libmpdec).
The pure-Python fallback is Lib/_pydecimal.py; this file shadows it whenever
the interpreter is built with mpdecimal support, which is the default.
Two Python types are defined: Decimal and Context. Every Decimal instance
carries an mpd_t value (mpdecimal's internal representation). Every arithmetic
operation is forwarded to the corresponding mpd_q* function, which records
IEEE 754 signals (Inexact, Overflow, DivisionByZero, etc.) into the context's
status word. The Python layer then checks that word and raises the appropriate
Python exception if a trap is set.
Map
Top-level types
| Python name | C object | Source region |
|---|---|---|
Decimal | PyDecType | ~line 360 |
Context | PyDecContextType | ~line 3800 |
Key structs
| Struct | Purpose |
|---|---|
PyDecObject | Holds mpd_t mpd inline (flexible array at end) |
PyDecContextObject | Holds mpd_context_t ctx and the per-context trap/signal dicts |
Arithmetic dispatch (representative sample)
| Python method | mpdecimal function |
|---|---|
__add__ | mpd_qadd |
__sub__ | mpd_qsub |
__mul__ | mpd_qmul |
__truediv__ | mpd_qdiv |
__mod__ | mpd_qrem |
__pow__ | mpd_qpow |
sqrt | mpd_qsqrt |
ln | mpd_qln |
exp | mpd_qexp |
Module-level functions
| Function | Purpose |
|---|---|
getcontext | Returns the current thread-local Context |
setcontext | Sets the current thread-local Context |
localcontext | Returns a context manager wrapping a copy of the current context |
DecimalTuple | Named-tuple constructor for (sign, digits, exponent) |