Yaroslav Bulatov Yaroslav Bulatov - 6 months ago 43
Python Question

Overriding multiple global variables with ContextManager

Is there a utility/pattern to override multiple global variables within a context in Python 2.7? IE something like

var1 = someval
var2 = someotherval
with my_context(var1=newval1, var2=newval2,...):
print var1 # prints newval1

Answer

Yes, but the fact that it's unittest.mock.patch should tell you something about what this is intended to be used for:

import unittest.mock

with unittest.mock.patch('module.thing', replacement_thing):
    do_whatever()

It only accepts one target to patch, but you can just use it repeatedly to patch multiple things:

from unittest.mock import patch

with patch('module.thing1', replacement_thing), patch('module.thing2', other_thing):
    do_whatever()

If you want to do this for non-unit-testing purposes, you may want to reconsider your design.

If you're on Python 2 and unittest.mock isn't in the standard library, you can download the backport from PyPI. This one is called mock rather than unittest.mock.