Search code examples
pythoncontextmanager

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

Solution

  • 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()
    

    If you want to patch several things in the same call, you can use unittest.mock.patch.multiple:

    from unittest.mock import patch
    
    with patch.multiple(module, thing1=replacement_thing, thing2=other_thing):
        # module.thing1 and module.thing2 are now patched
        do_whatever()
    

    Just make sure none of the things you want to patch happen to collide with the argument names of that function (target, spec, create, spec_set, autospec, or new_callable). If they do, fall back to the regular patch.

    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.