In particular, I want to see which magic method is being called by a particular line of code.
For instance, I know that 1 + 2
actually calls (1).__add__(2)
and [1,2,3][0]
calls [1,2,3].__getitem__(0)
.
I'd like to know which magic methods are called for other operations without having to look it up online.
There isn't a good way to inspect that. You should probably just look it up.
In the implementation (specifically for CPython), 1 + 2
or [1, 2, 3][0]
won't actually go through the __add__
or __getitem__
methods at all; they'll go through C-level hooks and skip the methods entirely. Even if they went through the methods, it'd all happen in C-level code, which you can't debug with PDB or do much of anything to inspect.
The closest I have to something matching the spirit of what you're looking for is
>>> import unittest.mock
>>> unittest.mock.MagicMock() + 3
<MagicMock name='mock.__add__()' id='140290799397408'>
so hey, look! +
uses __add__
. That's something you can run to see what magic method is invoked for +
. It doesn't involve actually inspecting the magic methods involved in +
, though. MagicMock
just has already-written implementations of most of the standard magic methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With