Patch private methods in python | Rida Ayed

Patch private methods in python

I’ve encountered this rather profane yet tricky problem while testing a method:

class MyClass:

    def __method(self) -> str:
        pass
def test()
   with patch.object(MyClass,"__method") as _:
       pass
pytest
E           AttributeError: <class 'MyClass'> does not have the attribute '__method'

A llm pointed to the name mangling cause.
Changing __method to _MyClass__method fixes the error:

def test()
   with patch.object(MyClass,"_MyClass__method") as _:
       pass

The reason for this post, is that searching (ctrl+f) for ‘mangl’ or ‘priv’ yields nothing from the doc1