diff Modules/threadmodule.c @ 36737:fa92fe15251a legacy-trunk

Updates to the with-statement: - New semantics for __exit__() -- it must re-raise the exception if type is not None; the with-statement itself doesn't do this. (See the updated PEP for motivation.) - Added context managers to: - file - thread.LockType - threading.{Lock,RLock,Condition,Semaphore,BoundedSemaphore} - decimal.Context - Added contextlib.py, which defines @contextmanager, nested(), closing(). - Unit tests all around; bot no docs yet.
author Guido van Rossum <guido@python.org>
date Tue, 28 Feb 2006 21:57:43 +0000
parents 1af7f719ed28
children fd735596f69c
line wrap: on
line diff
--- a/Modules/threadmodule.c	Tue Feb 28 21:41:30 2006 +0000
+++ b/Modules/threadmodule.c	Tue Feb 28 21:57:43 2006 +0000
@@ -116,6 +116,36 @@
 \n\
 Return whether the lock is in the locked state.");
 
+static PyObject *
+lock_context(lockobject *self)
+{
+	Py_INCREF(self);
+	return (PyObject *)self;
+}
+
+PyDoc_STRVAR(lock_exit_doc,
+"__exit__(type, value, tb)\n\
+\n\
+Releases the lock; then re-raises the exception if type is not None.");
+
+static PyObject *
+lock_exit(lockobject *self, PyObject *args)
+{
+	PyObject *type, *value, *tb, *result;
+	if (!PyArg_ParseTuple(args, "OOO:__exit__", &type, &value, &tb))
+		return NULL;
+	result = lock_PyThread_release_lock(self);
+	if (result != NULL && type != Py_None) {
+		Py_DECREF(result);
+		result = NULL;
+		Py_INCREF(type);
+		Py_INCREF(value);
+		Py_INCREF(tb);
+		PyErr_Restore(type, value, tb);
+	}
+	return result;
+}
+
 static PyMethodDef lock_methods[] = {
 	{"acquire_lock", (PyCFunction)lock_PyThread_acquire_lock, 
 	 METH_VARARGS, acquire_doc},
@@ -129,6 +159,12 @@
 	 METH_NOARGS, locked_doc},
 	{"locked",       (PyCFunction)lock_locked_lock,  
 	 METH_NOARGS, locked_doc},
+	{"__context__",  (PyCFunction)lock_context,
+	 METH_NOARGS, PyDoc_STR("__context__() -> self.")},
+	{"__enter__",    (PyCFunction)lock_PyThread_acquire_lock,
+	 METH_VARARGS, acquire_doc},
+	{"__exit__",    (PyCFunction)lock_exit,
+	 METH_VARARGS, lock_exit_doc},
 	{NULL,           NULL}		/* sentinel */
 };