When a Python pricing call enters a compiled library, the Python debugger can show where the call started, but it cannot step through the C++ calculation. This walkthrough follows one QuantLib option from Python, across its SWIG binding, into AnalyticEuropeanEngine::calculate(), and back again by using two VS Code debug sessions attached to the same process.
The workflow is designed to make that handoff repeatable: pause before each pricing call, let GDB stop in the native engine, then resume C++ so Python can continue. You will see the engine run twice, with a spot update between calls.
flowchart LR
PY["Python script"] -->|"option.NPV()"| SWIG["SWIG binding"]
SWIG --> QL["QuantLib C++ engine"]
QL -->|"NPV result"| SWIG
SWIG --> PY
First prepare the debug-enabled QuantLib environment and VS Code launch configurations. Then run the example in order. Focused checkpoints show what to expect at each debugger handoff, and troubleshooting is collected at the end.
1. Prerequisites: prepare VS Code and QuantLib
For this example, the essential project structure is shown below. The operative system used for this post is any Linux distribution under Debian family such as Ubuntu, Kali or any other.
QuantLib_Debug/
├── .vscode/
│ └── launch.json
└── test_debug.py
This walkthrough uses two VS Code debugging sessions attached to the same Python process: one follows the Python code, and the other follows execution into QuantLib’s native C++ code. Install the Python, Python Debugger, and Microsoft C/C++ extensions to work with both sides. The Python Debugger extension provides the debugpy session, while the C/C++ extension connects VS Code to GDB for native debugging.
If installing extensions is new to you, watch Using extensions in Visual Studio Code, the video featured in the official VS Code introductory tutorial. It demonstrates how to find extensions, install them from the Extensions view, and disable them when they are not needed. On Linux, open that view with Ctrl+Shift+X, search for each extension, check its publisher, and select Install.
This walkthrough targets Linux with GDB. It assumes that you have already built QuantLib and its SWIG Python extension with debug information, installed the resulting wheel in a virtual environment, and retained the source files that match those builds. The QuantLib Debug build and SWIG setup explains that preparation. If you want to establish the native side first, the C++ European FX option example provides a separate test.
The objective here is different: start with a Python pricing call, stop inside QuantLib’s C++ engine, and return to Python in a predictable order.
Select the interpreter and check the paths
To choose the Python environment in VS Code:
- Open the project folder that contains
test_debug.py. - Open the Command Palette with Ctrl+Shift+P.
- Type Python: Select Interpreter and select that command.
- Choose the virtual environment that contains your debug-enabled QuantLib package. If it is not listed, select Enter interpreter path… and browse to the environment’s Python executable.
The interpreter list appears as shown below:
The example uses these paths that you can check manually just by running the command ls <path-to-check> (they should not be empty):
| Component | Example path | What to verify |
|---|---|---|
| Python interpreter | /<path-to-your-venv-folder>/test_debug_quantlib/bin/python |
This environment contains the intended QuantLib wheel. |
| GDB | /usr/bin/gdb |
GDB is installed and available to the C/C++ extension. |
| QuantLib debug libraries | $HOME/quantlib-debug-install/lib |
This directory contains the debug build of libQuantLib.so. |
| QuantLib source tree | $HOME/GIT/QuantLib |
These sources match the compiled debug library. |
Replace the user-specific paths with your own throughout the configuration below. Selecting an interpreter in the editor does not override an explicit python path in a launch configuration, so keep the two aligned.
2. Configure the two debugger sessions
We need two views of the calculation, not two copies of the script. One session follows the Python statements that construct and reprice the option. The other inspects the compiled C++ code that performs the calculation. Both target the same Python process. An introduction to debugging in VS Code may be found in this Youtube link.
debugpy provides the Python debugging implementation. The Python Debugger extension uses it to manage Python breakpoints, display Python variables and stack frames, and step through test_debug.py. In this experiment, it lets us pause before each NPV() call and control when the spot quote changes. It does not provide source-level stepping through QuantLib’s compiled C++ implementation. See the official Python debugging guide and the debugpy documentation for configuration and implementation details.
cppdbg selects the Microsoft C/C++ extension’s native-debugging integration. It is a configuration type, not the underlying debugger’s name. With "MIMode": "gdb", this integration uses GDB to attach to the Python process and inspect native execution in the SWIG extension and QuantLib library. Debug symbols and matching source files let GDB relate compiled instructions to C++ statements and variables. Its role here is to stop inside AnalyticEuropeanEngine::calculate(), where the option’s value is calculated. The C/C++ configuration reference describes the VS Code settings, and the GDB manual explains the native debugger.
The diagram separates the debugging connections from the pricing call path. The sessions do not hand control directly to one another. We switch to the appropriate session when its breakpoint is reached.
flowchart TB
UI["VS Code<br/>Run and Debug / CALL STACK"]
PYDBG["Python session<br/>debugpy"]
CPPDBG["C/C++ session<br/>cppdbg integration"]
GDB["GDB<br/>Native debugger"]
UI -. "Python debug commands" .-> PYDBG
UI -. "Native debug commands" .-> CPPDBG
CPPDBG -. "GDB/MI" .-> GDB
subgraph PROCESS["One Python process - the same PID"]
PY["test_debug.py<br/>Build option, call NPV, update spot"]
SWIG["Compiled SWIG extension<br/>Python-to-C++ boundary"]
QL["QuantLib C++ library<br/>AnalyticEuropeanEngine::calculate()"]
PY -->|"option.NPV()"| SWIG
SWIG -->|"Native pricing calls"| QL
QL -->|"Calculated result"| SWIG
SWIG -->|"Return value"| PY
end
PYDBG -. "Python breakpoints and stepping" .-> PY
GDB -. "Native breakpoints and inspection" .-> SWIG
GDB -. "Native breakpoints and stepping" .-> QL
Solid arrows show application calls and returns. Dashed arrows show debugging connections. This is a conceptual view, not a complete map of debugger processes or QuantLib’s internal calls.
When Python pauses before option.NPV(), its debugger controls the next Python step. If GDB then stops inside the pricing engine, that Python step remains unfinished until the native call returns. Continuing the C++ session allows the calculation to finish so Python can reach its next stop.
Following the Youtube video mentioned before, let’s create an appropriate .vscode/launch.json with the following two configurations so that enables us to use both debuggers:
{
"version": "0.2.0",
"configurations": [
{
"name": "1. Python (debugpy)",
"type": "debugpy",
"request": "launch",
"python": "/<path-to-your-venv-folder>/test_debug_quantlib/bin/python",
"program": "${workspaceFolder}/test_debug.py",
"cwd": "${workspaceFolder}",
"env": {
"LD_LIBRARY_PATH": "${env:HOME}/quantlib-debug-install/lib",
"PYTHONUNBUFFERED": "1"
},
"stopOnEntry": true,
"justMyCode": false
},
{
"name": "2. GDB attach to Python",
"type": "cppdbg",
"request": "attach",
"program": "/<path-to-your-venv-folder>/test_debug_quantlib/bin/python",
"processId": "${command:pickProcess}",
"MIMode": "gdb",
"miDebuggerPath": "/usr/bin/gdb",
"setupCommands": [
{
"description": "Enable pretty-printing",
"text": "-enable-pretty-printing",
"ignoreFailures": true
},
{
"description": "Allow pending breakpoints",
"text": "set breakpoint pending on",
"ignoreFailures": true
}
]
}
]
}
This is the Python-launch and GDB-attach subset of the example’s configuration. The separate GDB-only launch and compound launch are intentionally omitted because neither is needed for the sequential workflow.
Several settings matter to the handoff:
stopOnEntry: truepauses Python before the script imports QuantLib, giving you time to attach GDB before the pricing code runs.LD_LIBRARY_PATHdirects the launched process toward the debug QuantLib library. It does not create debug symbols or guarantee that the installed extension is the correct build.justMyCode: falseallows Python-level inspection beyond your script. It does not turn Python stepping into C++ stepping.set breakpoint pending onlets a native breakpoint wait for the QuantLib shared library to load.processIdopens a process picker. You must select the actual script process, not a debug adapter or launcher.
Leave fork-following commands disabled for this example. You will attach directly to the script’s PID, so following a newly created child is unnecessary. Also leave set stop-on-solib-events 1 disabled, as shared-library loading stops would interrupt the intended sequence.
The VS Code Python Debugger extension supplies debugpy for this launch workflow. A separate terminal command using python -m debugpy would require that module to be available to the selected interpreter.
Understand the control model before pressing F5
Before starting the workflow, keep in mind that Python and GDB run as two separate debug sessions attached to the same operating-system process. VS Code does not combine them into one mixed-language debugger. The Python debugger displays Python frames. GDB displays native frames from the compiled extension and QuantLib library. Breakpoints are how you move your investigation from one debugger to the other.
The overall control flow is:
Start Python and pause at entry
-> Attach GDB to the same Python process
-> Continue Python to the first pricing call
-> GDB stops at a native breakpoint
-> Inspect or step through C++
-> Continue GDB so the native call can return
-> Resume Python and continue the script
In this workflow, F5 starts or continues the currently selected debug session. Before using it, confirm which session and frame are selected. The Python session should be started first and left paused at entry while you attach GDB to its PID. Once both sessions are active, use the debug toolbar dropdown to switch between 1. Python (debugpy) and 2. GDB attach to Python. This dropdown selects an active debugging session. It is different from the launch-configuration dropdown used to start or attach a debugger.
How to read the CALL STACK
The CALL STACK view lists frames for each debug session. It is not a single chronological stack that merges Python and C++ calls. Under 1. Python (debugpy), you can follow Python frames such as test_debug.py and QuantLib.py. Under 2. GDB attach to Python, you can inspect native frames such as the SWIG wrapper and QuantLib’s C++ functions when GDB is stopped.
A frame represents a function call at a particular point in that session’s execution. Selecting a frame changes the source location and variables shown by VS Code. Selecting the session determines which debugger receives commands such as Continue, F10, and F11. Check both the session and the highlighted frame before stepping or inspecting values.
When GDB stops at a C++ breakpoint, the Python call is waiting for the native function to return. Select the C++ session to inspect or continue the native code. After continuing GDB, switch back to the Python session to resume the script. This is why the session names and frame selection matter even though both sessions are attached to the same PID. The Call Stack helps you see which debugger currently owns the stop.
This distinction explains the most important rule in the walkthrough:
Before continuing or stepping, select the session and frame that own the current stop. When GDB has stopped the process, resume the C++ session first. Python cannot finish a pricing call while GDB has suspended its process.
3. Working example: follow one option through two pricing calls
The example deliberately keeps the financial setup small. It constructs a European call with a strike of 100, an initial spot of 100, a flat dividend yield of 2%, a flat risk-free rate of 5%, and constant volatility of 20%. The evaluation date is May 15, 1998, and exercise is on May 17, 1999.
QuantLib represents these inputs through a BlackScholesMertonProcess, then uses AnalyticEuropeanEngine to calculate the option value. This is an analytical pricing example, not a calibration exercise or a trading recommendation.
Save the following as test_debug.py in the workspace root:
import QuantLib as ql
def build_option():
today = ql.Date(15, ql.May, 1998)
ql.Settings.instance().evaluationDate = today
payoff = ql.PlainVanillaPayoff(ql.Option.Call, 100.0)
exercise = ql.EuropeanExercise(ql.Date(17, ql.May, 1999))
option = ql.VanillaOption(payoff, exercise)
spot = ql.SimpleQuote(100.0)
dividend = ql.FlatForward(today, 0.02, ql.Actual365Fixed())
risk_free = ql.FlatForward(today, 0.05, ql.Actual365Fixed())
volatility = ql.BlackConstantVol(today, ql.TARGET(), 0.20, ql.Actual365Fixed())
process = ql.BlackScholesMertonProcess(
ql.QuoteHandle(spot),
ql.YieldTermStructureHandle(dividend),
ql.YieldTermStructureHandle(risk_free),
ql.BlackVolTermStructureHandle(volatility),
)
engine = ql.AnalyticEuropeanEngine(process)
option.setPricingEngine(engine)
return option, spot
def main():
option, spot = build_option()
print("Initial NPV:", option.NPV())
# Change an input and price again so breakpoints in QuantLib pricing code
# are hit from a second, easy-to-repeat call.
spot.setValue(105.0)
print("Repriced NPV:", option.NPV())
if __name__ == "__main__":
main()
NPV() returns the option’s net present value. For debugging, the important feature is not the complexity of the payoff but the two calls separated by a change to a live input.
QuantLib can reuse cached results when nothing has changed. Calling NPV() twice without changing an input may therefore skip the pricing engine on the second call. Updating the SimpleQuote invalidates the dependent calculation, giving us a second opportunity to stop inside the engine.
The README records the following expected output:
Initial NPV: 9.25485869123328
Repriced NPV: 12.416641769134362
The increase is consistent with raising spot for this vanilla call under the stated assumptions. Matching the output is useful, but it does not prove that either debugger has reached the intended code. We will verify that through the breakpoint sequence.
4. Set breakpoints on both sides of the boundary
Python breakpoints
Set these three breakpoints in test_debug.py:
| Line in the supplied script | Statement | Why stop here? |
|---|---|---|
| 32 | print("Initial NPV:", option.NPV()) |
Pause immediately before the first pricing call. |
| 36 | spot.setValue(105.0) |
Observe the input change that triggers recalculation. |
| 37 | print("Repriced NPV:", option.NPV()) |
Pause immediately before the second pricing call. |
A Python line breakpoint stops before that line executes. If you edit the script, locate the statements rather than relying on the original line numbers.
5. Run the workflow: start Python, then attach GDB
Step 1. Launch only the Python session
After saving launch.json, use these steps to open the launch-configuration list:
- Open Run and Debug by clicking its play-and-bug icon in the Activity Bar, or press Ctrl+Shift+D.
- At the top of the Run and Debug panel, click the configuration dropdown. In the screenshot, it currently displays 1. Python (debugpy).
- Choose 1. Python (debugpy) to launch the Python script, or 2. GDB attach to Python to attach GDB to the running process.
The screenshot shows the dropdown open with both configurations available.
Because stopOnEntry is enabled, Python should pause before the script starts executing its pricing setup.
Checkpoint: VS Code should show a paused Python session and a highlighted entry statement. Leave it paused while you identify the process and attach GDB.
Use this sequential startup rather than the compound launch included in the original project. Starting both sessions concurrently does not guarantee that the script process is ready when the native process picker opens.
Step 2. Identify the actual Python process
To open the Debug Console and run an expression in the paused Python session:
- In the VS Code menu, select View > Debug Console. You can also open the Command Palette with Ctrl+Shift+P, type Debug Console, and select View: Debug Console.
- In CALL STACK, select a frame belonging to 1. Python (debugpy). A frame represents a particular function call in the paused program.
- Click the Debug Console prompt and enter this expression:
__import__("os").getpid()
Record the returned number. It is the process identifier (PID) of the Python interpreter running this script, and it is the identifier you will select when attaching GDB.
Do not choose a process merely because its name contains python. VS Code may also be running Python debug adapters or launchers, and attaching to one of those would not expose the option’s calculation.
Step 3. Attach the native debugger
Keep the Python session paused, then:
- Select 2. GDB attach to Python in the launch configuration list.
- Open the Command Palette and run Debug: Start Debugging.
- In the process picker, choose the entry whose PID matches the number recorded in Step 2.
In the Attach to process picker, type or locate the PID recorded from the Python Debug Console and select the matching Python process. Confirm that the process path belongs to the virtual environment used for this walkthrough.
You should now see both sessions in CALL STACK. From this point onward, the Python session means 1. Python (debugpy), and the C++ session means 2. GDB attach to Python.
GDB may pause the process immediately after attaching. If it does, select a frame in the C++ session and press Continue once. This releases GDB’s native stop. It does not require Python to advance past its separate entry pause.
Before moving on, the intended state is:
- Python is paused at entry, ready for you to continue the script.
- GDB is attached to that same PID and is running, ready to stop when the native breakpoint is reached.
If this is not the state you see, resolve the attachment or pause state before continuing. It is easier to establish the correct starting point than to recover after a pricing call has already run.
Step 4. Set the first C++ breakpoint
Once GDB is attached to the Python PID and running, select the Python session and continue to the first pricing breakpoint, line 32 in the supplied script:
print("Initial NPV:", option.NPV())
Press F11 (Step Into), or select Step Into on the debug toolbar. With the Python session selected, this follows option.NPV() into the generated Python wrapper, QuantLib.py. If necessary, keep stepping until execution is paused before this statement:
return _QuantLib.Instrument_NPV(self)
This line marks the boundary we want to inspect. QuantLib.py provides the Python-facing method, while _QuantLib is the compiled extension module. Calling its Instrument_NPV function transfers execution to the native binding generated by SWIG, before QuantLib’s C++ instrument and pricing logic run.
The corresponding C++ binding is in the generated wrapper source, quantlib_wrap.cpp (the filename’s capitalization can vary with the build). In this build, the native entry point is named _wrap_Instrument_NPV. Notice the naming connection: the Python call to _QuantLib.Instrument_NPV(self) maps to the SWIG wrapper _wrap_Instrument_NPV. The leading underscore in _QuantLib matters because this is the extension module, not the top-level QuantLib package.
This gives us a native starting point without first knowing which pricing engine the instrument will use. We identify the boundary from the Python call in front of us, rather than guessing where to place a breakpoint deeper in QuantLib.
Before proceeding, confirm that the wrapper displayed in the editor belongs to the running environment. With a Python frame selected and GDB running, evaluate these expressions individually in the Python session’s Debug Console:
__import__("sys").executable
ql.__file__
__import__("QuantLib._QuantLib", fromlist=["_QuantLib"]).__file__
They identify the Python interpreter, the Python wrapper, and the compiled extension actually loaded by the process. The second expression assumes that the selected frame has the script’s ql import available. If you are inside QuantLib.py, select the calling frame in test_debug.py to evaluate it, then return to the wrapper frame.
In the environment comparison behind this example, a wrapper opened from general differed from the one used by the launch configuration’s test_debug_quantlib interpreter. A location such as line 16598 in one wrapper is therefore not a reliable breakpoint location in the other. Use the files reported by the running process, not simply a similarly named file already open in VS Code.
To stop at that native entry point without searching the generated C++ file:
- Leave Python paused before the
returnstatement. - Switch to the C++ session. If GDB is running, use Pause, not Stop. Stop would end the debugging session rather than temporarily suspend execution.
- With the C++ session selected, enter the following in its Debug Console:
-exec tbreak _wrap_Instrument_NPV
The Debug Console should confirm that GDB set a temporary breakpoint for this symbol. The screenshot shows the command and the resulting confirmation:
tbreak creates a temporary breakpoint, which GDB automatically removes after it is hit. The symbol name comes from this generated binding, so it should not be assumed to be identical in every SWIG build. If GDB cannot resolve it, check the loaded extension’s symbols and matching generated source.
For the repeatable engine stops used later in this walkthrough, also keep a regular breakpoint enabled inside AnalyticEuropeanEngine::calculate() in ql/pricingengines/vanilla/analyticeuropeanengine.cpp. Alternatively, add the function breakpoint QuantLib::AnalyticEuropeanEngine::calculate() const in VS Code’s BREAKPOINTS view. This is a convenience for this known example, not a prerequisite for discovering the engine through native stepping. Unlike the temporary wrapper breakpoint, the regular engine breakpoint remains available for both pricing calls.
Finally, Continue the C++ session. This releases the native pause while Python remains paused at the wrapper’s return statement. We are now ready to execute that statement and catch its entry into C++.
Checkpoint: Python is paused in QuantLib.py, GDB is running on the same PID, and the temporary SWIG-entry breakpoint is armed. Setting the breakpoint does not itself execute the Python call.
6. Follow the first Python-to-C++ handoff
Step 5. Execute the wrapper call and stop in C++
With the Python session selected, press F10 (Step Over) to execute the current line.
The current line invokes _QuantLib.Instrument_NPV(self). Step Over does not disable GDB’s breakpoints. GDB should stop first at _wrap_Instrument_NPV in the generated C++ wrapper. Select the C++ session/frame to inspect this entry point. GDB removes the temporary breakpoint after it is hit.
This is the first native C++ stop reached from the Python pricing call. The C++ debugger is paused inside the SWIG-generated _wrap_Instrument_NPV function in quantlib_wrap.cpp:
quantlib_wrap.cpp wrapper at _wrap_Instrument_NPV.The wrapper marks the boundary between Python and C++. It is not the pricing engine itself. From this stop, either continue the C++ session to the regular engine breakpoint or follow the intervening implementation as described below.
Follow the wrapper into QuantLib
The generated wrapper first converts and validates the Python arguments. The key native call in this build is:
result = (Real)((Instrument const *)arg1)->NPV();
In the C++ session, use Step Over from the debugger controls (or press F10) until execution reaches this call. Alternatively, set a breakpoint on the call and press Continue (F5) to run to it. Unlike F10, F5 continues execution until it reaches a breakpoint or another stop condition.
The screenshot shows the debugger paused at this statement:
Instrument::NPV().In practical terms, the wrapper has obtained a pointer to the underlying C++ instrument and is requesting its value. You can reach the implementation behind this call in either of two ways:
-
Inspect the conversion work: use F10 in the C++ session until the call above is the next statement, then press F11 to enter
NPV(). Execution should stop in QuantLib’sinstrument.hppheader at the inline implementation ofInstrument::NPV().
After stepping into the wrapper's NPV()call, the C++ debugger is in the inlineInstrument::NPV()implementation ininstrument.hpp. -
Skip the conversion work: while stopped in the wrapper, set another temporary breakpoint in the C++ session’s Debug Console, then continue the session:
-exec tbreak QuantLib::Instrument::NPV
With matching symbols and source files available, GDB should stop in Instrument::NPV(). Its implementation is:
inline Real Instrument::NPV() const {
calculate();
QL_REQUIRE(NPV_ != Null<Real>(), "NPV not provided");
return NPV_;
}
The method requests a calculation, verifies that a value was provided, and returns it. From this point, F11 performs native C++ stepping. It does not automatically issue a Python command across the language boundary. Step into calculate() to follow the instrument’s calculation logic.
Moving beyond header files in C++ debugging
The QuantLib implementation we have followed so far is in header files such as .hpp or .h. The SWIG wrapper is generated binding code. To examine the pricing logic in greater detail, continue into the engine’s .cpp implementation. In this example, pressing Step Into (F11) leads to the code below in instrument.hpp. The engine_ member identifies the pricing engine used for this calculation.
inline void Instrument::performCalculations() const {
QL_REQUIRE(engine_, "null pricing engine");
engine_->reset();
setupArguments(engine_->getArguments());
engine_->getArguments()->validate();
engine_->calculate();
fetchResults(engine_->getResults());
}
How can we identify the pricing engine in use? The Python code that constructs the instrument can provide a clue, but we can also inspect the engine directly. While paused in the code above, enter the following command in the C++ Debug Console. It calls get() and prints the object referenced by engine_. In this example, the output identifies the concrete pricing engine as QuantLib::AnalyticEuropeanEngine.
-exec print *engine_.get()
Instrument::performCalculations(), with the attached pricing engine inspected in the Debug Console.Setting a breakpoint in the pricing engine’s .cpp file
Now that we have identified the engine, we can set a breakpoint in its function and inspect the implementation in a .cpp file. Enter the command below in the C++ Debug Console. Include const in the function signature so that GDB can resolve the breakpoint correctly.
-exec break QuantLib::AnalyticEuropeanEngine::calculate() const
AnalyticEuropeanEngine::calculate() implementation in the C++ Debug Console.Next, continue to the breakpoint. The debugger should stop in the pricing engine’s implementation, where you can step through the code and inspect how the calculation proceeds.
AnalyticEuropeanEngine::calculate() and pauses in the pricing engine's source.Execution path through the debuggers
For this unexpired option, when recalculation is required, execution follows this path:
Python: option.NPV()
-> Python wrapper: _QuantLib.Instrument_NPV(self)
-> C++ SWIG wrapper: _wrap_Instrument_NPV(...)
-> QuantLib::Instrument::NPV()
-> Instrument::calculate()
-> LazyObject::calculate()
-> Instrument::performCalculations()
-> engine_->calculate()
-> AnalyticEuropeanEngine::calculate()
LazyObject determines whether a cached result can be reused. performCalculations() prepares the engine’s arguments, invokes the engine, and retrieves its results. At engine_->calculate(), press F11 to follow the virtual call to the engine attached to the instrument. Because virtual dispatch selects the concrete implementation at runtime, you do not need to know the engine’s class name in advance.
This path depends on the instrument’s state. An expired instrument may take the expiry branch, while a cached or frozen calculation may bypass the engine. Compiler inlining and available debug information can also affect which source-level stops GDB exposes.
Whether you stepped through the calls or continued to the regular breakpoint, the next checkpoint is the pricing engine:
Checkpoint: VS Code should be paused in the engine’s C++ source. Before inspecting variables or stepping further, select the relevant frame in the C++ session.
You can now inspect this, the current engine object, and its members. As you step through the function, inspect local variables after they are initialized. This helps connect the model inputs created in Python to the quantities used by the pricing implementation.
Use F10 to execute the next C++ statement without entering a called function, or F11 to step into a C++ function when its source is available. On the first pass, keep the investigation focused so that the handoff back to Python remains easy to follow.
The Python session may still appear to be running, but this does not mean it has advanced past the pricing line. Its step-over is waiting for the native call that GDB has paused.
Avoid calling
option.NPV()from Watches or the Debug Console during this exercise. Evaluating it can trigger another calculation or return a cached result, which can make the intended sequence harder to follow. Inspect existing values instead of introducing additional pricing calls.
Step 6. Let the native calculation return
With the C++ session selected, press Continue to let the native calculation finish.
The result returns through the SWIG wrapper, allowing Python to complete its pending step in QuantLib.py. Select the Python session and press Continue to reach the next explicit Python breakpoint:
spot.setValue(105.0)
Checkpoint: Python should now highlight the spot-update statement. It has not executed yet. Select the Python session/frame before taking the next step.
If another native breakpoint interrupts the return, inspect it and continue the C++ session first. Do not attempt to complete the Python step while GDB has the process paused.
7. Change spot and repeat the handoff
Step 7. Execute the input update
Check that Python is paused at spot.setValue(105.0), then press F10 with the Python session selected.
The quote changes from 100.0 to 105.0. Python should then pause before the second pricing statement:
print("Repriced NPV:", option.NPV())
Checkpoint: the input update has executed, but the repricing call has not. Changing the observable quote invalidates the dependent cached calculation. The next NPV() request should therefore run the engine again, rather than simply return the previous result.
Step 8. Enter the pricing engine a second time
Press F10 again with the Python session selected.
GDB should stop inside AnalyticEuropeanEngine::calculate() again. Select the C++ session/frame and, if useful, follow the same statements you inspected during the first call. Comparing the same point in both calculations is more informative than comparing variables at different stages of initialization.
When you are ready, press Continue in the C++ session so the repricing call can finish. If Python pauses after its pending step completes, select the Python session and continue to program exit.
Completion check: you should have observed two engine breakpoint hits, one for each explicit pricing call, with the Python spot update between them. Compare the program output with the expected values shown earlier. Numerical output alone does not confirm that you followed the intended native path.
The intended sequence is:
Python: initial NPV line
-> Python: QuantLib.py wrapper
-> C++: temporary SWIG-entry breakpoint
-> C++: pricing engine, first call
-> Python: spot update
-> Python: repricing line
-> C++: pricing engine, second call
-> Python: completion
The following checklist summarizes who owns each action:
| Current stop | Session to select | Action | Expected next stop |
|---|---|---|---|
| Python entry, with GDB attached and running | Python | Continue | Initial NPV line |
| Initial NPV line | Python | F11 | Python wrapper in QuantLib.py |
| Python wrapper, with the temporary native breakpoint armed and GDB running | Python | F10 | C++ SWIG entry point |
| SWIG entry point | C++ | Continue | C++ pricing engine |
| First engine calculation | C++, then Python | Continue C++, then continue Python after its step completes | Python spot update |
| Spot update | Python | F10 | Python repricing line |
| Repricing line | Python | F10 | C++ pricing engine again |
| Second engine calculation | C++ | Continue | Python completes its pending step |
| Python paused after repricing | Python | Continue | Program exit |
The result: an explainable path from Python to the pricing engine
The useful outcome is not simply having two debug sessions open. It is being able to stop before a financial calculation, inspect the native implementation that produces it, and return to the Python code that consumes the result.
Python builds the instrument and changes its inputs. The SWIG extension connects those calls to QuantLib. The C++ pricing engine calculates the result. Boundary breakpoints and explicit session selection let you inspect each layer without expecting one debugger to understand them all.
Once both pricing calls follow the intended sequence, you have a repeatable starting point for investigating custom instruments, pricing engines, and binding behavior. That establishes visibility into the implementation, not proof that a model’s assumptions or outputs are economically correct.
8. Troubleshooting
If the sequence becomes confusing, first check which debugger owns the current stop. A pricing call can look stalled simply because the other session is waiting for you to resume it.
| Symptom | What to check / do |
|---|---|
| The next debugger step seems wrong | Check the selected session and frame before using F5, F10, or F11. These commands apply only to the selected debugging context. F11 does not automatically cross from Python into C++. Set a breakpoint in the destination language and switch sessions when it hits. |
| Python appears frozen during a pricing call | Check CALL STACK. If GDB has stopped the process, select the C++ frame and continue that session first so the native call can return. If both sessions paused just after attachment, continue GDB, then resume Python from its entry pause. |
| The C++ breakpoint is still unverified at the first NPV call | A pending breakpoint is expected before QuantLib loads. Once the import has occurred, inspect the loaded library with -exec info sharedlibrary in the C++ Debug Console. Verify that the intended debug QuantLib library and SWIG extension are loaded, have debug information, and match the available sources. |
| GDB finds a function but cannot open its source | Add a sourceFileMap to the C++ attach configuration, mapping the original build path to the current source path. Add another mapping for QuantLib-SWIG if needed. The mapped source must still match the compiled version. |
| The first engine breakpoint hits, but the second does not | Confirm Python executed spot.setValue(105.0), reached the repricing line, and stepped with the Python session selected. Check that GDB is still attached to the same PID, running, and has the engine breakpoint enabled. Unchanged inputs may use cached results and skip recalculation. |
| GDB refuses to attach | Confirm the selected PID is the script’s Python process, then check process ownership and the machine’s Linux ptrace policy. Follow the system’s approved debugging policy rather than broadly weakening security settings. |
Throughout the workflow, keep both debuggers attached to the same PID, and if Python restarts, get its new PID and reattach GDB. Disable unrelated breakpoints and shared-library event stops while learning the sequence. The GDB-only configuration can help investigate C++ execution, but it does not activate Python breakpoints and is not a replacement for this two-session workflow.