Mock Python's built in print function

前端 未结 11 1956
醉话见心
醉话见心 2020-12-06 09:10

I\'ve tried

from mock import Mock
import __builtin__

__builtin__.print = Mock()

But that raises a syntax error. I\'ve also tried patching

11条回答
  •  独厮守ぢ
    2020-12-06 09:41

    First, the module is called __builtins__ and you don't need to import it.

    Now, in Python 2 print is a keyword so you can't use it as an attribute name directly. You can use setattr/getattr to workaround it:

    getattr(__builtins__, "print")
    

    Another option is to use from __future__ import print_function which changes how Python parses the module to Python 3 syntax.

提交回复
热议问题