Add context() method to registry.Value objects. Closes GH-430.

This method returns a context objet, for use with the 'with' statement.
This commit is contained in:
Valentin Lorentz 2012-12-08 20:05:51 +01:00
parent 69c60ca1f5
commit 4e8c35dd0c
2 changed files with 19 additions and 0 deletions

View File

@ -360,6 +360,18 @@ class Value(Group):
for callback, args, kwargs in self._callbacks: for callback, args, kwargs in self._callbacks:
callback(*args, **kwargs) 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): def addCallback(self, callback, *args, **kwargs):
"""Add a callback to the list. A callback is a function that will be """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 called when the value is changed. You can give this function as many

View File

@ -174,4 +174,11 @@ class ValuesTestCase(SupyTestCase):
registry.open_registry(filename) registry.open_registry(filename)
self.assertEqual(conf.supybot.reply.whenAddressedBy.chars(), '\\') 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: # vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79: