diff --git a/src/registry.py b/src/registry.py index d196c8eff..1981fca42 100644 --- a/src/registry.py +++ b/src/registry.py @@ -360,6 +360,18 @@ class Value(Group): for callback, args, kwargs in self._callbacks: callback(*args, **kwargs) + def context(self, value): + """Return a context manager object, which sets this variable to a + temporary value, and set the previous value back when exiting the + context.""" + class Context: + def __enter__(self2): + self2._old_value = self.value + self.setValue(value) + def __exit__(self2, exc_type, exc_value, traceback): + self.setValue(self2._old_value) + return Context() + def addCallback(self, callback, *args, **kwargs): """Add a callback to the list. A callback is a function that will be called when the value is changed. You can give this function as many diff --git a/test/test_registry.py b/test/test_registry.py index 6d18d2148..9a8826ace 100644 --- a/test/test_registry.py +++ b/test/test_registry.py @@ -174,4 +174,11 @@ class ValuesTestCase(SupyTestCase): registry.open_registry(filename) self.assertEqual(conf.supybot.reply.whenAddressedBy.chars(), '\\') + def testWith(self): + v = registry.String('foo', 'help') + self.assertEqual(v(), 'foo') + with v.context('bar'): + self.assertEqual(v(), 'bar') + self.assertEqual(v(), 'foo') + # vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79: