RSS Amplifier

Rida Ayed · Feb 8, 2026

Patch private methods in python

0
Sign in to vote or save

This page cannot be shown here. You can still read it on the original site — the toolbar below keeps your place in the directory.

I&rsquo;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…

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


  1. https://docs.python.org/3/library/unittest.mock.html
     ↩︎

Read on /posts/patch-private-methods-in-python/

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.