Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python mock return value

Tags:

python

mocking

Normally, when using mock, I'll have

from mock import Mock

m = Mock()
m
<Mock id='4334328720'>

Is it possible to change this output?

like image 563
Nam Ngo Avatar asked May 03 '26 09:05

Nam Ngo


1 Answers

Sure. You can inherit from Mock and change the __repr__ method:

from mock import Mock
class Mock2(Mock):
    def __repr__(self):
        return "Hello World!"

m = Mock2()

>> m
Hello World!

You could also dynamically change the __repr__ method of your object like this:

from mock import Mock
m = Mock()

def new_repr(self):
    return "Hello dynamic Python!"
m.__repr__ = new_repr

>> m
Hello dynamic Python!
like image 105
Qlaus Avatar answered May 05 '26 00:05

Qlaus