Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect method calls made by Python behind the scenes?

Tags:

python

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.

like image 508
japseow Avatar asked Aug 06 '18 06:08

japseow


1 Answers

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.

like image 185
user2357112 supports Monica Avatar answered Nov 03 '22 02:11

user2357112 supports Monica