From python-3000-checkins at python.org Thu Aug 17 07:40:04 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Thu, 17 Aug 2006 07:40:04 +0200 (CEST) Subject: [Python-3000-checkins] r51335 - python/branches/p3yk/Modules/pyexpat.c Message-ID: <20060817054004.7F44D1E4004@bag.python.org> Author: guido.van.rossum Date: Thu Aug 17 07:40:03 2006 New Revision: 51335 Modified: python/branches/p3yk/Modules/pyexpat.c Log: Get rid of the last mention of WITH_CYCLE_GC that I could find. Modified: python/branches/p3yk/Modules/pyexpat.c ============================================================================== --- python/branches/p3yk/Modules/pyexpat.c (original) +++ python/branches/p3yk/Modules/pyexpat.c Thu Aug 17 07:40:03 2006 @@ -1665,7 +1665,6 @@ return -1; } -#ifdef WITH_CYCLE_GC static int xmlparse_traverse(xmlparseobject *op, visitproc visit, void *arg) { @@ -1682,7 +1681,6 @@ Py_CLEAR(op->intern); return 0; } -#endif PyDoc_STRVAR(Xmlparsetype__doc__, "XML parser"); @@ -1714,12 +1712,8 @@ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /*tp_flags*/ #endif Xmlparsetype__doc__, /* tp_doc - Documentation string */ -#ifdef WITH_CYCLE_GC (traverseproc)xmlparse_traverse, /* tp_traverse */ (inquiry)xmlparse_clear /* tp_clear */ -#else - 0, 0 -#endif }; /* End of code for xmlparser objects */ From python-3000-checkins at python.org Thu Aug 17 07:43:01 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Thu, 17 Aug 2006 07:43:01 +0200 (CEST) Subject: [Python-3000-checkins] r51336 - in python/branches/p3yk: Include/Python.h Include/classobject.h Include/methodobject.h Include/object.h Include/structmember.h Modules/_sre.c Modules/arraymodule.c Modules/cPickle.c Modules/gcmodule.c Objects/abstract.c Objects/bytesobject.c Objects/classobject.c Objects/dictobject.c Objects/listobject.c Objects/object.c Objects/setobject.c Objects/stringobject.c Objects/typeobject.c Objects/unicodeobject.c Python/ceval.c Python/structmember.c README Message-ID: <20060817054301.78C581E4004@bag.python.org> Author: guido.van.rossum Date: Thu Aug 17 07:42:55 2006 New Revision: 51336 Modified: python/branches/p3yk/Include/Python.h python/branches/p3yk/Include/classobject.h python/branches/p3yk/Include/methodobject.h python/branches/p3yk/Include/object.h python/branches/p3yk/Include/structmember.h python/branches/p3yk/Modules/_sre.c python/branches/p3yk/Modules/arraymodule.c python/branches/p3yk/Modules/cPickle.c python/branches/p3yk/Modules/gcmodule.c python/branches/p3yk/Objects/abstract.c python/branches/p3yk/Objects/bytesobject.c python/branches/p3yk/Objects/classobject.c python/branches/p3yk/Objects/dictobject.c python/branches/p3yk/Objects/listobject.c python/branches/p3yk/Objects/object.c python/branches/p3yk/Objects/setobject.c python/branches/p3yk/Objects/stringobject.c python/branches/p3yk/Objects/typeobject.c python/branches/p3yk/Objects/unicodeobject.c python/branches/p3yk/Python/ceval.c python/branches/p3yk/Python/structmember.c python/branches/p3yk/README Log: Completely get rid of PyClass and PyInstance. (classobject.[ch] aren't empty yet because they also define PyMethod.) This breaks lots of stuff, notably cPickle. But it's a step in the right direction. I'll clean it up later. (Also a few unrelated changes, e.g. T_NONE to define a "struct member" that is always None, and simplification of __hash__ -- these are unfinished.) Modified: python/branches/p3yk/Include/Python.h ============================================================================== --- python/branches/p3yk/Include/Python.h (original) +++ python/branches/p3yk/Include/Python.h Thu Aug 17 07:42:55 2006 @@ -7,14 +7,6 @@ #include "patchlevel.h" #include "pyconfig.h" -/* Cyclic gc is always enabled, starting with release 2.3a1. Supply the - * old symbol for the benefit of extension modules written before then - * that may be conditionalizing on it. The core doesn't use it anymore. - */ -#ifndef WITH_CYCLE_GC -#define WITH_CYCLE_GC 1 -#endif - #include #ifndef UCHAR_MAX Modified: python/branches/p3yk/Include/classobject.h ============================================================================== --- python/branches/p3yk/Include/classobject.h (original) +++ python/branches/p3yk/Include/classobject.h Thu Aug 17 07:42:55 2006 @@ -1,5 +1,4 @@ - -/* Class object interface */ +/* Former class object interface -- now only (un)bound methods are here */ /* Revealing some structures (not for general use) */ @@ -11,58 +10,22 @@ typedef struct { PyObject_HEAD - PyObject *cl_bases; /* A tuple of class objects */ - PyObject *cl_dict; /* A dictionary */ - PyObject *cl_name; /* A string */ - /* The following three are functions or NULL */ - PyObject *cl_getattr; - PyObject *cl_setattr; - PyObject *cl_delattr; -} PyClassObject; - -typedef struct { - PyObject_HEAD - PyClassObject *in_class; /* The class object */ - PyObject *in_dict; /* A dictionary */ - PyObject *in_weakreflist; /* List of weak references */ -} PyInstanceObject; - -typedef struct { - PyObject_HEAD PyObject *im_func; /* The callable object implementing the method */ PyObject *im_self; /* The instance it is bound to, or NULL */ PyObject *im_class; /* The class that asked for the method */ PyObject *im_weakreflist; /* List of weak references */ } PyMethodObject; -PyAPI_DATA(PyTypeObject) PyClass_Type, PyInstance_Type, PyMethod_Type; +PyAPI_DATA(PyTypeObject) PyMethod_Type; -#define PyClass_Check(op) ((op)->ob_type == &PyClass_Type) -#define PyInstance_Check(op) ((op)->ob_type == &PyInstance_Type) #define PyMethod_Check(op) ((op)->ob_type == &PyMethod_Type) -PyAPI_FUNC(PyObject *) PyClass_New(PyObject *, PyObject *, PyObject *); -PyAPI_FUNC(PyObject *) PyInstance_New(PyObject *, PyObject *, - PyObject *); -PyAPI_FUNC(PyObject *) PyInstance_NewRaw(PyObject *, PyObject *); PyAPI_FUNC(PyObject *) PyMethod_New(PyObject *, PyObject *, PyObject *); PyAPI_FUNC(PyObject *) PyMethod_Function(PyObject *); PyAPI_FUNC(PyObject *) PyMethod_Self(PyObject *); PyAPI_FUNC(PyObject *) PyMethod_Class(PyObject *); -/* Look up attribute with name (a string) on instance object pinst, using - * only the instance and base class dicts. If a descriptor is found in - * a class dict, the descriptor is returned without calling it. - * Returns NULL if nothing found, else a borrowed reference to the - * value associated with name in the dict in which name was found. - * The point of this routine is that it never calls arbitrary Python - * code, so is always "safe": all it does is dict lookups. The function - * can't fail, never sets an exception, and NULL is not an error (it just - * means "not found"). - */ -PyAPI_FUNC(PyObject *) _PyInstance_Lookup(PyObject *pinst, PyObject *name); - /* Macros for direct access to these values. Type checks are *not* done, so use with care. */ #define PyMethod_GET_FUNCTION(meth) \ @@ -72,9 +35,6 @@ #define PyMethod_GET_CLASS(meth) \ (((PyMethodObject *)meth) -> im_class) -PyAPI_FUNC(int) PyClass_IsSubclass(PyObject *, PyObject *); - - #ifdef __cplusplus } #endif Modified: python/branches/p3yk/Include/methodobject.h ============================================================================== --- python/branches/p3yk/Include/methodobject.h (original) +++ python/branches/p3yk/Include/methodobject.h Thu Aug 17 07:42:55 2006 @@ -63,7 +63,7 @@ #define METH_CLASS 0x0010 #define METH_STATIC 0x0020 -/* METH_COEXIST allows a method to be entered eventhough a slot has +/* METH_COEXIST allows a method to be entered even though a slot has already filled the entry. When defined, the flag allows a separate method, "__contains__" for example, to coexist with a defined slot like sq_contains. */ Modified: python/branches/p3yk/Include/object.h ============================================================================== --- python/branches/p3yk/Include/object.h (original) +++ python/branches/p3yk/Include/object.h Thu Aug 17 07:42:55 2006 @@ -147,7 +147,7 @@ typedef int (*traverseproc)(PyObject *, visitproc, void *); typedef struct { - /* Number implementations should check *both* + /* Number implementations must check *both* arguments for proper type and implement the necessary conversions in the slot functions themselves. */ @@ -173,7 +173,7 @@ unaryfunc nb_float; unaryfunc nb_oct; unaryfunc nb_hex; - /* Added in release 2.0 */ + binaryfunc nb_inplace_add; binaryfunc nb_inplace_subtract; binaryfunc nb_inplace_multiply; @@ -185,13 +185,11 @@ binaryfunc nb_inplace_xor; binaryfunc nb_inplace_or; - /* Added in release 2.2 */ binaryfunc nb_floor_divide; binaryfunc nb_true_divide; binaryfunc nb_inplace_floor_divide; binaryfunc nb_inplace_true_divide; - /* Added in release 2.5 */ lenfunc nb_index; } PyNumberMethods; @@ -204,7 +202,7 @@ ssizeobjargproc sq_ass_item; ssizessizeobjargproc sq_ass_slice; objobjproc sq_contains; - /* Added in release 2.0 */ + binaryfunc sq_inplace_concat; ssizeargfunc sq_inplace_repeat; } PySequenceMethods; @@ -292,7 +290,6 @@ /* weak reference enabler */ Py_ssize_t tp_weaklistoffset; - /* Added in release 2.2 */ /* Iterators */ getiterfunc tp_iter; iternextfunc tp_iternext; Modified: python/branches/p3yk/Include/structmember.h ============================================================================== --- python/branches/p3yk/Include/structmember.h (original) +++ python/branches/p3yk/Include/structmember.h Thu Aug 17 07:42:55 2006 @@ -67,9 +67,11 @@ converting to None. */ #ifdef HAVE_LONG_LONG #define T_LONGLONG 17 -#define T_ULONGLONG 18 +#define T_ULONGLONG 18 #endif /* HAVE_LONG_LONG */ +#define T_NONE 19 /* Value is always None */ + /* Flags */ #define READONLY 1 #define RO READONLY /* Shorthand */ Modified: python/branches/p3yk/Modules/_sre.c ============================================================================== --- python/branches/p3yk/Modules/_sre.c (original) +++ python/branches/p3yk/Modules/_sre.c Thu Aug 17 07:42:55 2006 @@ -3363,19 +3363,19 @@ {NULL, NULL} }; -#if PY_VERSION_HEX < 0x02030000 -DL_EXPORT(void) init_sre(void) -#else PyMODINIT_FUNC init_sre(void) -#endif { PyObject* m; PyObject* d; PyObject* x; - /* Patch object types */ - Pattern_Type.ob_type = Match_Type.ob_type = - Scanner_Type.ob_type = &PyType_Type; + /* Initialize object types */ + if (PyType_Ready(&Pattern_Type) < 0) + return; + if (PyType_Ready(&Match_Type) < 0) + return; + if (PyType_Ready(&Scanner_Type) < 0) + return; m = Py_InitModule("_" SRE_MODULE, _functions); if (m == NULL) Modified: python/branches/p3yk/Modules/arraymodule.c ============================================================================== --- python/branches/p3yk/Modules/arraymodule.c (original) +++ python/branches/p3yk/Modules/arraymodule.c Thu Aug 17 07:42:55 2006 @@ -2112,7 +2112,8 @@ { PyObject *m; - Arraytype.ob_type = &PyType_Type; + if (PyType_Ready(&Arraytype) < 0) + return; PyArrayIter_Type.ob_type = &PyType_Type; m = Py_InitModule3("array", a_methods, module_doc); if (m == NULL) Modified: python/branches/p3yk/Modules/cPickle.c ============================================================================== --- python/branches/p3yk/Modules/cPickle.c (original) +++ python/branches/p3yk/Modules/cPickle.c Thu Aug 17 07:42:55 2006 @@ -1786,148 +1786,6 @@ } -static int -save_inst(Picklerobject *self, PyObject *args) -{ - PyObject *class = 0, *module = 0, *name = 0, *state = 0, - *getinitargs_func = 0, *getstate_func = 0, *class_args = 0; - char *module_str, *name_str; - int module_size, name_size, res = -1; - - static char inst = INST, obj = OBJ, build = BUILD; - - if (self->fast && !fast_save_enter(self, args)) - goto finally; - - if (self->write_func(self, &MARKv, 1) < 0) - goto finally; - - if (!( class = PyObject_GetAttr(args, __class___str))) - goto finally; - - if (self->bin) { - if (save(self, class, 0) < 0) - goto finally; - } - - if ((getinitargs_func = PyObject_GetAttr(args, __getinitargs___str))) { - PyObject *element = 0; - int i, len; - - if (!( class_args = - PyObject_Call(getinitargs_func, empty_tuple, NULL))) - goto finally; - - if ((len = PyObject_Size(class_args)) < 0) - goto finally; - - for (i = 0; i < len; i++) { - if (!( element = PySequence_GetItem(class_args, i))) - goto finally; - - if (save(self, element, 0) < 0) { - Py_DECREF(element); - goto finally; - } - - Py_DECREF(element); - } - } - else { - if (PyErr_ExceptionMatches(PyExc_AttributeError)) - PyErr_Clear(); - else - goto finally; - } - - if (!self->bin) { - if (!( name = ((PyClassObject *)class)->cl_name )) { - PyErr_SetString(PicklingError, "class has no name"); - goto finally; - } - - if (!( module = whichmodule(class, name))) - goto finally; - - - if ((module_size = PyString_Size(module)) < 0 || - (name_size = PyString_Size(name)) < 0) - goto finally; - - module_str = PyString_AS_STRING((PyStringObject *)module); - name_str = PyString_AS_STRING((PyStringObject *)name); - - if (self->write_func(self, &inst, 1) < 0) - goto finally; - - if (self->write_func(self, module_str, module_size) < 0) - goto finally; - - if (self->write_func(self, "\n", 1) < 0) - goto finally; - - if (self->write_func(self, name_str, name_size) < 0) - goto finally; - - if (self->write_func(self, "\n", 1) < 0) - goto finally; - } - else if (self->write_func(self, &obj, 1) < 0) { - goto finally; - } - - if ((getstate_func = PyObject_GetAttr(args, __getstate___str))) { - state = PyObject_Call(getstate_func, empty_tuple, NULL); - if (!state) - goto finally; - } - else { - if (PyErr_ExceptionMatches(PyExc_AttributeError)) - PyErr_Clear(); - else - goto finally; - - if (!( state = PyObject_GetAttr(args, __dict___str))) { - if (PyErr_ExceptionMatches(PyExc_AttributeError)) - PyErr_Clear(); - else - goto finally; - res = 0; - goto finally; - } - } - - if (!PyDict_Check(state)) { - if (put2(self, args) < 0) - goto finally; - } - else { - if (put(self, args) < 0) - goto finally; - } - - if (save(self, state, 0) < 0) - goto finally; - - if (self->write_func(self, &build, 1) < 0) - goto finally; - - res = 0; - - finally: - if (self->fast && !fast_save_leave(self, args)) - res = -1; - - Py_XDECREF(module); - Py_XDECREF(class); - Py_XDECREF(state); - Py_XDECREF(getinitargs_func); - Py_XDECREF(getstate_func); - Py_XDECREF(class_args); - - return res; -} - static int save_global(Picklerobject *self, PyObject *args, PyObject *name) @@ -2420,20 +2278,6 @@ } break; - case 'i': - if (type == &PyInstance_Type) { - res = save_inst(self, args); - goto finally; - } - break; - - case 'c': - if (type == &PyClass_Type) { - res = save_global(self, args, NULL); - goto finally; - } - break; - case 'f': if (type == &PyFunction_Type) { res = save_global(self, args, NULL); @@ -3594,57 +3438,6 @@ return 0; } -static PyObject * -Instance_New(PyObject *cls, PyObject *args) -{ - PyObject *r = 0; - - if (PyClass_Check(cls)) { - int l; - - if ((l=PyObject_Size(args)) < 0) goto err; - if (!( l )) { - PyObject *__getinitargs__; - - __getinitargs__ = PyObject_GetAttr(cls, - __getinitargs___str); - if (!__getinitargs__) { - /* We have a class with no __getinitargs__, - so bypass usual construction */ - PyObject *inst; - - PyErr_Clear(); - if (!( inst=PyInstance_NewRaw(cls, NULL))) - goto err; - return inst; - } - Py_DECREF(__getinitargs__); - } - - if ((r=PyInstance_New(cls, args, NULL))) return r; - else goto err; - } - - if ((r=PyObject_CallObject(cls, args))) return r; - - err: - { - PyObject *tp, *v, *tb, *tmp_value; - - PyErr_Fetch(&tp, &v, &tb); - tmp_value = v; - /* NULL occurs when there was a KeyboardInterrupt */ - if (tmp_value == NULL) - tmp_value = Py_None; - if ((r = PyTuple_Pack(3, tmp_value, cls, args))) { - Py_XDECREF(v); - v=r; - } - PyErr_Restore(tp,v,tb); - } - return NULL; -} - static int load_obj(Unpicklerobject *self) @@ -3655,10 +3448,6 @@ if ((i = marker(self)) < 0) return -1; if (!( tup=Pdata_popTuple(self->stack, i+1))) return -1; PDATA_POP(self->stack, class); - if (class) { - obj = Instance_New(class, tup); - Py_DECREF(class); - } Py_DECREF(tup); if (! obj) return -1; @@ -3694,8 +3483,8 @@ if (! class) return -1; if ((tup=Pdata_popTuple(self->stack, i))) { - obj = Instance_New(class, tup); - Py_DECREF(tup); + PyErr_SetString(UnpicklingError, "it's dead, Jim"); + return -1; } Py_DECREF(class); @@ -4388,10 +4177,6 @@ PDATA_POP(self->stack, arg_tup); if (! arg_tup) return -1; PDATA_POP(self->stack, callable); - if (callable) { - ob = Instance_New(callable, arg_tup); - Py_DECREF(callable); - } Py_DECREF(arg_tup); if (! ob) return -1; Modified: python/branches/p3yk/Modules/gcmodule.c ============================================================================== --- python/branches/p3yk/Modules/gcmodule.c (original) +++ python/branches/p3yk/Modules/gcmodule.c Thu Aug 17 07:42:55 2006 @@ -66,12 +66,10 @@ #define DEBUG_STATS (1<<0) /* print collection statistics */ #define DEBUG_COLLECTABLE (1<<1) /* print collectable objects */ #define DEBUG_UNCOLLECTABLE (1<<2) /* print uncollectable objects */ -#define DEBUG_INSTANCES (1<<3) /* print instances */ #define DEBUG_OBJECTS (1<<4) /* print other objects */ #define DEBUG_SAVEALL (1<<5) /* save all garbage in gc.garbage */ #define DEBUG_LEAK DEBUG_COLLECTABLE | \ DEBUG_UNCOLLECTABLE | \ - DEBUG_INSTANCES | \ DEBUG_OBJECTS | \ DEBUG_SAVEALL static int debug; @@ -410,13 +408,7 @@ static int has_finalizer(PyObject *op) { - if (PyInstance_Check(op)) { - assert(delstr != NULL); - return _PyInstance_Lookup(op, delstr) != NULL; - } - else if (PyType_HasFeature(op->ob_type, Py_TPFLAGS_HEAPTYPE)) - return op->ob_type->tp_del != NULL; - else if (PyGen_CheckExact(op)) + if (PyGen_CheckExact(op)) return PyGen_NeedsFinalizing((PyGenObject *)op); else return 0; @@ -633,26 +625,9 @@ } static void -debug_instance(char *msg, PyInstanceObject *inst) -{ - char *cname; - /* simple version of instance_repr */ - PyObject *classname = inst->in_class->cl_name; - if (classname != NULL && PyString_Check(classname)) - cname = PyString_AsString(classname); - else - cname = "?"; - PySys_WriteStderr("gc: %.100s <%.100s instance at %p>\n", - msg, cname, inst); -} - -static void debug_cycle(char *msg, PyObject *op) { - if ((debug & DEBUG_INSTANCES) && PyInstance_Check(op)) { - debug_instance(msg, (PyInstanceObject *)op); - } - else if (debug & DEBUG_OBJECTS) { + if (debug & DEBUG_OBJECTS) { PySys_WriteStderr("gc: %.100s <%.100s %p>\n", msg, op->ob_type->tp_name, op); } @@ -983,7 +958,6 @@ " DEBUG_STATS - Print statistics during collection.\n" " DEBUG_COLLECTABLE - Print collectable objects found.\n" " DEBUG_UNCOLLECTABLE - Print unreachable but uncollectable objects found.\n" -" DEBUG_INSTANCES - Print instance objects.\n" " DEBUG_OBJECTS - Print objects other than instances.\n" " DEBUG_SAVEALL - Save objects to gc.garbage rather than freeing them.\n" " DEBUG_LEAK - Debug leaking programs (everything but STATS).\n"); @@ -1244,7 +1218,6 @@ ADD_INT(DEBUG_STATS); ADD_INT(DEBUG_COLLECTABLE); ADD_INT(DEBUG_UNCOLLECTABLE); - ADD_INT(DEBUG_INSTANCES); ADD_INT(DEBUG_OBJECTS); ADD_INT(DEBUG_SAVEALL); ADD_INT(DEBUG_LEAK); Modified: python/branches/p3yk/Objects/abstract.c ============================================================================== --- python/branches/p3yk/Objects/abstract.c (original) +++ python/branches/p3yk/Objects/abstract.c Thu Aug 17 07:42:55 2006 @@ -1000,8 +1000,6 @@ int PySequence_Check(PyObject *s) { - if (s && PyInstance_Check(s)) - return PyObject_HasAttrString(s, "__getitem__"); return s != NULL && s->ob_type->tp_as_sequence && s->ob_type->tp_as_sequence->sq_item != NULL; } @@ -1586,9 +1584,6 @@ int PyMapping_Check(PyObject *o) { - if (o && PyInstance_Check(o)) - return PyObject_HasAttrString(o, "__getitem__"); - return o && o->ob_type->tp_as_mapping && o->ob_type->tp_as_mapping->mp_subscript && !(o->ob_type->tp_as_sequence && Modified: python/branches/p3yk/Objects/bytesobject.c ============================================================================== --- python/branches/p3yk/Objects/bytesobject.c (original) +++ python/branches/p3yk/Objects/bytesobject.c Thu Aug 17 07:42:55 2006 @@ -379,13 +379,6 @@ return 0; } -static long -bytes_nohash(PyObject *self) -{ - PyErr_SetString(PyExc_TypeError, "bytes objects are unhashable"); - return -1; -} - static int bytes_init(PyBytesObject *self, PyObject *args, PyObject *kwds) { @@ -833,7 +826,7 @@ 0, /* tp_as_number */ &bytes_as_sequence, /* tp_as_sequence */ &bytes_as_mapping, /* tp_as_mapping */ - bytes_nohash, /* tp_hash */ + 0, /* tp_hash */ 0, /* tp_call */ (reprfunc)bytes_str, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ Modified: python/branches/p3yk/Objects/classobject.c ============================================================================== --- python/branches/p3yk/Objects/classobject.c (original) +++ python/branches/p3yk/Objects/classobject.c Thu Aug 17 07:42:55 2006 @@ -1,5 +1,4 @@ - -/* Class object implementation */ +/* Class object implementation (dead now except for methods) */ #include "Python.h" #include "structmember.h" @@ -7,114 +6,6 @@ #define TP_DESCR_GET(t) ((t)->tp_descr_get) -/* Forward */ -static PyObject *class_lookup(PyClassObject *, PyObject *, - PyClassObject **); -static PyObject *instance_getattr1(PyInstanceObject *, PyObject *); -static PyObject *instance_getattr2(PyInstanceObject *, PyObject *); - -static PyObject *getattrstr, *setattrstr, *delattrstr; - - -PyObject * -PyClass_New(PyObject *bases, PyObject *dict, PyObject *name) - /* bases is NULL or tuple of classobjects! */ -{ - PyClassObject *op, *dummy; - static PyObject *docstr, *modstr, *namestr; - if (docstr == NULL) { - docstr= PyString_InternFromString("__doc__"); - if (docstr == NULL) - return NULL; - } - if (modstr == NULL) { - modstr= PyString_InternFromString("__module__"); - if (modstr == NULL) - return NULL; - } - if (namestr == NULL) { - namestr= PyString_InternFromString("__name__"); - if (namestr == NULL) - return NULL; - } - if (name == NULL || !PyString_Check(name)) { - PyErr_SetString(PyExc_TypeError, - "PyClass_New: name must be a string"); - return NULL; - } - if (dict == NULL || !PyDict_Check(dict)) { - PyErr_SetString(PyExc_TypeError, - "PyClass_New: dict must be a dictionary"); - return NULL; - } - if (PyDict_GetItem(dict, docstr) == NULL) { - if (PyDict_SetItem(dict, docstr, Py_None) < 0) - return NULL; - } - if (PyDict_GetItem(dict, modstr) == NULL) { - PyObject *globals = PyEval_GetGlobals(); - if (globals != NULL) { - PyObject *modname = PyDict_GetItem(globals, namestr); - if (modname != NULL) { - if (PyDict_SetItem(dict, modstr, modname) < 0) - return NULL; - } - } - } - if (bases == NULL) { - bases = PyTuple_New(0); - if (bases == NULL) - return NULL; - } - else { - Py_ssize_t i, n; - PyObject *base; - if (!PyTuple_Check(bases)) { - PyErr_SetString(PyExc_TypeError, - "PyClass_New: bases must be a tuple"); - return NULL; - } - n = PyTuple_Size(bases); - for (i = 0; i < n; i++) { - base = PyTuple_GET_ITEM(bases, i); - if (!PyClass_Check(base)) { - if (PyCallable_Check( - (PyObject *) base->ob_type)) - return PyObject_CallFunctionObjArgs( - (PyObject *) base->ob_type, - name, bases, dict, NULL); - PyErr_SetString(PyExc_TypeError, - "PyClass_New: base must be a class"); - return NULL; - } - } - Py_INCREF(bases); - } - op = PyObject_GC_New(PyClassObject, &PyClass_Type); - if (op == NULL) { - Py_DECREF(bases); - return NULL; - } - op->cl_bases = bases; - Py_INCREF(dict); - op->cl_dict = dict; - Py_XINCREF(name); - op->cl_name = name; - if (getattrstr == NULL) { - getattrstr = PyString_InternFromString("__getattr__"); - setattrstr = PyString_InternFromString("__setattr__"); - delattrstr = PyString_InternFromString("__delattr__"); - } - op->cl_getattr = class_lookup(op, getattrstr, &dummy); - op->cl_setattr = class_lookup(op, setattrstr, &dummy); - op->cl_delattr = class_lookup(op, delattrstr, &dummy); - Py_XINCREF(op->cl_getattr); - Py_XINCREF(op->cl_setattr); - Py_XINCREF(op->cl_delattr); - _PyObject_GC_TRACK(op); - return (PyObject *) op; -} - PyObject * PyMethod_Function(PyObject *im) { @@ -145,1929 +36,8 @@ return ((PyMethodObject *)im)->im_class; } -PyDoc_STRVAR(class_doc, -"classobj(name, bases, dict)\n\ -\n\ -Create a class object. The name must be a string; the second argument\n\ -a tuple of classes, and the third a dictionary."); - -static PyObject * -class_new(PyTypeObject *type, PyObject *args, PyObject *kwds) -{ - PyObject *name, *bases, *dict; - static char *kwlist[] = {"name", "bases", "dict", 0}; - - if (!PyArg_ParseTupleAndKeywords(args, kwds, "SOO", kwlist, - &name, &bases, &dict)) - return NULL; - return PyClass_New(bases, dict, name); -} - -/* Class methods */ - -static void -class_dealloc(PyClassObject *op) -{ - _PyObject_GC_UNTRACK(op); - Py_DECREF(op->cl_bases); - Py_DECREF(op->cl_dict); - Py_XDECREF(op->cl_name); - Py_XDECREF(op->cl_getattr); - Py_XDECREF(op->cl_setattr); - Py_XDECREF(op->cl_delattr); - PyObject_GC_Del(op); -} - -static PyObject * -class_lookup(PyClassObject *cp, PyObject *name, PyClassObject **pclass) -{ - Py_ssize_t i, n; - PyObject *value = PyDict_GetItem(cp->cl_dict, name); - if (value != NULL) { - *pclass = cp; - return value; - } - n = PyTuple_Size(cp->cl_bases); - for (i = 0; i < n; i++) { - /* XXX What if one of the bases is not a class? */ - PyObject *v = class_lookup( - (PyClassObject *) - PyTuple_GetItem(cp->cl_bases, i), name, pclass); - if (v != NULL) - return v; - } - return NULL; -} - -static PyObject * -class_getattr(register PyClassObject *op, PyObject *name) -{ - register PyObject *v; - register char *sname = PyString_AsString(name); - PyClassObject *klass; - descrgetfunc f; - - if (sname[0] == '_' && sname[1] == '_') { - if (strcmp(sname, "__dict__") == 0) { - if (PyEval_GetRestricted()) { - PyErr_SetString(PyExc_RuntimeError, - "class.__dict__ not accessible in restricted mode"); - return NULL; - } - Py_INCREF(op->cl_dict); - return op->cl_dict; - } - if (strcmp(sname, "__bases__") == 0) { - Py_INCREF(op->cl_bases); - return op->cl_bases; - } - if (strcmp(sname, "__name__") == 0) { - if (op->cl_name == NULL) - v = Py_None; - else - v = op->cl_name; - Py_INCREF(v); - return v; - } - } - v = class_lookup(op, name, &klass); - if (v == NULL) { - PyErr_Format(PyExc_AttributeError, - "class %.50s has no attribute '%.400s'", - PyString_AS_STRING(op->cl_name), sname); - return NULL; - } - f = TP_DESCR_GET(v->ob_type); - if (f == NULL) - Py_INCREF(v); - else - v = f(v, (PyObject *)NULL, (PyObject *)op); - return v; -} - -static void -set_slot(PyObject **slot, PyObject *v) -{ - PyObject *temp = *slot; - Py_XINCREF(v); - *slot = v; - Py_XDECREF(temp); -} - -static void -set_attr_slots(PyClassObject *c) -{ - PyClassObject *dummy; - - set_slot(&c->cl_getattr, class_lookup(c, getattrstr, &dummy)); - set_slot(&c->cl_setattr, class_lookup(c, setattrstr, &dummy)); - set_slot(&c->cl_delattr, class_lookup(c, delattrstr, &dummy)); -} - -static char * -set_dict(PyClassObject *c, PyObject *v) -{ - if (v == NULL || !PyDict_Check(v)) - return "__dict__ must be a dictionary object"; - set_slot(&c->cl_dict, v); - set_attr_slots(c); - return ""; -} - -static char * -set_bases(PyClassObject *c, PyObject *v) -{ - Py_ssize_t i, n; - - if (v == NULL || !PyTuple_Check(v)) - return "__bases__ must be a tuple object"; - n = PyTuple_Size(v); - for (i = 0; i < n; i++) { - PyObject *x = PyTuple_GET_ITEM(v, i); - if (!PyClass_Check(x)) - return "__bases__ items must be classes"; - if (PyClass_IsSubclass(x, (PyObject *)c)) - return "a __bases__ item causes an inheritance cycle"; - } - set_slot(&c->cl_bases, v); - set_attr_slots(c); - return ""; -} - -static char * -set_name(PyClassObject *c, PyObject *v) -{ - if (v == NULL || !PyString_Check(v)) - return "__name__ must be a string object"; - if (strlen(PyString_AS_STRING(v)) != (size_t)PyString_GET_SIZE(v)) - return "__name__ must not contain null bytes"; - set_slot(&c->cl_name, v); - return ""; -} - -static int -class_setattr(PyClassObject *op, PyObject *name, PyObject *v) -{ - char *sname; - if (PyEval_GetRestricted()) { - PyErr_SetString(PyExc_RuntimeError, - "classes are read-only in restricted mode"); - return -1; - } - sname = PyString_AsString(name); - if (sname[0] == '_' && sname[1] == '_') { - Py_ssize_t n = PyString_Size(name); - if (sname[n-1] == '_' && sname[n-2] == '_') { - char *err = NULL; - if (strcmp(sname, "__dict__") == 0) - err = set_dict(op, v); - else if (strcmp(sname, "__bases__") == 0) - err = set_bases(op, v); - else if (strcmp(sname, "__name__") == 0) - err = set_name(op, v); - else if (strcmp(sname, "__getattr__") == 0) - set_slot(&op->cl_getattr, v); - else if (strcmp(sname, "__setattr__") == 0) - set_slot(&op->cl_setattr, v); - else if (strcmp(sname, "__delattr__") == 0) - set_slot(&op->cl_delattr, v); - /* For the last three, we fall through to update the - dictionary as well. */ - if (err != NULL) { - if (*err == '\0') - return 0; - PyErr_SetString(PyExc_TypeError, err); - return -1; - } - } - } - if (v == NULL) { - int rv = PyDict_DelItem(op->cl_dict, name); - if (rv < 0) - PyErr_Format(PyExc_AttributeError, - "class %.50s has no attribute '%.400s'", - PyString_AS_STRING(op->cl_name), sname); - return rv; - } - else - return PyDict_SetItem(op->cl_dict, name, v); -} - -static PyObject * -class_repr(PyClassObject *op) -{ - PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__"); - char *name; - if (op->cl_name == NULL || !PyString_Check(op->cl_name)) - name = "?"; - else - name = PyString_AsString(op->cl_name); - if (mod == NULL || !PyString_Check(mod)) - return PyString_FromFormat("", name, op); - else - return PyString_FromFormat("", - PyString_AsString(mod), - name, op); -} - -static PyObject * -class_str(PyClassObject *op) -{ - PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__"); - PyObject *name = op->cl_name; - PyObject *res; - Py_ssize_t m, n; - - if (name == NULL || !PyString_Check(name)) - return class_repr(op); - if (mod == NULL || !PyString_Check(mod)) { - Py_INCREF(name); - return name; - } - m = PyString_GET_SIZE(mod); - n = PyString_GET_SIZE(name); - res = PyString_FromStringAndSize((char *)NULL, m+1+n); - if (res != NULL) { - char *s = PyString_AS_STRING(res); - memcpy(s, PyString_AS_STRING(mod), m); - s += m; - *s++ = '.'; - memcpy(s, PyString_AS_STRING(name), n); - } - return res; -} - -static int -class_traverse(PyClassObject *o, visitproc visit, void *arg) -{ - Py_VISIT(o->cl_bases); - Py_VISIT(o->cl_dict); - Py_VISIT(o->cl_name); - Py_VISIT(o->cl_getattr); - Py_VISIT(o->cl_setattr); - Py_VISIT(o->cl_delattr); - return 0; -} - -PyTypeObject PyClass_Type = { - PyObject_HEAD_INIT(&PyType_Type) - 0, - "classobj", - sizeof(PyClassObject), - 0, - (destructor)class_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - 0, /* tp_compare */ - (reprfunc)class_repr, /* tp_repr */ - 0, /* tp_as_number */ - 0, /* tp_as_sequence */ - 0, /* tp_as_mapping */ - 0, /* tp_hash */ - PyInstance_New, /* tp_call */ - (reprfunc)class_str, /* tp_str */ - (getattrofunc)class_getattr, /* tp_getattro */ - (setattrofunc)class_setattr, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ - class_doc, /* tp_doc */ - (traverseproc)class_traverse, /* tp_traverse */ - 0, /* tp_clear */ - 0, /* tp_richcompare */ - 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ - 0, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - class_new, /* tp_new */ -}; - -int -PyClass_IsSubclass(PyObject *klass, PyObject *base) -{ - Py_ssize_t i, n; - PyClassObject *cp; - if (klass == base) - return 1; - if (PyTuple_Check(base)) { - n = PyTuple_GET_SIZE(base); - for (i = 0; i < n; i++) { - if (PyClass_IsSubclass(klass, PyTuple_GET_ITEM(base, i))) - return 1; - } - return 0; - } - if (klass == NULL || !PyClass_Check(klass)) - return 0; - cp = (PyClassObject *)klass; - n = PyTuple_Size(cp->cl_bases); - for (i = 0; i < n; i++) { - if (PyClass_IsSubclass(PyTuple_GetItem(cp->cl_bases, i), base)) - return 1; - } - return 0; -} - - -/* Instance objects */ - -PyObject * -PyInstance_NewRaw(PyObject *klass, PyObject *dict) -{ - PyInstanceObject *inst; - - if (!PyClass_Check(klass)) { - PyErr_BadInternalCall(); - return NULL; - } - if (dict == NULL) { - dict = PyDict_New(); - if (dict == NULL) - return NULL; - } - else { - if (!PyDict_Check(dict)) { - PyErr_BadInternalCall(); - return NULL; - } - Py_INCREF(dict); - } - inst = PyObject_GC_New(PyInstanceObject, &PyInstance_Type); - if (inst == NULL) { - Py_DECREF(dict); - return NULL; - } - inst->in_weakreflist = NULL; - Py_INCREF(klass); - inst->in_class = (PyClassObject *)klass; - inst->in_dict = dict; - _PyObject_GC_TRACK(inst); - return (PyObject *)inst; -} - -PyObject * -PyInstance_New(PyObject *klass, PyObject *arg, PyObject *kw) -{ - register PyInstanceObject *inst; - PyObject *init; - static PyObject *initstr; - - inst = (PyInstanceObject *) PyInstance_NewRaw(klass, NULL); - if (inst == NULL) - return NULL; - if (initstr == NULL) - initstr = PyString_InternFromString("__init__"); - init = instance_getattr2(inst, initstr); - if (init == NULL) { - if (PyErr_Occurred()) { - Py_DECREF(inst); - return NULL; - } - if ((arg != NULL && (!PyTuple_Check(arg) || - PyTuple_Size(arg) != 0)) - || (kw != NULL && (!PyDict_Check(kw) || - PyDict_Size(kw) != 0))) { - PyErr_SetString(PyExc_TypeError, - "this constructor takes no arguments"); - Py_DECREF(inst); - inst = NULL; - } - } - else { - PyObject *res = PyEval_CallObjectWithKeywords(init, arg, kw); - Py_DECREF(init); - if (res == NULL) { - Py_DECREF(inst); - inst = NULL; - } - else { - if (res != Py_None) { - PyErr_SetString(PyExc_TypeError, - "__init__() should return None"); - Py_DECREF(inst); - inst = NULL; - } - Py_DECREF(res); - } - } - return (PyObject *)inst; -} - -/* Instance methods */ - -PyDoc_STRVAR(instance_doc, -"instance(class[, dict])\n\ -\n\ -Create an instance without calling its __init__() method.\n\ -The class must be a classic class.\n\ -If present, dict must be a dictionary or None."); - -static PyObject * -instance_new(PyTypeObject* type, PyObject* args, PyObject *kw) -{ - PyObject *klass; - PyObject *dict = Py_None; - - if (!PyArg_ParseTuple(args, "O!|O:instance", - &PyClass_Type, &klass, &dict)) - return NULL; - - if (dict == Py_None) - dict = NULL; - else if (!PyDict_Check(dict)) { - PyErr_SetString(PyExc_TypeError, - "instance() second arg must be dictionary or None"); - return NULL; - } - return PyInstance_NewRaw(klass, dict); -} - - -static void -instance_dealloc(register PyInstanceObject *inst) -{ - PyObject *error_type, *error_value, *error_traceback; - PyObject *del; - static PyObject *delstr; - - _PyObject_GC_UNTRACK(inst); - if (inst->in_weakreflist != NULL) - PyObject_ClearWeakRefs((PyObject *) inst); - - /* Temporarily resurrect the object. */ - assert(inst->ob_type == &PyInstance_Type); - assert(inst->ob_refcnt == 0); - inst->ob_refcnt = 1; - - /* Save the current exception, if any. */ - PyErr_Fetch(&error_type, &error_value, &error_traceback); - /* Execute __del__ method, if any. */ - if (delstr == NULL) - delstr = PyString_InternFromString("__del__"); - if ((del = instance_getattr2(inst, delstr)) != NULL) { - PyObject *res = PyEval_CallObject(del, (PyObject *)NULL); - if (res == NULL) - PyErr_WriteUnraisable(del); - else - Py_DECREF(res); - Py_DECREF(del); - } - /* Restore the saved exception. */ - PyErr_Restore(error_type, error_value, error_traceback); - - /* Undo the temporary resurrection; can't use DECREF here, it would - * cause a recursive call. - */ - assert(inst->ob_refcnt > 0); - if (--inst->ob_refcnt == 0) { - Py_DECREF(inst->in_class); - Py_XDECREF(inst->in_dict); - PyObject_GC_Del(inst); - } - else { - Py_ssize_t refcnt = inst->ob_refcnt; - /* __del__ resurrected it! Make it look like the original - * Py_DECREF never happened. - */ - _Py_NewReference((PyObject *)inst); - inst->ob_refcnt = refcnt; - _PyObject_GC_TRACK(inst); - /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so - * we need to undo that. */ - _Py_DEC_REFTOTAL; - /* If Py_TRACE_REFS, _Py_NewReference re-added self to the - * object chain, so no more to do there. - * If COUNT_ALLOCS, the original decref bumped tp_frees, and - * _Py_NewReference bumped tp_allocs: both of those need to be - * undone. - */ -#ifdef COUNT_ALLOCS - --inst->ob_type->tp_frees; - --inst->ob_type->tp_allocs; -#endif - } -} - -static PyObject * -instance_getattr1(register PyInstanceObject *inst, PyObject *name) -{ - register PyObject *v; - register char *sname = PyString_AsString(name); - if (sname[0] == '_' && sname[1] == '_') { - if (strcmp(sname, "__dict__") == 0) { - if (PyEval_GetRestricted()) { - PyErr_SetString(PyExc_RuntimeError, - "instance.__dict__ not accessible in restricted mode"); - return NULL; - } - Py_INCREF(inst->in_dict); - return inst->in_dict; - } - if (strcmp(sname, "__class__") == 0) { - Py_INCREF(inst->in_class); - return (PyObject *)inst->in_class; - } - } - v = instance_getattr2(inst, name); - if (v == NULL && !PyErr_Occurred()) { - PyErr_Format(PyExc_AttributeError, - "%.50s instance has no attribute '%.400s'", - PyString_AS_STRING(inst->in_class->cl_name), sname); - } - return v; -} - -static PyObject * -instance_getattr2(register PyInstanceObject *inst, PyObject *name) -{ - register PyObject *v; - PyClassObject *klass; - descrgetfunc f; - - v = PyDict_GetItem(inst->in_dict, name); - if (v != NULL) { - Py_INCREF(v); - return v; - } - v = class_lookup(inst->in_class, name, &klass); - if (v != NULL) { - Py_INCREF(v); - f = TP_DESCR_GET(v->ob_type); - if (f != NULL) { - PyObject *w = f(v, (PyObject *)inst, - (PyObject *)(inst->in_class)); - Py_DECREF(v); - v = w; - } - } - return v; -} - -static PyObject * -instance_getattr(register PyInstanceObject *inst, PyObject *name) -{ - register PyObject *func, *res; - res = instance_getattr1(inst, name); - if (res == NULL && (func = inst->in_class->cl_getattr) != NULL) { - PyObject *args; - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return NULL; - PyErr_Clear(); - args = PyTuple_Pack(2, inst, name); - if (args == NULL) - return NULL; - res = PyEval_CallObject(func, args); - Py_DECREF(args); - } - return res; -} - -/* See classobject.h comments: this only does dict lookups, and is always - * safe to call. - */ -PyObject * -_PyInstance_Lookup(PyObject *pinst, PyObject *name) -{ - PyObject *v; - PyClassObject *klass; - PyInstanceObject *inst; /* pinst cast to the right type */ - - assert(PyInstance_Check(pinst)); - inst = (PyInstanceObject *)pinst; - - assert(PyString_Check(name)); - - v = PyDict_GetItem(inst->in_dict, name); - if (v == NULL) - v = class_lookup(inst->in_class, name, &klass); - return v; -} - -static int -instance_setattr1(PyInstanceObject *inst, PyObject *name, PyObject *v) -{ - if (v == NULL) { - int rv = PyDict_DelItem(inst->in_dict, name); - if (rv < 0) - PyErr_Format(PyExc_AttributeError, - "%.50s instance has no attribute '%.400s'", - PyString_AS_STRING(inst->in_class->cl_name), - PyString_AS_STRING(name)); - return rv; - } - else - return PyDict_SetItem(inst->in_dict, name, v); -} - -static int -instance_setattr(PyInstanceObject *inst, PyObject *name, PyObject *v) -{ - PyObject *func, *args, *res, *tmp; - char *sname = PyString_AsString(name); - if (sname[0] == '_' && sname[1] == '_') { - Py_ssize_t n = PyString_Size(name); - if (sname[n-1] == '_' && sname[n-2] == '_') { - if (strcmp(sname, "__dict__") == 0) { - if (PyEval_GetRestricted()) { - PyErr_SetString(PyExc_RuntimeError, - "__dict__ not accessible in restricted mode"); - return -1; - } - if (v == NULL || !PyDict_Check(v)) { - PyErr_SetString(PyExc_TypeError, - "__dict__ must be set to a dictionary"); - return -1; - } - tmp = inst->in_dict; - Py_INCREF(v); - inst->in_dict = v; - Py_DECREF(tmp); - return 0; - } - if (strcmp(sname, "__class__") == 0) { - if (PyEval_GetRestricted()) { - PyErr_SetString(PyExc_RuntimeError, - "__class__ not accessible in restricted mode"); - return -1; - } - if (v == NULL || !PyClass_Check(v)) { - PyErr_SetString(PyExc_TypeError, - "__class__ must be set to a class"); - return -1; - } - tmp = (PyObject *)(inst->in_class); - Py_INCREF(v); - inst->in_class = (PyClassObject *)v; - Py_DECREF(tmp); - return 0; - } - } - } - if (v == NULL) - func = inst->in_class->cl_delattr; - else - func = inst->in_class->cl_setattr; - if (func == NULL) - return instance_setattr1(inst, name, v); - if (v == NULL) - args = PyTuple_Pack(2, inst, name); - else - args = PyTuple_Pack(3, inst, name, v); - if (args == NULL) - return -1; - res = PyEval_CallObject(func, args); - Py_DECREF(args); - if (res == NULL) - return -1; - Py_DECREF(res); - return 0; -} - -static PyObject * -instance_repr(PyInstanceObject *inst) -{ - PyObject *func; - PyObject *res; - static PyObject *reprstr; - - if (reprstr == NULL) - reprstr = PyString_InternFromString("__repr__"); - func = instance_getattr(inst, reprstr); - if (func == NULL) { - PyObject *classname, *mod; - char *cname; - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return NULL; - PyErr_Clear(); - classname = inst->in_class->cl_name; - mod = PyDict_GetItemString(inst->in_class->cl_dict, - "__module__"); - if (classname != NULL && PyString_Check(classname)) - cname = PyString_AsString(classname); - else - cname = "?"; - if (mod == NULL || !PyString_Check(mod)) - return PyString_FromFormat("", - cname, inst); - else - return PyString_FromFormat("<%s.%s instance at %p>", - PyString_AsString(mod), - cname, inst); - } - res = PyEval_CallObject(func, (PyObject *)NULL); - Py_DECREF(func); - return res; -} - -static PyObject * -instance_str(PyInstanceObject *inst) -{ - PyObject *func; - PyObject *res; - static PyObject *strstr; - - if (strstr == NULL) - strstr = PyString_InternFromString("__str__"); - func = instance_getattr(inst, strstr); - if (func == NULL) { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return NULL; - PyErr_Clear(); - return instance_repr(inst); - } - res = PyEval_CallObject(func, (PyObject *)NULL); - Py_DECREF(func); - return res; -} - -static long -instance_hash(PyInstanceObject *inst) -{ - PyObject *func; - PyObject *res; - long outcome; - static PyObject *hashstr, *eqstr, *cmpstr; - - if (hashstr == NULL) - hashstr = PyString_InternFromString("__hash__"); - func = instance_getattr(inst, hashstr); - if (func == NULL) { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return -1; - PyErr_Clear(); - /* If there is no __eq__ and no __cmp__ method, we hash on the - address. If an __eq__ or __cmp__ method exists, there must - be a __hash__. */ - if (eqstr == NULL) - eqstr = PyString_InternFromString("__eq__"); - func = instance_getattr(inst, eqstr); - if (func == NULL) { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return -1; - PyErr_Clear(); - if (cmpstr == NULL) - cmpstr = PyString_InternFromString("__cmp__"); - func = instance_getattr(inst, cmpstr); - if (func == NULL) { - if (!PyErr_ExceptionMatches( - PyExc_AttributeError)) - return -1; - PyErr_Clear(); - return _Py_HashPointer(inst); - } - } - Py_XDECREF(func); - PyErr_SetString(PyExc_TypeError, "unhashable instance"); - return -1; - } - res = PyEval_CallObject(func, (PyObject *)NULL); - Py_DECREF(func); - if (res == NULL) - return -1; - if (PyInt_Check(res) || PyLong_Check(res)) - /* This already converts a -1 result to -2. */ - outcome = res->ob_type->tp_hash(res); - else { - PyErr_SetString(PyExc_TypeError, - "__hash__() should return an int"); - outcome = -1; - } - Py_DECREF(res); - return outcome; -} - -static int -instance_traverse(PyInstanceObject *o, visitproc visit, void *arg) -{ - Py_VISIT(o->in_class); - Py_VISIT(o->in_dict); - return 0; -} - -static PyObject *getitemstr, *setitemstr, *delitemstr, *lenstr; -static PyObject *iterstr, *nextstr; - -static Py_ssize_t -instance_length(PyInstanceObject *inst) -{ - PyObject *func; - PyObject *res; - Py_ssize_t outcome; - - if (lenstr == NULL) - lenstr = PyString_InternFromString("__len__"); - func = instance_getattr(inst, lenstr); - if (func == NULL) - return -1; - res = PyEval_CallObject(func, (PyObject *)NULL); - Py_DECREF(func); - if (res == NULL) - return -1; - if (PyInt_Check(res)) { - Py_ssize_t temp = PyInt_AsSsize_t(res); - if (temp == -1 && PyErr_Occurred()) { - Py_DECREF(res); - return -1; - } - outcome = (Py_ssize_t)temp; -#if SIZEOF_SIZE_T < SIZEOF_LONG - /* Overflow check -- range of PyInt is more than C int */ - if (outcome != temp) { - PyErr_SetString(PyExc_OverflowError, - "__len__() should return 0 <= outcome < 2**31"); - outcome = -1; - } - else -#endif - if (outcome < 0) - PyErr_SetString(PyExc_ValueError, - "__len__() should return >= 0"); - } - else { - PyErr_SetString(PyExc_TypeError, - "__len__() should return an int"); - outcome = -1; - } - Py_DECREF(res); - return outcome; -} - -static PyObject * -instance_subscript(PyInstanceObject *inst, PyObject *key) -{ - PyObject *func; - PyObject *arg; - PyObject *res; - - if (getitemstr == NULL) - getitemstr = PyString_InternFromString("__getitem__"); - func = instance_getattr(inst, getitemstr); - if (func == NULL) - return NULL; - arg = PyTuple_Pack(1, key); - if (arg == NULL) { - Py_DECREF(func); - return NULL; - } - res = PyEval_CallObject(func, arg); - Py_DECREF(func); - Py_DECREF(arg); - return res; -} - -static int -instance_ass_subscript(PyInstanceObject *inst, PyObject *key, PyObject *value) -{ - PyObject *func; - PyObject *arg; - PyObject *res; - - if (value == NULL) { - if (delitemstr == NULL) - delitemstr = PyString_InternFromString("__delitem__"); - func = instance_getattr(inst, delitemstr); - } - else { - if (setitemstr == NULL) - setitemstr = PyString_InternFromString("__setitem__"); - func = instance_getattr(inst, setitemstr); - } - if (func == NULL) - return -1; - if (value == NULL) - arg = PyTuple_Pack(1, key); - else - arg = PyTuple_Pack(2, key, value); - if (arg == NULL) { - Py_DECREF(func); - return -1; - } - res = PyEval_CallObject(func, arg); - Py_DECREF(func); - Py_DECREF(arg); - if (res == NULL) - return -1; - Py_DECREF(res); - return 0; -} - -static PyMappingMethods instance_as_mapping = { - (lenfunc)instance_length, /* mp_length */ - (binaryfunc)instance_subscript, /* mp_subscript */ - (objobjargproc)instance_ass_subscript, /* mp_ass_subscript */ -}; - -static PyObject * -instance_item(PyInstanceObject *inst, Py_ssize_t i) -{ - PyObject *func, *res; - - if (getitemstr == NULL) - getitemstr = PyString_InternFromString("__getitem__"); - func = instance_getattr(inst, getitemstr); - if (func == NULL) - return NULL; - res = PyObject_CallFunction(func, "n", i); - Py_DECREF(func); - return res; -} - -static PyObject * -instance_slice(PyInstanceObject *inst, Py_ssize_t i, Py_ssize_t j) -{ - PyObject *func, *arg, *res; - static PyObject *getslicestr; - - if (getslicestr == NULL) - getslicestr = PyString_InternFromString("__getslice__"); - func = instance_getattr(inst, getslicestr); - - if (func == NULL) { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return NULL; - PyErr_Clear(); - - if (getitemstr == NULL) - getitemstr = PyString_InternFromString("__getitem__"); - func = instance_getattr(inst, getitemstr); - if (func == NULL) - return NULL; - arg = Py_BuildValue("(N)", _PySlice_FromIndices(i, j)); - } else - arg = Py_BuildValue("(nn)", i, j); - - if (arg == NULL) { - Py_DECREF(func); - return NULL; - } - res = PyEval_CallObject(func, arg); - Py_DECREF(func); - Py_DECREF(arg); - return res; -} - -static int -instance_ass_item(PyInstanceObject *inst, Py_ssize_t i, PyObject *item) -{ - PyObject *func, *arg, *res; - - if (item == NULL) { - if (delitemstr == NULL) - delitemstr = PyString_InternFromString("__delitem__"); - func = instance_getattr(inst, delitemstr); - } - else { - if (setitemstr == NULL) - setitemstr = PyString_InternFromString("__setitem__"); - func = instance_getattr(inst, setitemstr); - } - if (func == NULL) - return -1; - if (item == NULL) - arg = PyInt_FromSsize_t(i); - else - arg = Py_BuildValue("(nO)", i, item); - if (arg == NULL) { - Py_DECREF(func); - return -1; - } - res = PyEval_CallObject(func, arg); - Py_DECREF(func); - Py_DECREF(arg); - if (res == NULL) - return -1; - Py_DECREF(res); - return 0; -} - -static int -instance_ass_slice(PyInstanceObject *inst, Py_ssize_t i, Py_ssize_t j, PyObject *value) -{ - PyObject *func, *arg, *res; - static PyObject *setslicestr, *delslicestr; - - if (value == NULL) { - if (delslicestr == NULL) - delslicestr = - PyString_InternFromString("__delslice__"); - func = instance_getattr(inst, delslicestr); - if (func == NULL) { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return -1; - PyErr_Clear(); - if (delitemstr == NULL) - delitemstr = - PyString_InternFromString("__delitem__"); - func = instance_getattr(inst, delitemstr); - if (func == NULL) - return -1; - - arg = Py_BuildValue("(N)", - _PySlice_FromIndices(i, j)); - } else - arg = Py_BuildValue("(nn)", i, j); - } - else { - if (setslicestr == NULL) - setslicestr = - PyString_InternFromString("__setslice__"); - func = instance_getattr(inst, setslicestr); - if (func == NULL) { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return -1; - PyErr_Clear(); - if (setitemstr == NULL) - setitemstr = - PyString_InternFromString("__setitem__"); - func = instance_getattr(inst, setitemstr); - if (func == NULL) - return -1; - - arg = Py_BuildValue("(NO)", - _PySlice_FromIndices(i, j), value); - } else - arg = Py_BuildValue("(nnO)", i, j, value); - } - if (arg == NULL) { - Py_DECREF(func); - return -1; - } - res = PyEval_CallObject(func, arg); - Py_DECREF(func); - Py_DECREF(arg); - if (res == NULL) - return -1; - Py_DECREF(res); - return 0; -} - -static int -instance_contains(PyInstanceObject *inst, PyObject *member) -{ - static PyObject *__contains__; - PyObject *func; - - /* Try __contains__ first. - * If that can't be done, try iterator-based searching. - */ - - if(__contains__ == NULL) { - __contains__ = PyString_InternFromString("__contains__"); - if(__contains__ == NULL) - return -1; - } - func = instance_getattr(inst, __contains__); - if (func) { - PyObject *res; - int ret; - PyObject *arg = PyTuple_Pack(1, member); - if(arg == NULL) { - Py_DECREF(func); - return -1; - } - res = PyEval_CallObject(func, arg); - Py_DECREF(func); - Py_DECREF(arg); - if(res == NULL) - return -1; - ret = PyObject_IsTrue(res); - Py_DECREF(res); - return ret; - } - - /* Couldn't find __contains__. */ - if (PyErr_ExceptionMatches(PyExc_AttributeError)) { - /* Assume the failure was simply due to that there is no - * __contains__ attribute, and try iterating instead. - */ - PyErr_Clear(); - return _PySequence_IterSearch((PyObject *)inst, member, - PY_ITERSEARCH_CONTAINS) > 0; - } - else - return -1; -} - -static PySequenceMethods -instance_as_sequence = { - (lenfunc)instance_length, /* sq_length */ - 0, /* sq_concat */ - 0, /* sq_repeat */ - (ssizeargfunc)instance_item, /* sq_item */ - (ssizessizeargfunc)instance_slice, /* sq_slice */ - (ssizeobjargproc)instance_ass_item, /* sq_ass_item */ - (ssizessizeobjargproc)instance_ass_slice,/* sq_ass_slice */ - (objobjproc)instance_contains, /* sq_contains */ -}; - -static PyObject * -generic_unary_op(PyInstanceObject *self, PyObject *methodname) -{ - PyObject *func, *res; - - if ((func = instance_getattr(self, methodname)) == NULL) - return NULL; - res = PyEval_CallObject(func, (PyObject *)NULL); - Py_DECREF(func); - return res; -} - -static PyObject * -generic_binary_op(PyObject *v, PyObject *w, char *opname) -{ - PyObject *result; - PyObject *args; - PyObject *func = PyObject_GetAttrString(v, opname); - if (func == NULL) { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return NULL; - PyErr_Clear(); - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - args = PyTuple_Pack(1, w); - if (args == NULL) { - Py_DECREF(func); - return NULL; - } - result = PyEval_CallObject(func, args); - Py_DECREF(args); - Py_DECREF(func); - return result; -} - - -static PyObject *coerce_obj; - -/* Try one half of a binary operator involving a class instance. */ -static PyObject * -half_binop(PyObject *v, PyObject *w, char *opname, binaryfunc thisfunc, - int swapped) -{ - PyObject *args; - PyObject *coercefunc; - PyObject *coerced = NULL; - PyObject *v1; - PyObject *result; - - if (!PyInstance_Check(v)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - if (coerce_obj == NULL) { - coerce_obj = PyString_InternFromString("__coerce__"); - if (coerce_obj == NULL) - return NULL; - } - coercefunc = PyObject_GetAttr(v, coerce_obj); - if (coercefunc == NULL) { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return NULL; - PyErr_Clear(); - return generic_binary_op(v, w, opname); - } - - args = PyTuple_Pack(1, w); - if (args == NULL) { - Py_DECREF(coercefunc); - return NULL; - } - coerced = PyEval_CallObject(coercefunc, args); - Py_DECREF(args); - Py_DECREF(coercefunc); - if (coerced == NULL) { - return NULL; - } - if (coerced == Py_None || coerced == Py_NotImplemented) { - Py_DECREF(coerced); - return generic_binary_op(v, w, opname); - } - if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) { - Py_DECREF(coerced); - PyErr_SetString(PyExc_TypeError, - "coercion should return None or 2-tuple"); - return NULL; - } - v1 = PyTuple_GetItem(coerced, 0); - w = PyTuple_GetItem(coerced, 1); - if (v1->ob_type == v->ob_type && PyInstance_Check(v)) { - /* prevent recursion if __coerce__ returns self as the first - * argument */ - result = generic_binary_op(v1, w, opname); - } else { - if (Py_EnterRecursiveCall(" after coercion")) - return NULL; - if (swapped) - result = (thisfunc)(w, v1); - else - result = (thisfunc)(v1, w); - Py_LeaveRecursiveCall(); - } - Py_DECREF(coerced); - return result; -} - -/* Implement a binary operator involving at least one class instance. */ -static PyObject * -do_binop(PyObject *v, PyObject *w, char *opname, char *ropname, - binaryfunc thisfunc) -{ - PyObject *result = half_binop(v, w, opname, thisfunc, 0); - if (result == Py_NotImplemented) { - Py_DECREF(result); - result = half_binop(w, v, ropname, thisfunc, 1); - } - return result; -} - -static PyObject * -do_binop_inplace(PyObject *v, PyObject *w, char *iopname, char *opname, - char *ropname, binaryfunc thisfunc) -{ - PyObject *result = half_binop(v, w, iopname, thisfunc, 0); - if (result == Py_NotImplemented) { - Py_DECREF(result); - result = do_binop(v, w, opname, ropname, thisfunc); - } - return result; -} - -static int -instance_coerce(PyObject **pv, PyObject **pw) -{ - PyObject *v = *pv; - PyObject *w = *pw; - PyObject *coercefunc; - PyObject *args; - PyObject *coerced; - - if (coerce_obj == NULL) { - coerce_obj = PyString_InternFromString("__coerce__"); - if (coerce_obj == NULL) - return -1; - } - coercefunc = PyObject_GetAttr(v, coerce_obj); - if (coercefunc == NULL) { - /* No __coerce__ method */ - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return -1; - PyErr_Clear(); - return 1; - } - /* Has __coerce__ method: call it */ - args = PyTuple_Pack(1, w); - if (args == NULL) { - return -1; - } - coerced = PyEval_CallObject(coercefunc, args); - Py_DECREF(args); - Py_DECREF(coercefunc); - if (coerced == NULL) { - /* __coerce__ call raised an exception */ - return -1; - } - if (coerced == Py_None || coerced == Py_NotImplemented) { - /* __coerce__ says "I can't do it" */ - Py_DECREF(coerced); - return 1; - } - if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) { - /* __coerce__ return value is malformed */ - Py_DECREF(coerced); - PyErr_SetString(PyExc_TypeError, - "coercion should return None or 2-tuple"); - return -1; - } - /* __coerce__ returned two new values */ - *pv = PyTuple_GetItem(coerced, 0); - *pw = PyTuple_GetItem(coerced, 1); - Py_INCREF(*pv); - Py_INCREF(*pw); - Py_DECREF(coerced); - return 0; -} - -#define UNARY(funcname, methodname) \ -static PyObject *funcname(PyInstanceObject *self) { \ - static PyObject *o; \ - if (o == NULL) o = PyString_InternFromString(methodname); \ - return generic_unary_op(self, o); \ -} - -#define BINARY(f, m, n) \ -static PyObject *f(PyObject *v, PyObject *w) { \ - return do_binop(v, w, "__" m "__", "__r" m "__", n); \ -} - -#define BINARY_INPLACE(f, m, n) \ -static PyObject *f(PyObject *v, PyObject *w) { \ - return do_binop_inplace(v, w, "__i" m "__", "__" m "__", \ - "__r" m "__", n); \ -} - -UNARY(instance_neg, "__neg__") -UNARY(instance_pos, "__pos__") -UNARY(instance_abs, "__abs__") - -BINARY(instance_or, "or", PyNumber_Or) -BINARY(instance_and, "and", PyNumber_And) -BINARY(instance_xor, "xor", PyNumber_Xor) -BINARY(instance_lshift, "lshift", PyNumber_Lshift) -BINARY(instance_rshift, "rshift", PyNumber_Rshift) -BINARY(instance_add, "add", PyNumber_Add) -BINARY(instance_sub, "sub", PyNumber_Subtract) -BINARY(instance_mul, "mul", PyNumber_Multiply) -BINARY(instance_mod, "mod", PyNumber_Remainder) -BINARY(instance_divmod, "divmod", PyNumber_Divmod) -BINARY(instance_floordiv, "floordiv", PyNumber_FloorDivide) -BINARY(instance_truediv, "truediv", PyNumber_TrueDivide) - -BINARY_INPLACE(instance_ior, "or", PyNumber_InPlaceOr) -BINARY_INPLACE(instance_ixor, "xor", PyNumber_InPlaceXor) -BINARY_INPLACE(instance_iand, "and", PyNumber_InPlaceAnd) -BINARY_INPLACE(instance_ilshift, "lshift", PyNumber_InPlaceLshift) -BINARY_INPLACE(instance_irshift, "rshift", PyNumber_InPlaceRshift) -BINARY_INPLACE(instance_iadd, "add", PyNumber_InPlaceAdd) -BINARY_INPLACE(instance_isub, "sub", PyNumber_InPlaceSubtract) -BINARY_INPLACE(instance_imul, "mul", PyNumber_InPlaceMultiply) -BINARY_INPLACE(instance_imod, "mod", PyNumber_InPlaceRemainder) -BINARY_INPLACE(instance_ifloordiv, "floordiv", PyNumber_InPlaceFloorDivide) -BINARY_INPLACE(instance_itruediv, "truediv", PyNumber_InPlaceTrueDivide) - -/* Try a 3-way comparison, returning an int; v is an instance. Return: - -2 for an exception; - -1 if v < w; - 0 if v == w; - 1 if v > w; - 2 if this particular 3-way comparison is not implemented or undefined. -*/ -static int -half_cmp(PyObject *v, PyObject *w) -{ - static PyObject *cmp_obj; - PyObject *args; - PyObject *cmp_func; - PyObject *result; - long l; - - assert(PyInstance_Check(v)); - - if (cmp_obj == NULL) { - cmp_obj = PyString_InternFromString("__cmp__"); - if (cmp_obj == NULL) - return -2; - } - - cmp_func = PyObject_GetAttr(v, cmp_obj); - if (cmp_func == NULL) { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return -2; - PyErr_Clear(); - return 2; - } - - args = PyTuple_Pack(1, w); - if (args == NULL) { - Py_DECREF(cmp_func); - return -2; - } - - result = PyEval_CallObject(cmp_func, args); - Py_DECREF(args); - Py_DECREF(cmp_func); - - if (result == NULL) - return -2; - - if (result == Py_NotImplemented) { - Py_DECREF(result); - return 2; - } - - l = PyInt_AsLong(result); - Py_DECREF(result); - if (l == -1 && PyErr_Occurred()) { - PyErr_SetString(PyExc_TypeError, - "comparison did not return an int"); - return -2; - } - - return l < 0 ? -1 : l > 0 ? 1 : 0; -} - -/* Try a 3-way comparison, returning an int; either v or w is an instance. - We first try a coercion. Return: - -2 for an exception; - -1 if v < w; - 0 if v == w; - 1 if v > w; - 2 if this particular 3-way comparison is not implemented or undefined. - THIS IS ONLY CALLED FROM object.c! -*/ -static int -instance_compare(PyObject *v, PyObject *w) -{ - int c; - - c = PyNumber_CoerceEx(&v, &w); - if (c < 0) - return -2; - if (c == 0) { - /* If neither is now an instance, use regular comparison */ - if (!PyInstance_Check(v) && !PyInstance_Check(w)) { - c = PyObject_Compare(v, w); - Py_DECREF(v); - Py_DECREF(w); - if (PyErr_Occurred()) - return -2; - return c < 0 ? -1 : c > 0 ? 1 : 0; - } - } - else { - /* The coercion didn't do anything. - Treat this the same as returning v and w unchanged. */ - Py_INCREF(v); - Py_INCREF(w); - } - - if (PyInstance_Check(v)) { - c = half_cmp(v, w); - if (c <= 1) { - Py_DECREF(v); - Py_DECREF(w); - return c; - } - } - if (PyInstance_Check(w)) { - c = half_cmp(w, v); - if (c <= 1) { - Py_DECREF(v); - Py_DECREF(w); - if (c >= -1) - c = -c; - return c; - } - } - Py_DECREF(v); - Py_DECREF(w); - return 2; -} - -static int -instance_nonzero(PyInstanceObject *self) -{ - PyObject *func, *res; - long outcome; - static PyObject *nonzerostr; - - if (nonzerostr == NULL) - nonzerostr = PyString_InternFromString("__nonzero__"); - if ((func = instance_getattr(self, nonzerostr)) == NULL) { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return -1; - PyErr_Clear(); - if (lenstr == NULL) - lenstr = PyString_InternFromString("__len__"); - if ((func = instance_getattr(self, lenstr)) == NULL) { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return -1; - PyErr_Clear(); - /* Fall back to the default behavior: - all instances are nonzero */ - return 1; - } - } - res = PyEval_CallObject(func, (PyObject *)NULL); - Py_DECREF(func); - if (res == NULL) - return -1; - if (!PyInt_Check(res)) { - Py_DECREF(res); - PyErr_SetString(PyExc_TypeError, - "__nonzero__ should return an int"); - return -1; - } - outcome = PyInt_AsLong(res); - Py_DECREF(res); - if (outcome < 0) { - PyErr_SetString(PyExc_ValueError, - "__nonzero__ should return >= 0"); - return -1; - } - return outcome > 0; -} - -static Py_ssize_t -instance_index(PyInstanceObject *self) -{ - PyObject *func, *res; - Py_ssize_t outcome; - static PyObject *indexstr = NULL; - - if (indexstr == NULL) { - indexstr = PyString_InternFromString("__index__"); - if (indexstr == NULL) - return -1; - } - if ((func = instance_getattr(self, indexstr)) == NULL) { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return -1; - PyErr_Clear(); - PyErr_SetString(PyExc_TypeError, - "object cannot be interpreted as an index"); - return -1; - } - res = PyEval_CallObject(func, (PyObject *)NULL); - Py_DECREF(func); - if (res == NULL) - return -1; - if (PyInt_Check(res) || PyLong_Check(res)) { - outcome = res->ob_type->tp_as_number->nb_index(res); - } - else { - PyErr_SetString(PyExc_TypeError, - "__index__ must return an int or a long"); - outcome = -1; - } - Py_DECREF(res); - return outcome; -} - - -UNARY(instance_invert, "__invert__") -UNARY(instance_int, "__int__") -UNARY(instance_long, "__long__") -UNARY(instance_float, "__float__") -UNARY(instance_oct, "__oct__") -UNARY(instance_hex, "__hex__") - -static PyObject * -bin_power(PyObject *v, PyObject *w) -{ - return PyNumber_Power(v, w, Py_None); -} - -/* This version is for ternary calls only (z != None) */ -static PyObject * -instance_pow(PyObject *v, PyObject *w, PyObject *z) -{ - if (z == Py_None) { - return do_binop(v, w, "__pow__", "__rpow__", bin_power); - } - else { - PyObject *func; - PyObject *args; - PyObject *result; - - /* XXX Doesn't do coercions... */ - func = PyObject_GetAttrString(v, "__pow__"); - if (func == NULL) - return NULL; - args = PyTuple_Pack(2, w, z); - if (args == NULL) { - Py_DECREF(func); - return NULL; - } - result = PyEval_CallObject(func, args); - Py_DECREF(func); - Py_DECREF(args); - return result; - } -} - -static PyObject * -bin_inplace_power(PyObject *v, PyObject *w) -{ - return PyNumber_InPlacePower(v, w, Py_None); -} - - -static PyObject * -instance_ipow(PyObject *v, PyObject *w, PyObject *z) -{ - if (z == Py_None) { - return do_binop_inplace(v, w, "__ipow__", "__pow__", - "__rpow__", bin_inplace_power); - } - else { - /* XXX Doesn't do coercions... */ - PyObject *func; - PyObject *args; - PyObject *result; - - func = PyObject_GetAttrString(v, "__ipow__"); - if (func == NULL) { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return NULL; - PyErr_Clear(); - return instance_pow(v, w, z); - } - args = PyTuple_Pack(2, w, z); - if (args == NULL) { - Py_DECREF(func); - return NULL; - } - result = PyEval_CallObject(func, args); - Py_DECREF(func); - Py_DECREF(args); - return result; - } -} - - -/* Map rich comparison operators to their __xx__ namesakes */ -#define NAME_OPS 6 -static PyObject **name_op = NULL; - -static int -init_name_op(void) -{ - int i; - char *_name_op[] = { - "__lt__", - "__le__", - "__eq__", - "__ne__", - "__gt__", - "__ge__", - }; - - name_op = (PyObject **)malloc(sizeof(PyObject *) * NAME_OPS); - if (name_op == NULL) - return -1; - for (i = 0; i < NAME_OPS; ++i) { - name_op[i] = PyString_InternFromString(_name_op[i]); - if (name_op[i] == NULL) - return -1; - } - return 0; -} - -static PyObject * -half_richcompare(PyObject *v, PyObject *w, int op) -{ - PyObject *method; - PyObject *args; - PyObject *res; - - assert(PyInstance_Check(v)); - - if (name_op == NULL) { - if (init_name_op() < 0) - return NULL; - } - /* If the instance doesn't define an __getattr__ method, use - instance_getattr2 directly because it will not set an - exception on failure. */ - if (((PyInstanceObject *)v)->in_class->cl_getattr == NULL) - method = instance_getattr2((PyInstanceObject *)v, - name_op[op]); - else - method = PyObject_GetAttr(v, name_op[op]); - if (method == NULL) { - if (PyErr_Occurred()) { - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return NULL; - PyErr_Clear(); - } - res = Py_NotImplemented; - Py_INCREF(res); - return res; - } - - args = PyTuple_Pack(1, w); - if (args == NULL) { - Py_DECREF(method); - return NULL; - } - - res = PyEval_CallObject(method, args); - Py_DECREF(args); - Py_DECREF(method); - - return res; -} - -static PyObject * -instance_richcompare(PyObject *v, PyObject *w, int op) -{ - PyObject *res; - - if (PyInstance_Check(v)) { - res = half_richcompare(v, w, op); - if (res != Py_NotImplemented) - return res; - Py_DECREF(res); - } - - if (PyInstance_Check(w)) { - res = half_richcompare(w, v, _Py_SwappedOp[op]); - if (res != Py_NotImplemented) - return res; - Py_DECREF(res); - } - - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; -} - - -/* Get the iterator */ -static PyObject * -instance_getiter(PyInstanceObject *self) -{ - PyObject *func; - - if (iterstr == NULL) { - iterstr = PyString_InternFromString("__iter__"); - if (iterstr == NULL) - return NULL; - } - if (getitemstr == NULL) { - getitemstr = PyString_InternFromString("__getitem__"); - if (getitemstr == NULL) - return NULL; - } - - if ((func = instance_getattr(self, iterstr)) != NULL) { - PyObject *res = PyEval_CallObject(func, (PyObject *)NULL); - Py_DECREF(func); - if (res != NULL && !PyIter_Check(res)) { - PyErr_Format(PyExc_TypeError, - "__iter__ returned non-iterator " - "of type '%.100s'", - res->ob_type->tp_name); - Py_DECREF(res); - res = NULL; - } - return res; - } - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return NULL; - PyErr_Clear(); - if ((func = instance_getattr(self, getitemstr)) == NULL) { - PyErr_SetString(PyExc_TypeError, - "iteration over non-sequence"); - return NULL; - } - Py_DECREF(func); - return PySeqIter_New((PyObject *)self); -} - - -/* Call the iterator's next */ -static PyObject * -instance_iternext(PyInstanceObject *self) -{ - PyObject *func; - - if (nextstr == NULL) - nextstr = PyString_InternFromString("next"); - - if ((func = instance_getattr(self, nextstr)) != NULL) { - PyObject *res = PyEval_CallObject(func, (PyObject *)NULL); - Py_DECREF(func); - if (res != NULL) { - return res; - } - if (PyErr_ExceptionMatches(PyExc_StopIteration)) { - PyErr_Clear(); - return NULL; - } - return NULL; - } - PyErr_SetString(PyExc_TypeError, "instance has no next() method"); - return NULL; -} - -static PyObject * -instance_call(PyObject *func, PyObject *arg, PyObject *kw) -{ - PyObject *res, *call = PyObject_GetAttrString(func, "__call__"); - if (call == NULL) { - PyInstanceObject *inst = (PyInstanceObject*) func; - if (!PyErr_ExceptionMatches(PyExc_AttributeError)) - return NULL; - PyErr_Clear(); - PyErr_Format(PyExc_AttributeError, - "%.200s instance has no __call__ method", - PyString_AsString(inst->in_class->cl_name)); - return NULL; - } - /* We must check and increment the recursion depth here. Scenario: - class A: - pass - A.__call__ = A() # that's right - a = A() # ok - a() # infinite recursion - This bounces between instance_call() and PyObject_Call() without - ever hitting eval_frame() (which has the main recursion check). */ - if (Py_EnterRecursiveCall(" in __call__")) { - res = NULL; - } - else { - res = PyObject_Call(call, arg, kw); - Py_LeaveRecursiveCall(); - } - Py_DECREF(call); - return res; -} - - -static PyNumberMethods instance_as_number = { - instance_add, /* nb_add */ - instance_sub, /* nb_subtract */ - instance_mul, /* nb_multiply */ - instance_mod, /* nb_remainder */ - instance_divmod, /* nb_divmod */ - instance_pow, /* nb_power */ - (unaryfunc)instance_neg, /* nb_negative */ - (unaryfunc)instance_pos, /* nb_positive */ - (unaryfunc)instance_abs, /* nb_absolute */ - (inquiry)instance_nonzero, /* nb_nonzero */ - (unaryfunc)instance_invert, /* nb_invert */ - instance_lshift, /* nb_lshift */ - instance_rshift, /* nb_rshift */ - instance_and, /* nb_and */ - instance_xor, /* nb_xor */ - instance_or, /* nb_or */ - instance_coerce, /* nb_coerce */ - (unaryfunc)instance_int, /* nb_int */ - (unaryfunc)instance_long, /* nb_long */ - (unaryfunc)instance_float, /* nb_float */ - (unaryfunc)instance_oct, /* nb_oct */ - (unaryfunc)instance_hex, /* nb_hex */ - instance_iadd, /* nb_inplace_add */ - instance_isub, /* nb_inplace_subtract */ - instance_imul, /* nb_inplace_multiply */ - instance_imod, /* nb_inplace_remainder */ - instance_ipow, /* nb_inplace_power */ - instance_ilshift, /* nb_inplace_lshift */ - instance_irshift, /* nb_inplace_rshift */ - instance_iand, /* nb_inplace_and */ - instance_ixor, /* nb_inplace_xor */ - instance_ior, /* nb_inplace_or */ - instance_floordiv, /* nb_floor_divide */ - instance_truediv, /* nb_true_divide */ - instance_ifloordiv, /* nb_inplace_floor_divide */ - instance_itruediv, /* nb_inplace_true_divide */ - (lenfunc)instance_index, /* nb_index */ -}; - -PyTypeObject PyInstance_Type = { - PyObject_HEAD_INIT(&PyType_Type) - 0, - "instance", - sizeof(PyInstanceObject), - 0, - (destructor)instance_dealloc, /* tp_dealloc */ - 0, /* tp_print */ - 0, /* tp_getattr */ - 0, /* tp_setattr */ - instance_compare, /* tp_compare */ - (reprfunc)instance_repr, /* tp_repr */ - &instance_as_number, /* tp_as_number */ - &instance_as_sequence, /* tp_as_sequence */ - &instance_as_mapping, /* tp_as_mapping */ - (hashfunc)instance_hash, /* tp_hash */ - instance_call, /* tp_call */ - (reprfunc)instance_str, /* tp_str */ - (getattrofunc)instance_getattr, /* tp_getattro */ - (setattrofunc)instance_setattr, /* tp_setattro */ - 0, /* tp_as_buffer */ - Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/ - instance_doc, /* tp_doc */ - (traverseproc)instance_traverse, /* tp_traverse */ - 0, /* tp_clear */ - instance_richcompare, /* tp_richcompare */ - offsetof(PyInstanceObject, in_weakreflist), /* tp_weaklistoffset */ - (getiterfunc)instance_getiter, /* tp_iter */ - (iternextfunc)instance_iternext, /* tp_iternext */ - 0, /* tp_methods */ - 0, /* tp_members */ - 0, /* tp_getset */ - 0, /* tp_base */ - 0, /* tp_dict */ - 0, /* tp_descr_get */ - 0, /* tp_descr_set */ - 0, /* tp_dictoffset */ - 0, /* tp_init */ - 0, /* tp_alloc */ - instance_new, /* tp_new */ -}; - -/* Instance method objects are used for two purposes: +/* Method objects are used for two purposes: (a) as bound instance methods (returned by instancename.methodname) (b) as unbound methods (returned by ClassName.methodname) In case (b), im_self is NULL Modified: python/branches/p3yk/Objects/dictobject.c ============================================================================== --- python/branches/p3yk/Objects/dictobject.c (original) +++ python/branches/p3yk/Objects/dictobject.c Thu Aug 17 07:42:55 2006 @@ -2006,13 +2006,6 @@ return dict_update_common(self, args, kwds, "dict"); } -static long -dict_nohash(PyObject *self) -{ - PyErr_SetString(PyExc_TypeError, "dict objects are unhashable"); - return -1; -} - static PyObject * dict_iter(dictobject *dict) { @@ -2045,7 +2038,7 @@ 0, /* tp_as_number */ &dict_as_sequence, /* tp_as_sequence */ &dict_as_mapping, /* tp_as_mapping */ - dict_nohash, /* tp_hash */ + 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ Modified: python/branches/p3yk/Objects/listobject.c ============================================================================== --- python/branches/p3yk/Objects/listobject.c (original) +++ python/branches/p3yk/Objects/listobject.c Thu Aug 17 07:42:55 2006 @@ -2381,13 +2381,6 @@ return 0; } -static long -list_nohash(PyObject *self) -{ - PyErr_SetString(PyExc_TypeError, "list objects are unhashable"); - return -1; -} - static PyObject *list_iter(PyObject *seq); static PyObject *list_reversed(PyListObject* seq, PyObject* unused); @@ -2655,7 +2648,7 @@ 0, /* tp_as_number */ &list_as_sequence, /* tp_as_sequence */ &list_as_mapping, /* tp_as_mapping */ - list_nohash, /* tp_hash */ + 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ Modified: python/branches/p3yk/Objects/object.c ============================================================================== --- python/branches/p3yk/Objects/object.c (original) +++ python/branches/p3yk/Objects/object.c Thu Aug 17 07:42:55 2006 @@ -2,6 +2,7 @@ /* Generic object operations; and implementation of None (NoObject) */ #include "Python.h" +#include "sliceobject.h" /* For PyEllipsis_Type */ #ifdef __cplusplus extern "C" { @@ -663,10 +664,6 @@ which has the same return conventions as this function. */ f = v->ob_type->tp_compare; - if (PyInstance_Check(v)) - return (*f)(v, w); - if (PyInstance_Check(w)) - return (*w->ob_type->tp_compare)(v, w); /* If both have the same (non-NULL) tp_compare, use it. */ if (f != NULL && f == w->ob_type->tp_compare) { @@ -789,15 +786,7 @@ if (v->ob_type == w->ob_type && (f = v->ob_type->tp_compare) != NULL) { c = (*f)(v, w); - if (PyInstance_Check(v)) { - /* Instance tp_compare has a different signature. - But if it returns undefined we fall through. */ - if (c != 2) - return c; - /* Else fall through to try_rich_to_3way_compare() */ - } - else - return adjust_tp_compare(c); + return adjust_tp_compare(c); } /* We only get here if one of the following is true: a) v and w have different types @@ -911,7 +900,7 @@ /* If the types are equal, and not old-style instances, try to get out cheap (don't bother with coercions etc.). */ - if (v->ob_type == w->ob_type && !PyInstance_Check(v)) { + if (v->ob_type == w->ob_type) { cmpfunc fcmp; richcmpfunc frich = RICHCOMPARE(v->ob_type); /* If the type has richcmp, try it first. try_rich_compare @@ -1063,10 +1052,7 @@ PyTypeObject *tp = v->ob_type; if (tp->tp_hash != NULL) return (*tp->tp_hash)(v); - if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) { - return _Py_HashPointer(v); /* Use address as hash value */ - } - /* If there's a cmp but no hash defined, the object can't be hashed */ + /* Otherwise, the object can't be hashed */ PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'", v->ob_type->tp_name); return -1; @@ -1303,12 +1289,8 @@ n = PyTuple_GET_SIZE(mro); for (i = 0; i < n; i++) { base = PyTuple_GET_ITEM(mro, i); - if (PyClass_Check(base)) - dict = ((PyClassObject *)base)->cl_dict; - else { - assert(PyType_Check(base)); - dict = ((PyTypeObject *)base)->tp_dict; - } + assert(PyType_Check(base)); + dict = ((PyTypeObject *)base)->tp_dict; assert(dict && PyDict_Check(dict)); descr = PyDict_GetItem(dict, name); if (descr != NULL) @@ -1554,20 +1536,7 @@ { if (x == NULL) return 0; - if (PyInstance_Check(x)) { - PyObject *call = PyObject_GetAttrString(x, "__call__"); - if (call == NULL) { - PyErr_Clear(); - return 0; - } - /* Could test recursively but don't, for fear of endless - recursion if some joker sets self.__call__ = self */ - Py_DECREF(call); - return 1; - } - else { - return x->ob_type->tp_call != NULL; - } + return x->ob_type->tp_call != NULL; } /* Helper for PyObject_Dir. @@ -1701,7 +1670,7 @@ /* Elif some form of type or class, grab its dict and its bases. We deliberately don't suck up its __class__, as methods belonging to the metaclass would probably be more confusing than helpful. */ - else if (PyType_Check(arg) || PyClass_Check(arg)) { + else if (PyType_Check(arg)) { masterdict = PyDict_New(); if (masterdict == NULL) goto error; @@ -1886,6 +1855,9 @@ if (PyType_Ready(&PyNone_Type) < 0) Py_FatalError("Can't initialize type(None)"); + if (PyType_Ready(Py_Ellipsis->ob_type) < 0) + Py_FatalError("Can't initialize type(Ellipsis)"); + if (PyType_Ready(&PyNotImplemented_Type) < 0) Py_FatalError("Can't initialize type(NotImplemented)"); } Modified: python/branches/p3yk/Objects/setobject.c ============================================================================== --- python/branches/p3yk/Objects/setobject.c (original) +++ python/branches/p3yk/Objects/setobject.c Thu Aug 17 07:42:55 2006 @@ -718,13 +718,6 @@ return hash; } -static long -set_nohash(PyObject *self) -{ - PyErr_SetString(PyExc_TypeError, "set objects are unhashable"); - return -1; -} - /***** Set iterator type ***********************************************/ typedef struct { @@ -1813,7 +1806,7 @@ &set_as_number, /* tp_as_number */ &set_as_sequence, /* tp_as_sequence */ 0, /* tp_as_mapping */ - set_nohash, /* tp_hash */ + 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ Modified: python/branches/p3yk/Objects/stringobject.c ============================================================================== --- python/branches/p3yk/Objects/stringobject.c (original) +++ python/branches/p3yk/Objects/stringobject.c Thu Aug 17 07:42:55 2006 @@ -3982,6 +3982,8 @@ Return a nice string representation of the object.\n\ If the argument is a string, the return value is the same object."); +static PyObject *str_iter(PyObject *seq); + PyTypeObject PyString_Type = { PyObject_HEAD_INIT(&PyType_Type) 0, @@ -4009,7 +4011,7 @@ 0, /* tp_clear */ (richcmpfunc)string_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ + str_iter, /* tp_iter */ 0, /* tp_iternext */ string_methods, /* tp_methods */ 0, /* tp_members */ @@ -4984,3 +4986,120 @@ Py_DECREF(interned); interned = NULL; } + + +/*********************** Str Iterator ****************************/ + +typedef struct { + PyObject_HEAD + long it_index; + PyStringObject *it_seq; /* Set to NULL when iterator is exhausted */ +} striterobject; + +static void +striter_dealloc(striterobject *it) +{ + _PyObject_GC_UNTRACK(it); + Py_XDECREF(it->it_seq); + PyObject_GC_Del(it); +} + +static int +striter_traverse(striterobject *it, visitproc visit, void *arg) +{ + Py_VISIT(it->it_seq); + return 0; +} + +static PyObject * +striter_next(striterobject *it) +{ + PyStringObject *seq; + PyObject *item; + + assert(it != NULL); + seq = it->it_seq; + if (seq == NULL) + return NULL; + assert(PyString_Check(seq)); + + if (it->it_index < PyString_GET_SIZE(seq)) { + item = PyString_FromStringAndSize(PyString_AS_STRING(seq)+it->it_index, 1); + if (item != NULL) + ++it->it_index; + return item; + } + + Py_DECREF(seq); + it->it_seq = NULL; + return NULL; +} + +static PyObject * +striter_len(striterobject *it) +{ + Py_ssize_t len = 0; + if (it->it_seq) + len = PyString_GET_SIZE(it->it_seq) - it->it_index; + return PyInt_FromSsize_t(len); +} + +PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); + +static PyMethodDef striter_methods[] = { + {"__length_hint__", (PyCFunction)striter_len, METH_NOARGS, length_hint_doc}, + {NULL, NULL} /* sentinel */ +}; + +PyTypeObject PyStringIter_Type = { + PyObject_HEAD_INIT(&PyType_Type) + 0, /* ob_size */ + "striterator", /* tp_name */ + sizeof(striterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)striter_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ + 0, /* tp_doc */ + (traverseproc)striter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)striter_next, /* tp_iternext */ + striter_methods, /* tp_methods */ + 0, +}; + +static PyObject * +str_iter(PyObject *seq) +{ + striterobject *it; + + if (!PyString_Check(seq)) { + PyErr_BadInternalCall(); + return NULL; + } + it = PyObject_GC_New(striterobject, &PyStringIter_Type); + if (it == NULL) + return NULL; + it->it_index = 0; + Py_INCREF(seq); + it->it_seq = (PyStringObject *)seq; + _PyObject_GC_TRACK(it); + return (PyObject *)it; +} Modified: python/branches/p3yk/Objects/typeobject.c ============================================================================== --- python/branches/p3yk/Objects/typeobject.c (original) +++ python/branches/p3yk/Objects/typeobject.c Thu Aug 17 07:42:55 2006 @@ -214,7 +214,7 @@ } for (i = 0; i < PyTuple_GET_SIZE(value); i++) { ob = PyTuple_GET_ITEM(value, i); - if (!PyClass_Check(ob) && !PyType_Check(ob)) { + if (!PyType_Check(ob)) { PyErr_Format( PyExc_TypeError, "%s.__bases__ must be tuple of old- or new-style classes, not '%s'", @@ -957,47 +957,6 @@ return retval; } -static int -fill_classic_mro(PyObject *mro, PyObject *cls) -{ - PyObject *bases, *base; - Py_ssize_t i, n; - - assert(PyList_Check(mro)); - assert(PyClass_Check(cls)); - i = PySequence_Contains(mro, cls); - if (i < 0) - return -1; - if (!i) { - if (PyList_Append(mro, cls) < 0) - return -1; - } - bases = ((PyClassObject *)cls)->cl_bases; - assert(bases && PyTuple_Check(bases)); - n = PyTuple_GET_SIZE(bases); - for (i = 0; i < n; i++) { - base = PyTuple_GET_ITEM(bases, i); - if (fill_classic_mro(mro, base) < 0) - return -1; - } - return 0; -} - -static PyObject * -classic_mro(PyObject *cls) -{ - PyObject *mro; - - assert(PyClass_Check(cls)); - mro = PyList_New(0); - if (mro != NULL) { - if (fill_classic_mro(mro, cls) == 0) - return mro; - Py_DECREF(mro); - } - return NULL; -} - /* Method resolution order algorithm C3 described in "A Monotonic Superclass Linearization for Dylan", @@ -1229,11 +1188,7 @@ for (i = 0; i < n; i++) { PyObject *base = PyTuple_GET_ITEM(bases, i); PyObject *parentMRO; - if (PyType_Check(base)) - parentMRO = PySequence_List( - ((PyTypeObject*)base)->tp_mro); - else - parentMRO = classic_mro(base); + parentMRO = PySequence_List(((PyTypeObject*)base)->tp_mro); if (parentMRO == NULL) { Py_DECREF(to_merge); return NULL; @@ -1315,9 +1270,7 @@ for (i = 0; i < len; i++) { PyTypeObject *t; cls = PyTuple_GET_ITEM(tuple, i); - if (PyClass_Check(cls)) - continue; - else if (!PyType_Check(cls)) { + if (!PyType_Check(cls)) { PyErr_Format(PyExc_TypeError, "mro() returned a non-class ('%.500s')", cls->ob_type->tp_name); @@ -1356,8 +1309,6 @@ winner = NULL; for (i = 0; i < n; i++) { base_proto = PyTuple_GET_ITEM(bases, i); - if (PyClass_Check(base_proto)) - continue; if (!PyType_Check(base_proto)) { PyErr_SetString( PyExc_TypeError, @@ -1636,8 +1587,6 @@ for (i = 0; i < nbases; i++) { tmp = PyTuple_GET_ITEM(bases, i); tmptype = tmp->ob_type; - if (tmptype == &PyClass_Type) - continue; /* Special case classic classes */ if (PyType_IsSubtype(winner, tmptype)) continue; if (PyType_IsSubtype(tmptype, winner)) { @@ -1793,14 +1742,6 @@ tmp = PyTuple_GET_ITEM(bases, i); if (tmp == (PyObject *)base) continue; /* Skip primary base */ - if (PyClass_Check(tmp)) { - /* Classic base class provides both */ - if (may_add_dict && !add_dict) - add_dict++; - if (may_add_weak && !add_weak) - add_weak++; - break; - } assert(PyType_Check(tmp)); tmptype = (PyTypeObject *)tmp; if (may_add_dict && !add_dict && @@ -2006,12 +1947,8 @@ n = PyTuple_GET_SIZE(mro); for (i = 0; i < n; i++) { base = PyTuple_GET_ITEM(mro, i); - if (PyClass_Check(base)) - dict = ((PyClassObject *)base)->cl_dict; - else { - assert(PyType_Check(base)); - dict = ((PyTypeObject *)base)->tp_dict; - } + assert(PyType_Check(base)); + dict = ((PyTypeObject *)base)->tp_dict; assert(dict && PyDict_Check(dict)); res = PyDict_GetItem(dict, name); if (res != NULL) @@ -2364,12 +2301,6 @@ return f(self); } -static long -object_hash(PyObject *self) -{ - return _Py_HashPointer(self); -} - static PyObject * object_get_class(PyObject *self, void *closure) { @@ -2762,7 +2693,7 @@ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ - object_hash, /* tp_hash */ + (hashfunc)_Py_HashPointer, /* tp_hash */ 0, /* tp_call */ object_str, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ @@ -2791,7 +2722,7 @@ }; -/* Initialize the __dict__ in a type object */ +/* Add the methods from tp_methods to the __dict__ in a type object */ static int add_methods(PyTypeObject *type, PyMethodDef *meth) @@ -3118,7 +3049,7 @@ */ /* Initialize the base class */ - if (base && base->tp_dict == NULL) { + if (base != NULL && base->tp_dict == NULL) { if (PyType_Ready(base) < 0) goto error; } @@ -4490,41 +4421,35 @@ slot_tp_hash(PyObject *self) { PyObject *func; - static PyObject *hash_str, *eq_str, *cmp_str; + static PyObject *hash_str; long h; func = lookup_method(self, "__hash__", &hash_str); - if (func != NULL) { - PyObject *res = PyEval_CallObject(func, NULL); + if (func == Py_None) { Py_DECREF(func); - if (res == NULL) - return -1; - if (PyLong_Check(res)) - h = PyLong_Type.tp_hash(res); - else - h = PyInt_AsLong(res); - Py_DECREF(res); + func = NULL; } - else { - PyErr_Clear(); - func = lookup_method(self, "__eq__", &eq_str); - if (func == NULL) { - PyErr_Clear(); - func = lookup_method(self, "__cmp__", &cmp_str); - } - if (func != NULL) { - PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'", - self->ob_type->tp_name); - Py_DECREF(func); - return -1; - } + + if (func == NULL) { PyErr_Clear(); - h = _Py_HashPointer((void *)self); - } - if (h == -1 && !PyErr_Occurred()) - h = -2; - return h; + PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'", + self->ob_type->tp_name); + return -1; + } + + PyObject *res = PyEval_CallObject(func, NULL); + Py_DECREF(func); + if (res == NULL) + return -1; + if (PyLong_Check(res)) + h = PyLong_Type.tp_hash(res); + else + h = PyInt_AsLong(res); + Py_DECREF(res); + if (h == -1 && !PyErr_Occurred()) + h = -2; + return h; } static PyObject * @@ -5579,8 +5504,6 @@ tmp = PyTuple_GET_ITEM(mro, i); if (PyType_Check(tmp)) dict = ((PyTypeObject *)tmp)->tp_dict; - else if (PyClass_Check(tmp)) - dict = ((PyClassObject *)tmp)->cl_dict; else continue; res = PyDict_GetItem(dict, name); Modified: python/branches/p3yk/Objects/unicodeobject.c ============================================================================== --- python/branches/p3yk/Objects/unicodeobject.c (original) +++ python/branches/p3yk/Objects/unicodeobject.c Thu Aug 17 07:42:55 2006 @@ -7848,6 +7848,8 @@ encoding defaults to the current default string encoding.\n\ errors can be 'strict', 'replace' or 'ignore' and defaults to 'strict'."); +static PyObject *unicode_iter(PyObject *seq); + PyTypeObject PyUnicode_Type = { PyObject_HEAD_INIT(&PyType_Type) 0, /* ob_size */ @@ -7876,7 +7878,7 @@ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ - 0, /* tp_iter */ + unicode_iter, /* tp_iter */ 0, /* tp_iternext */ unicode_methods, /* tp_methods */ 0, /* tp_members */ @@ -7961,6 +7963,124 @@ unicode_freelist_size = 0; } + + +/********************* Unicode Iterator **************************/ + +typedef struct { + PyObject_HEAD + long it_index; + PyUnicodeObject *it_seq; /* Set to NULL when iterator is exhausted */ +} unicodeiterobject; + +static void +unicodeiter_dealloc(unicodeiterobject *it) +{ + _PyObject_GC_UNTRACK(it); + Py_XDECREF(it->it_seq); + PyObject_GC_Del(it); +} + +static int +unicodeiter_traverse(unicodeiterobject *it, visitproc visit, void *arg) +{ + Py_VISIT(it->it_seq); + return 0; +} + +static PyObject * +unicodeiter_next(unicodeiterobject *it) +{ + PyUnicodeObject *seq; + PyObject *item; + + assert(it != NULL); + seq = it->it_seq; + if (seq == NULL) + return NULL; + assert(PyUnicode_Check(seq)); + + if (it->it_index < PyUnicode_GET_SIZE(seq)) { + item = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(seq)+it->it_index, 1); + if (item != NULL) + ++it->it_index; + return item; + } + + Py_DECREF(seq); + it->it_seq = NULL; + return NULL; +} + +static PyObject * +unicodeiter_len(unicodeiterobject *it) +{ + Py_ssize_t len = 0; + if (it->it_seq) + len = PyUnicode_GET_SIZE(it->it_seq) - it->it_index; + return PyInt_FromSsize_t(len); +} + +PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); + +static PyMethodDef unicodeiter_methods[] = { + {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS, length_hint_doc}, + {NULL, NULL} /* sentinel */ +}; + +PyTypeObject PyUnicodeIter_Type = { + PyObject_HEAD_INIT(&PyType_Type) + 0, /* ob_size */ + "unicodeiterator", /* tp_name */ + sizeof(unicodeiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)unicodeiter_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ + 0, /* tp_doc */ + (traverseproc)unicodeiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)unicodeiter_next, /* tp_iternext */ + unicodeiter_methods, /* tp_methods */ + 0, +}; + +static PyObject * +unicode_iter(PyObject *seq) +{ + unicodeiterobject *it; + + if (!PyUnicode_Check(seq)) { + PyErr_BadInternalCall(); + return NULL; + } + it = PyObject_GC_New(unicodeiterobject, &PyUnicodeIter_Type); + if (it == NULL) + return NULL; + it->it_index = 0; + Py_INCREF(seq); + it->it_seq = (PyUnicodeObject *)seq; + _PyObject_GC_TRACK(it); + return (PyObject *)it; +} + #ifdef __cplusplus } #endif Modified: python/branches/p3yk/Python/ceval.c ============================================================================== --- python/branches/p3yk/Python/ceval.c (original) +++ python/branches/p3yk/Python/ceval.c Thu Aug 17 07:42:55 2006 @@ -3409,14 +3409,8 @@ return PyString_AsString(((PyFunctionObject*)func)->func_name); else if (PyCFunction_Check(func)) return ((PyCFunctionObject*)func)->m_ml->ml_name; - else if (PyClass_Check(func)) - return PyString_AsString(((PyClassObject*)func)->cl_name); - else if (PyInstance_Check(func)) { - return PyString_AsString( - ((PyInstanceObject*)func)->in_class->cl_name); - } else { + else return func->ob_type->tp_name; - } } const char * @@ -3428,13 +3422,8 @@ return "()"; else if (PyCFunction_Check(func)) return "()"; - else if (PyClass_Check(func)) - return " constructor"; - else if (PyInstance_Check(func)) { - return " instance"; - } else { + else return " object"; - } } static void Modified: python/branches/p3yk/Python/structmember.c ============================================================================== --- python/branches/p3yk/Python/structmember.c (original) +++ python/branches/p3yk/Python/structmember.c Thu Aug 17 07:42:55 2006 @@ -126,6 +126,10 @@ v = PyLong_FromUnsignedLongLong(*(unsigned PY_LONG_LONG *)addr); break; #endif /* HAVE_LONG_LONG */ + case T_NONE: + v = Py_None; + Py_INCREF(v); + break; default: PyErr_SetString(PyExc_SystemError, "bad memberdescr type"); v = NULL; Modified: python/branches/p3yk/README ============================================================================== --- python/branches/p3yk/README (original) +++ python/branches/p3yk/README Thu Aug 17 07:42:55 2006 @@ -1,4 +1,4 @@ -This is Python 3000 -- unversioned (branched off 2.5 pre alpha 1) +This is Python 3000 -- unversioned (branched off 2.5 in various beta stages) ================================================================= Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Python Software Foundation. @@ -30,6 +30,14 @@ holders. +Python 3000 disclaimer +---------------------- + +This README hasn't been updated for Python 3000 yet. If you see +anything that should clearly be deleted, let me know (guido at python.org) +or submit a patch to the Python 3000 category in SourceForge. + + What's new in this release? --------------------------- From python-3000-checkins at python.org Thu Aug 17 10:56:09 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Thu, 17 Aug 2006 10:56:09 +0200 (CEST) Subject: [Python-3000-checkins] r51337 - python/branches/p3yk/Lib/wsgiref/handlers.py Message-ID: <20060817085609.8AAC21E4004@bag.python.org> Author: guido.van.rossum Date: Thu Aug 17 10:56:08 2006 New Revision: 51337 Modified: python/branches/p3yk/Lib/wsgiref/handlers.py Log: Use explicit relative import, to make things work again. Modified: python/branches/p3yk/Lib/wsgiref/handlers.py ============================================================================== --- python/branches/p3yk/Lib/wsgiref/handlers.py (original) +++ python/branches/p3yk/Lib/wsgiref/handlers.py Thu Aug 17 10:56:08 2006 @@ -1,8 +1,8 @@ """Base classes for server/gateway implementations""" from types import StringType -from util import FileWrapper, guess_scheme, is_hop_by_hop -from headers import Headers +from .util import FileWrapper, guess_scheme, is_hop_by_hop +from .headers import Headers import sys, os, time From python-3000-checkins at python.org Thu Aug 17 10:57:27 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Thu, 17 Aug 2006 10:57:27 +0200 (CEST) Subject: [Python-3000-checkins] r51338 - python/branches/p3yk/Lib/logging/handlers.py Message-ID: <20060817085727.3AAA21E4004@bag.python.org> Author: guido.van.rossum Date: Thu Aug 17 10:57:26 2006 New Revision: 51338 Modified: python/branches/p3yk/Lib/logging/handlers.py Log: If cPickle isn't available, use pickle. Modified: python/branches/p3yk/Lib/logging/handlers.py ============================================================================== --- python/branches/p3yk/Lib/logging/handlers.py (original) +++ python/branches/p3yk/Lib/logging/handlers.py Thu Aug 17 10:57:26 2006 @@ -27,7 +27,11 @@ To use, simply 'import logging' and log away! """ -import sys, logging, socket, types, os, string, cPickle, struct, time, glob +import sys, logging, socket, types, os, string, struct, time, glob +try: + import cPickle as pickle +except ImportError: + import pickle try: import codecs @@ -389,7 +393,7 @@ if ei: dummy = self.format(record) # just to get traceback text into record.exc_text record.exc_info = None # to avoid Unpickleable error - s = cPickle.dumps(record.__dict__, 1) + s = pickle.dumps(record.__dict__, 1) if ei: record.exc_info = ei # for next handler slen = struct.pack(">L", len(s)) From python-3000-checkins at python.org Thu Aug 17 11:10:10 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Thu, 17 Aug 2006 11:10:10 +0200 (CEST) Subject: [Python-3000-checkins] r51339 - python/branches/p3yk/Lib/xml/sax/__init__.py python/branches/p3yk/Lib/xml/sax/saxutils.py python/branches/p3yk/Lib/xml/sax/xmlreader.py Message-ID: <20060817091010.93A9B1E4004@bag.python.org> Author: guido.van.rossum Date: Thu Aug 17 11:10:09 2006 New Revision: 51339 Modified: python/branches/p3yk/Lib/xml/sax/__init__.py python/branches/p3yk/Lib/xml/sax/saxutils.py python/branches/p3yk/Lib/xml/sax/xmlreader.py Log: Use explicit relative import to make this work again. Modified: python/branches/p3yk/Lib/xml/sax/__init__.py ============================================================================== --- python/branches/p3yk/Lib/xml/sax/__init__.py (original) +++ python/branches/p3yk/Lib/xml/sax/__init__.py Thu Aug 17 11:10:09 2006 @@ -19,9 +19,9 @@ expatreader -- Driver that allows use of the Expat parser with SAX. """ -from xmlreader import InputSource -from handler import ContentHandler, ErrorHandler -from _exceptions import SAXException, SAXNotRecognizedException, \ +from .xmlreader import InputSource +from .handler import ContentHandler, ErrorHandler +from ._exceptions import SAXException, SAXNotRecognizedException, \ SAXParseException, SAXNotSupportedException, \ SAXReaderNotAvailable Modified: python/branches/p3yk/Lib/xml/sax/saxutils.py ============================================================================== --- python/branches/p3yk/Lib/xml/sax/saxutils.py (original) +++ python/branches/p3yk/Lib/xml/sax/saxutils.py Thu Aug 17 11:10:09 2006 @@ -4,8 +4,8 @@ """ import os, urlparse, urllib, types -import handler -import xmlreader +from . import handler +from . import xmlreader try: _StringTypes = [types.StringType, types.UnicodeType] Modified: python/branches/p3yk/Lib/xml/sax/xmlreader.py ============================================================================== --- python/branches/p3yk/Lib/xml/sax/xmlreader.py (original) +++ python/branches/p3yk/Lib/xml/sax/xmlreader.py Thu Aug 17 11:10:09 2006 @@ -1,9 +1,9 @@ """An XML Reader is the SAX 2 name for an XML parser. XML Parsers should be based on this code. """ -import handler +from . import handler -from _exceptions import SAXNotSupportedException, SAXNotRecognizedException +from ._exceptions import SAXNotSupportedException, SAXNotRecognizedException # ===== XMLREADER ===== @@ -113,7 +113,7 @@ XMLReader.__init__(self) def parse(self, source): - import saxutils + from . import saxutils source = saxutils.prepare_input_source(source) self.prepareParser(source) From python-3000-checkins at python.org Thu Aug 17 22:24:22 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Thu, 17 Aug 2006 22:24:22 +0200 (CEST) Subject: [Python-3000-checkins] r51343 - in python/branches/p3yk: Lib/Cookie.py Lib/ctypes/macholib/dyld.py Lib/sqlite3/__init__.py Lib/test/pickletester.py Lib/test/regrtest.py Lib/test/test_array.py Lib/test/test_bool.py Lib/test/test_datetime.py Lib/test/test_deque.py Lib/test/test_descr.py Lib/test/test_exceptions.py Lib/test/test_generators.py Lib/test/test_logging.py Lib/test/test_re.py Lib/test/test_traceback.py Lib/xml/dom/__init__.py Objects/genobject.c setup.py Message-ID: <20060817202422.0638B1E4004@bag.python.org> Author: guido.van.rossum Date: Thu Aug 17 22:24:18 2006 New Revision: 51343 Modified: python/branches/p3yk/Lib/Cookie.py python/branches/p3yk/Lib/ctypes/macholib/dyld.py python/branches/p3yk/Lib/sqlite3/__init__.py python/branches/p3yk/Lib/test/pickletester.py python/branches/p3yk/Lib/test/regrtest.py python/branches/p3yk/Lib/test/test_array.py python/branches/p3yk/Lib/test/test_bool.py python/branches/p3yk/Lib/test/test_datetime.py python/branches/p3yk/Lib/test/test_deque.py python/branches/p3yk/Lib/test/test_descr.py python/branches/p3yk/Lib/test/test_exceptions.py python/branches/p3yk/Lib/test/test_generators.py python/branches/p3yk/Lib/test/test_logging.py python/branches/p3yk/Lib/test/test_re.py python/branches/p3yk/Lib/test/test_traceback.py python/branches/p3yk/Lib/xml/dom/__init__.py python/branches/p3yk/Objects/genobject.c python/branches/p3yk/setup.py Log: Quite a few fixes to make the library and test suite more robust when cPickle cannot be imported. This was necessary because my last mass checkin broke cPickle and I don't feel like debugging it right now; but it seems a good idea in general not to require cPickle when pickle.py is also there. A few unrelated fixes for issues while debigging various test failures. setup.py: disable building of cPickle until I've fixed it Objects/... genobject.c: disallow raising string exceptions Lib/... Cookie.py: fix doctest not to fail if cPickle is missing ctypes/macholib/dyld.py: fix relative imports sqlite3/__init__.py: fix relative import xml/dom/__init__.py: fix relative import Lib/test/... regrtest.py: reduce list of skipped items on darwin test_generators.py: don't test string exceptions; test throw() errors test_traceback.py: don't test string exceptions pickletester.py: don't fail if cPickle is missing test_datetime.py: don't fail if cPickle is missing test_descr.py: don't fail if cPickle is missing (still some other failures) test_exceptions.py: don't fail if cPickle is missing test_re.py: don't fail if cPickle is missing test_array.py: use pickle, not cPickle test_bool.py: don't fail if cPickle is missing test_deque.py: use pickle, not cPickle test_logging.py: use pickle, not cPickle Modified: python/branches/p3yk/Lib/Cookie.py ============================================================================== --- python/branches/p3yk/Lib/Cookie.py (original) +++ python/branches/p3yk/Lib/Cookie.py Thu Aug 17 22:24:18 2006 @@ -162,7 +162,7 @@ 7 >>> C["string"].value 'seven' - >>> C.output() + >>> C.output().replace('p0', 'p1') # Hack for cPickle/pickle differences 'Set-Cookie: number="I7\\012."\r\nSet-Cookie: string="S\'seven\'\\012p1\\012."' Be warned, however, if SerialCookie cannot de-serialize a value (because Modified: python/branches/p3yk/Lib/ctypes/macholib/dyld.py ============================================================================== --- python/branches/p3yk/Lib/ctypes/macholib/dyld.py (original) +++ python/branches/p3yk/Lib/ctypes/macholib/dyld.py Thu Aug 17 22:24:18 2006 @@ -6,8 +6,8 @@ """ import os -from framework import framework_info -from dylib import dylib_info +from ctypes.macholib.framework import framework_info +from ctypes.macholib.dylib import dylib_info from itertools import * __all__ = [ Modified: python/branches/p3yk/Lib/sqlite3/__init__.py ============================================================================== --- python/branches/p3yk/Lib/sqlite3/__init__.py (original) +++ python/branches/p3yk/Lib/sqlite3/__init__.py Thu Aug 17 22:24:18 2006 @@ -21,4 +21,4 @@ # misrepresented as being the original software. # 3. This notice may not be removed or altered from any source distribution. -from dbapi2 import * +from sqlite3.dbapi2 import * Modified: python/branches/p3yk/Lib/test/pickletester.py ============================================================================== --- python/branches/p3yk/Lib/test/pickletester.py (original) +++ python/branches/p3yk/Lib/test/pickletester.py Thu Aug 17 22:24:18 2006 @@ -1,6 +1,9 @@ import unittest import pickle -import cPickle +try: + import cPickle +except ImportError: + cPickle = None import pickletools import copy_reg @@ -10,7 +13,8 @@ # Tests that try a number of pickle protocols should have a # for proto in protocols: # kind of outer loop. -assert pickle.HIGHEST_PROTOCOL == cPickle.HIGHEST_PROTOCOL == 2 +if cPickle is not None: + assert pickle.HIGHEST_PROTOCOL == cPickle.HIGHEST_PROTOCOL == 2 protocols = range(pickle.HIGHEST_PROTOCOL + 1) Modified: python/branches/p3yk/Lib/test/regrtest.py ============================================================================== --- python/branches/p3yk/Lib/test/regrtest.py (original) +++ python/branches/p3yk/Lib/test/regrtest.py Thu Aug 17 22:24:18 2006 @@ -1033,25 +1033,19 @@ """, 'darwin': """ - test__locale test_al test_bsddb test_bsddb3 test_cd test_cl - test_curses test_gdbm test_gl test_imgfile test_largefile test_linuxaudiodev test_locale - test_minidom test_nis - test_ntpath test_ossaudiodev - test_poll - test_sqlite test_startfile test_sunaudiodev """, Modified: python/branches/p3yk/Lib/test/test_array.py ============================================================================== --- python/branches/p3yk/Lib/test/test_array.py (original) +++ python/branches/p3yk/Lib/test/test_array.py Thu Aug 17 22:24:18 2006 @@ -7,7 +7,7 @@ from test import test_support from weakref import proxy import array, cStringIO, math -from cPickle import loads, dumps +from pickle import loads, dumps class ArraySubclass(array.array): pass Modified: python/branches/p3yk/Lib/test/test_bool.py ============================================================================== --- python/branches/p3yk/Lib/test/test_bool.py (original) +++ python/branches/p3yk/Lib/test/test_bool.py Thu Aug 17 22:24:18 2006 @@ -289,14 +289,23 @@ self.assertIs(pickle.loads(pickle.dumps(False, True)), False) def test_cpickle(self): - import cPickle + try: + import cPickle + except ImportError: + return # Just ignore this if cPickle doesn't exist + self.assertIs(cPickle.loads(cPickle.dumps(True)), True) self.assertIs(cPickle.loads(cPickle.dumps(False)), False) self.assertIs(cPickle.loads(cPickle.dumps(True, True)), True) self.assertIs(cPickle.loads(cPickle.dumps(False, True)), False) def test_mixedpickle(self): - import pickle, cPickle + import pickle + try: + import cPickle + except ImportError: + return # Just ignore this if cPickle doesn't exist + self.assertIs(pickle.loads(cPickle.dumps(True)), True) self.assertIs(pickle.loads(cPickle.dumps(False)), False) self.assertIs(pickle.loads(cPickle.dumps(True, True)), True) @@ -308,15 +317,19 @@ self.assertIs(cPickle.loads(pickle.dumps(False, True)), False) def test_picklevalues(self): - import pickle, cPickle - # Test for specific backwards-compatible pickle values + import pickle self.assertEqual(pickle.dumps(True), "I01\n.") self.assertEqual(pickle.dumps(False), "I00\n.") - self.assertEqual(cPickle.dumps(True), "I01\n.") - self.assertEqual(cPickle.dumps(False), "I00\n.") self.assertEqual(pickle.dumps(True, True), "I01\n.") self.assertEqual(pickle.dumps(False, True), "I00\n.") + + try: + import cPickle + except ImportError: + return # Just ignore the rest if cPickle doesn't exist + self.assertEqual(cPickle.dumps(True), "I01\n.") + self.assertEqual(cPickle.dumps(False), "I00\n.") self.assertEqual(cPickle.dumps(True, True), "I01\n.") self.assertEqual(cPickle.dumps(False, True), "I00\n.") Modified: python/branches/p3yk/Lib/test/test_datetime.py ============================================================================== --- python/branches/p3yk/Lib/test/test_datetime.py (original) +++ python/branches/p3yk/Lib/test/test_datetime.py Thu Aug 17 22:24:18 2006 @@ -5,8 +5,11 @@ import sys import pickle -import cPickle import unittest +try: + import cPickle +except ImportError: + cPickle = None from test import test_support @@ -18,9 +21,14 @@ pickle_choices = [(pickler, unpickler, proto) for pickler in pickle, cPickle + if pickler is not None for unpickler in pickle, cPickle + if unpickler is not None for proto in range(3)] -assert len(pickle_choices) == 2*2*3 +if cPickle is None: + assert len(pickle_choices) == 3 +else: + assert len(pickle_choices) == 2*2*3 # An arbitrary collection of objects of non-datetime types, for testing # mixed-type comparisons. Modified: python/branches/p3yk/Lib/test/test_deque.py ============================================================================== --- python/branches/p3yk/Lib/test/test_deque.py (original) +++ python/branches/p3yk/Lib/test/test_deque.py Thu Aug 17 22:24:18 2006 @@ -3,7 +3,7 @@ from test import test_support, seq_tests from weakref import proxy import copy -import cPickle as pickle +import pickle from cStringIO import StringIO import random import os Modified: python/branches/p3yk/Lib/test/test_descr.py ============================================================================== --- python/branches/p3yk/Lib/test/test_descr.py (original) +++ python/branches/p3yk/Lib/test/test_descr.py Thu Aug 17 22:24:18 2006 @@ -2666,7 +2666,11 @@ def pickles(): if verbose: print "Testing pickling and copying new-style classes and objects..." - import pickle, cPickle + import pickle + try: + import cPickle + except ImportError: + cPickle = None def sorteditems(d): L = d.items() @@ -2722,6 +2726,8 @@ pass for p in pickle, cPickle: + if p is None: + continue # cPickle not found -- skip it for bin in 0, 1: if verbose: print p.__name__, ["text", "binary"][bin] @@ -2781,7 +2787,7 @@ def pickleslots(): if verbose: print "Testing pickling of classes with __slots__ ..." - import pickle, cPickle + import pickle, pickle as cPickle # Pickling of classes with __slots__ but without __getstate__ should fail global B, C, D, E class B(object): Modified: python/branches/p3yk/Lib/test/test_exceptions.py ============================================================================== --- python/branches/p3yk/Lib/test/test_exceptions.py (original) +++ python/branches/p3yk/Lib/test/test_exceptions.py Thu Aug 17 22:24:18 2006 @@ -4,7 +4,11 @@ import sys import unittest import warnings -import pickle, cPickle +import pickle +try: + import cPickle +except ImportError: + cPickle = None from test.test_support import TESTFN, unlink, run_unittest @@ -292,6 +296,8 @@ # test for pickling support for p in pickle, cPickle: + if p is None: + continue # cPickle not found -- skip it for protocol in range(p.HIGHEST_PROTOCOL + 1): new = p.loads(p.dumps(e, protocol)) for checkArgName in expected: Modified: python/branches/p3yk/Lib/test/test_generators.py ============================================================================== --- python/branches/p3yk/Lib/test/test_generators.py (original) +++ python/branches/p3yk/Lib/test/test_generators.py Thu Aug 17 22:24:18 2006 @@ -1585,6 +1585,21 @@ ... TypeError: throw() third argument must be a traceback object +>>> g.throw("abc") +Traceback (most recent call last): + ... +TypeError: exceptions must be classes or instances deriving from BaseException, not str + +>>> g.throw(0) +Traceback (most recent call last): + ... +TypeError: exceptions must be classes or instances deriving from BaseException, not int + +>>> g.throw(list) +Traceback (most recent call last): + ... +TypeError: exceptions must be classes or instances deriving from BaseException, not type + >>> def throw(g,exc): ... try: ... raise exc @@ -1619,11 +1634,6 @@ ... ValueError: 7 ->>> f().throw("abc") # throw on just-opened generator -Traceback (most recent call last): - ... -abc - Now let's try closing a generator: >>> def f(): Modified: python/branches/p3yk/Lib/test/test_logging.py ============================================================================== --- python/branches/p3yk/Lib/test/test_logging.py (original) +++ python/branches/p3yk/Lib/test/test_logging.py Thu Aug 17 22:24:18 2006 @@ -25,7 +25,7 @@ """ import select -import os, sys, string, struct, types, cPickle, cStringIO +import os, sys, string, struct, types, pickle, cStringIO import socket, tempfile, threading, time import logging, logging.handlers, logging.config from test.test_support import run_with_locale @@ -70,7 +70,7 @@ raise def unPickle(self, data): - return cPickle.loads(data) + return pickle.loads(data) def handleLogRecord(self, record): logname = "logrecv.tcp." + record.name Modified: python/branches/p3yk/Lib/test/test_re.py ============================================================================== --- python/branches/p3yk/Lib/test/test_re.py (original) +++ python/branches/p3yk/Lib/test/test_re.py Thu Aug 17 22:24:18 2006 @@ -412,8 +412,12 @@ def test_pickling(self): import pickle self.pickle_test(pickle) - import cPickle - self.pickle_test(cPickle) + try: + import cPickle + except ImportError: + pass # cPickle not found -- skip it + else: + self.pickle_test(cPickle) def pickle_test(self, pickle): oldpat = re.compile('a(?:b|(c|e){1,2}?|d)+?(.)') Modified: python/branches/p3yk/Lib/test/test_traceback.py ============================================================================== --- python/branches/p3yk/Lib/test/test_traceback.py (original) +++ python/branches/p3yk/Lib/test/test_traceback.py Thu Aug 17 22:24:18 2006 @@ -111,35 +111,6 @@ lst = traceback.format_exception_only(e.__class__, e) self.assertEqual(lst, ['KeyboardInterrupt\n']) - # String exceptions are deprecated, but legal. The quirky form with - # separate "type" and "value" tends to break things, because - # not isinstance(value, type) - # and a string cannot be the first argument to issubclass. - # - # Note that sys.last_type and sys.last_value do not get set if an - # exception is caught, so we sort of cheat and just emulate them. - # - # test_string_exception1 is equivalent to - # - # >>> raise "String Exception" - # - # test_string_exception2 is equivalent to - # - # >>> raise "String Exception", "String Value" - # - def test_string_exception1(self): - str_type = "String Exception" - err = traceback.format_exception_only(str_type, None) - self.assertEqual(len(err), 1) - self.assertEqual(err[0], str_type + '\n') - - def test_string_exception2(self): - str_type = "String Exception" - str_value = "String Value" - err = traceback.format_exception_only(str_type, str_value) - self.assertEqual(len(err), 1) - self.assertEqual(err[0], str_type + ': ' + str_value + '\n') - def test_format_exception_only_bad__str__(self): class X(Exception): def __str__(self): Modified: python/branches/p3yk/Lib/xml/dom/__init__.py ============================================================================== --- python/branches/p3yk/Lib/xml/dom/__init__.py (original) +++ python/branches/p3yk/Lib/xml/dom/__init__.py Thu Aug 17 22:24:18 2006 @@ -136,4 +136,4 @@ EMPTY_NAMESPACE = None EMPTY_PREFIX = None -from domreg import getDOMImplementation,registerDOMImplementation +from .domreg import getDOMImplementation, registerDOMImplementation Modified: python/branches/p3yk/Objects/genobject.c ============================================================================== --- python/branches/p3yk/Objects/genobject.c (original) +++ python/branches/p3yk/Objects/genobject.c Thu Aug 17 22:24:18 2006 @@ -253,12 +253,11 @@ } } - /* Allow raising builtin string exceptions */ - - else if (!PyString_CheckExact(typ)) { + else { /* Not something you can raise. throw() fails. */ PyErr_Format(PyExc_TypeError, - "exceptions must be classes, or instances, not %s", + "exceptions must be classes or instances " + "deriving from BaseException, not %s", typ->ob_type->tp_name); goto failed_throw; } Modified: python/branches/p3yk/setup.py ============================================================================== --- python/branches/p3yk/setup.py (original) +++ python/branches/p3yk/setup.py Thu Aug 17 22:24:18 2006 @@ -430,7 +430,7 @@ # cStringIO and cPickle exts.append( Extension('cStringIO', ['cStringIO.c']) ) - exts.append( Extension('cPickle', ['cPickle.c']) ) + ##exts.append( Extension('cPickle', ['cPickle.c']) ) # Memory-mapped files (also works on Win32). if platform not in ['atheos', 'mac']: From python-3000-checkins at python.org Thu Aug 17 23:11:48 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Thu, 17 Aug 2006 23:11:48 +0200 (CEST) Subject: [Python-3000-checkins] r51344 - in python/branches/p3yk: Lib/test/test_str.py Lib/test/test_unicode.py Objects/stringobject.c Objects/unicodeobject.c Message-ID: <20060817211148.ED5C21E4009@bag.python.org> Author: guido.van.rossum Date: Thu Aug 17 23:11:47 2006 New Revision: 51344 Modified: python/branches/p3yk/Lib/test/test_str.py python/branches/p3yk/Lib/test/test_unicode.py python/branches/p3yk/Objects/stringobject.c python/branches/p3yk/Objects/unicodeobject.c Log: Make the it_index field in the str/unicode iterators Py_ssize_t's. Test the new iterators on str/unicode. Modified: python/branches/p3yk/Lib/test/test_str.py ============================================================================== --- python/branches/p3yk/Lib/test/test_str.py (original) +++ python/branches/p3yk/Lib/test/test_str.py Thu Aug 17 23:11:47 2006 @@ -19,6 +19,14 @@ string_tests.MixinStrUnicodeUserStringTest.test_formatting(self) self.assertRaises(OverflowError, '%c'.__mod__, 0x1234) + def test_iterators(self): + # Make sure str objects have an __iter__ method + it = "abc".__iter__() + self.assertEqual(it.next(), "a") + self.assertEqual(it.next(), "b") + self.assertEqual(it.next(), "c") + self.assertRaises(StopIteration, it.next) + def test_conversion(self): # Make sure __str__() behaves properly class Foo0: Modified: python/branches/p3yk/Lib/test/test_unicode.py ============================================================================== --- python/branches/p3yk/Lib/test/test_unicode.py (original) +++ python/branches/p3yk/Lib/test/test_unicode.py Thu Aug 17 23:11:47 2006 @@ -93,6 +93,14 @@ testrepr = repr(u''.join(map(unichr, xrange(256)))) self.assertEqual(testrepr, latin1repr) + def test_iterators(self): + # Make sure unicode objects have an __iter__ method + it = u"\u1111\u2222\u3333".__iter__() + self.assertEqual(it.next(), u"\u1111") + self.assertEqual(it.next(), u"\u2222") + self.assertEqual(it.next(), u"\u3333") + self.assertRaises(StopIteration, it.next) + def test_count(self): string_tests.CommonTest.test_count(self) # check mixed argument types Modified: python/branches/p3yk/Objects/stringobject.c ============================================================================== --- python/branches/p3yk/Objects/stringobject.c (original) +++ python/branches/p3yk/Objects/stringobject.c Thu Aug 17 23:11:47 2006 @@ -4992,7 +4992,7 @@ typedef struct { PyObject_HEAD - long it_index; + Py_ssize_t it_index; PyStringObject *it_seq; /* Set to NULL when iterator is exhausted */ } striterobject; @@ -5024,7 +5024,8 @@ assert(PyString_Check(seq)); if (it->it_index < PyString_GET_SIZE(seq)) { - item = PyString_FromStringAndSize(PyString_AS_STRING(seq)+it->it_index, 1); + item = PyString_FromStringAndSize( + PyString_AS_STRING(seq)+it->it_index, 1); if (item != NULL) ++it->it_index; return item; @@ -5044,18 +5045,20 @@ return PyInt_FromSsize_t(len); } -PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); +PyDoc_STRVAR(length_hint_doc, + "Private method returning an estimate of len(list(it))."); static PyMethodDef striter_methods[] = { - {"__length_hint__", (PyCFunction)striter_len, METH_NOARGS, length_hint_doc}, + {"__length_hint__", (PyCFunction)striter_len, METH_NOARGS, + length_hint_doc}, {NULL, NULL} /* sentinel */ }; PyTypeObject PyStringIter_Type = { PyObject_HEAD_INIT(&PyType_Type) 0, /* ob_size */ - "striterator", /* tp_name */ - sizeof(striterobject), /* tp_basicsize */ + "striterator", /* tp_name */ + sizeof(striterobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ (destructor)striter_dealloc, /* tp_dealloc */ Modified: python/branches/p3yk/Objects/unicodeobject.c ============================================================================== --- python/branches/p3yk/Objects/unicodeobject.c (original) +++ python/branches/p3yk/Objects/unicodeobject.c Thu Aug 17 23:11:47 2006 @@ -7969,7 +7969,7 @@ typedef struct { PyObject_HEAD - long it_index; + Py_ssize_t it_index; PyUnicodeObject *it_seq; /* Set to NULL when iterator is exhausted */ } unicodeiterobject; @@ -8001,7 +8001,8 @@ assert(PyUnicode_Check(seq)); if (it->it_index < PyUnicode_GET_SIZE(seq)) { - item = PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(seq)+it->it_index, 1); + item = PyUnicode_FromUnicode( + PyUnicode_AS_UNICODE(seq)+it->it_index, 1); if (item != NULL) ++it->it_index; return item; @@ -8024,7 +8025,8 @@ PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it))."); static PyMethodDef unicodeiter_methods[] = { - {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS, length_hint_doc}, + {"__length_hint__", (PyCFunction)unicodeiter_len, METH_NOARGS, + length_hint_doc}, {NULL, NULL} /* sentinel */ }; @@ -8035,7 +8037,7 @@ sizeof(unicodeiterobject), /* tp_basicsize */ 0, /* tp_itemsize */ /* methods */ - (destructor)unicodeiter_dealloc, /* tp_dealloc */ + (destructor)unicodeiter_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ From python-3000-checkins at python.org Fri Aug 18 00:28:50 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Fri, 18 Aug 2006 00:28:50 +0200 (CEST) Subject: [Python-3000-checkins] r51345 - in python/branches/p3yk: Modules/cPickle.c setup.py Message-ID: <20060817222850.0D29C1E4004@bag.python.org> Author: guido.van.rossum Date: Fri Aug 18 00:28:49 2006 New Revision: 51345 Modified: python/branches/p3yk/Modules/cPickle.c python/branches/p3yk/setup.py Log: Fixed cPickle, by restoring some of the deleted code. -This line, and those below, will be ignored-- M setup.py M Modules/cPickle.c Modified: python/branches/p3yk/Modules/cPickle.c ============================================================================== --- python/branches/p3yk/Modules/cPickle.c (original) +++ python/branches/p3yk/Modules/cPickle.c Fri Aug 18 00:28:49 2006 @@ -1786,7 +1786,6 @@ } - static int save_global(Picklerobject *self, PyObject *args, PyObject *name) { @@ -2278,6 +2277,12 @@ } break; + case 'i': + break; + + case 'c': + break; + case 'f': if (type == &PyFunction_Type) { res = save_global(self, args, NULL); @@ -3438,6 +3443,30 @@ return 0; } +static PyObject * +Instance_New(PyObject *cls, PyObject *args) +{ + PyObject *r = 0; + + if ((r=PyObject_CallObject(cls, args))) return r; + + { + PyObject *tp, *v, *tb, *tmp_value; + + PyErr_Fetch(&tp, &v, &tb); + tmp_value = v; + /* NULL occurs when there was a KeyboardInterrupt */ + if (tmp_value == NULL) + tmp_value = Py_None; + if ((r = PyTuple_Pack(3, tmp_value, cls, args))) { + Py_XDECREF(v); + v=r; + } + PyErr_Restore(tp,v,tb); + } + return NULL; +} + static int load_obj(Unpicklerobject *self) @@ -3448,6 +3477,10 @@ if ((i = marker(self)) < 0) return -1; if (!( tup=Pdata_popTuple(self->stack, i+1))) return -1; PDATA_POP(self->stack, class); + if (class) { + obj = Instance_New(class, tup); + Py_DECREF(class); + } Py_DECREF(tup); if (! obj) return -1; @@ -3483,8 +3516,8 @@ if (! class) return -1; if ((tup=Pdata_popTuple(self->stack, i))) { - PyErr_SetString(UnpicklingError, "it's dead, Jim"); - return -1; + obj = Instance_New(class, tup); + Py_DECREF(tup); } Py_DECREF(class); @@ -4177,6 +4210,10 @@ PDATA_POP(self->stack, arg_tup); if (! arg_tup) return -1; PDATA_POP(self->stack, callable); + if (callable) { + ob = Instance_New(callable, arg_tup); + Py_DECREF(callable); + } Py_DECREF(arg_tup); if (! ob) return -1; Modified: python/branches/p3yk/setup.py ============================================================================== --- python/branches/p3yk/setup.py (original) +++ python/branches/p3yk/setup.py Fri Aug 18 00:28:49 2006 @@ -430,7 +430,7 @@ # cStringIO and cPickle exts.append( Extension('cStringIO', ['cStringIO.c']) ) - ##exts.append( Extension('cPickle', ['cPickle.c']) ) + exts.append( Extension('cPickle', ['cPickle.c']) ) # Memory-mapped files (also works on Win32). if platform not in ['atheos', 'mac']: From python-3000-checkins at python.org Fri Aug 18 00:37:45 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Fri, 18 Aug 2006 00:37:45 +0200 (CEST) Subject: [Python-3000-checkins] r51346 - in python/branches/p3yk/Lib/sqlite3: dbapi2.py test/userfunctions.py Message-ID: <20060817223745.5E4D71E4007@bag.python.org> Author: guido.van.rossum Date: Fri Aug 18 00:37:44 2006 New Revision: 51346 Modified: python/branches/p3yk/Lib/sqlite3/dbapi2.py python/branches/p3yk/Lib/sqlite3/test/userfunctions.py Log: Make unit tests pass: replace apply() and adapt to different attribute message. Modified: python/branches/p3yk/Lib/sqlite3/dbapi2.py ============================================================================== --- python/branches/p3yk/Lib/sqlite3/dbapi2.py (original) +++ python/branches/p3yk/Lib/sqlite3/dbapi2.py Fri Aug 18 00:37:44 2006 @@ -39,13 +39,13 @@ Timestamp = datetime.datetime def DateFromTicks(ticks): - return apply(Date, time.localtime(ticks)[:3]) + return Date(*time.localtime(ticks)[:3]) def TimeFromTicks(ticks): - return apply(Time, time.localtime(ticks)[3:6]) + return Time(*time.localtime(ticks)[3:6]) def TimestampFromTicks(ticks): - return apply(Timestamp, time.localtime(ticks)[:6]) + return Timestamp(*time.localtime(ticks)[:6]) version_info = tuple([int(x) for x in version.split(".")]) sqlite_version_info = tuple([int(x) for x in sqlite_version.split(".")]) Modified: python/branches/p3yk/Lib/sqlite3/test/userfunctions.py ============================================================================== --- python/branches/p3yk/Lib/sqlite3/test/userfunctions.py (original) +++ python/branches/p3yk/Lib/sqlite3/test/userfunctions.py Fri Aug 18 00:37:44 2006 @@ -280,7 +280,7 @@ cur.execute("select nostep(t) from test") self.fail("should have raised an AttributeError") except AttributeError, e: - self.failUnlessEqual(e.args[0], "AggrNoStep instance has no attribute 'step'") + self.failUnlessEqual(e.args[0], "'AggrNoStep' object has no attribute 'step'") def CheckAggrNoFinalize(self): cur = self.con.cursor() From python-3000-checkins at python.org Fri Aug 18 00:40:02 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Fri, 18 Aug 2006 00:40:02 +0200 (CEST) Subject: [Python-3000-checkins] r51347 - python/branches/p3yk/BROKEN Message-ID: <20060817224002.EE4F11E4004@bag.python.org> Author: guido.van.rossum Date: Fri Aug 18 00:40:02 2006 New Revision: 51347 Added: python/branches/p3yk/BROKEN (contents, props changed) Log: For posterity, here's a list of currently failing tests in py3k. Added: python/branches/p3yk/BROKEN ============================================================================== --- (empty file) +++ python/branches/p3yk/BROKEN Fri Aug 18 00:40:02 2006 @@ -0,0 +1,112 @@ +//////////////////////////////////////////////////////////////////////// +test_class +//////////////////////////////////////////////////////////////////////// + +test test_class failed -- hash(C1()) should raise +Also hash(C2()) +Also stack blowout, recursing between +#5921 0x0003868c in slot_tp_call (self=0x5b0c90, args=0x338030, kwds=0x0) at ../Objects/typeobject.c:4583 +#5922 0x00021124 in PyObject_Call (func=0x5b0c90, arg=0x3384c0, kw=0x134e10) at ../Objects/abstract.c:1791 + +//////////////////////////////////////////////////////////////////////// +test_minidom +//////////////////////////////////////////////////////////////////////// + +test test_minidom crashed -- : Error when calling the metaclass bases + Cannot create a consistent method resolution +order (MRO) for bases object, GetattrMagic + +//////////////////////////////////////////////////////////////////////// +test_xml_etree +//////////////////////////////////////////////////////////////////////// + +3 items had failures: + 18 of 32 in test.test_xml_etree.find + 1 of 3 in test.test_xml_etree.sanity + 8 of 12 in test.test_xml_etree.xinclude +***Test Failed*** 27 failures. +test test_xml_etree failed -- 27 of 91 doctests failed + +//////////////////////////////////////////////////////////////////////// +test_xml_etree_c +//////////////////////////////////////////////////////////////////////// + +********************************************************************** +File "/Users/guido/projects/python/py3k/Lib/test/test_xml_etree_c.py", line 112, in test.test_xml_etree_c.find +Failed example: + elem.find("section/tag").tag +Exception raised: + Traceback (most recent call last): + File "/Users/guido/projects/python/py3k/Lib/doctest.py", line 1207, in __run + compileflags, 1) in test.globs + File "", line 1, in + elem.find("section/tag").tag + AttributeError: 'NoneType' object has no attribute 'tag' + +//////////////////////////////////////////////////////////////////////// +test_descr +//////////////////////////////////////////////////////////////////////// + +Testing hash of mutable subclasses... +Traceback (most recent call last): + File "../Lib/test/test_descr.py", line 4096, in + test_main() + File "../Lib/test/test_descr.py", line 4059, in test_main + hashinherit() + File "../Lib/test/test_descr.py", line 3108, in hashinherit + raise TestFailed, "hash() of dict subclass should fail" +test.test_support.TestFailed: hash() of dict subclass should fail + +//////////////////////////////////////////////////////////////////////// +test_gc +//////////////////////////////////////////////////////////////////////// + +testing finalizers... restoring automatic collection +Traceback (most recent call last): + File "../Lib/test/test_gc.py", line 636, in + test() + File "../Lib/test/test_gc.py", line 623, in test + test_all() + File "../Lib/test/test_gc.py", line 586, in test_all + run_test("finalizers", test_finalizer) + File "../Lib/test/test_gc.py", line 18, in run_test + thunk() + File "../Lib/test/test_gc.py", line 125, in test_finalizer + raise TestFailed, "didn't find obj in garbage (finalizer)" +test.test_support.TestFailed: didn't find obj in garbage (finalizer) + +//////////////////////////////////////////////////////////////////////// +test_set +//////////////////////////////////////////////////////////////////////// + +====================================================================== +FAIL: test_contains (__main__.TestSetSubclass) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "../Lib/test/test_set.py", line 52, in test_contains + self.assert_(self.thetype(self.letters) in s) +AssertionError + +====================================================================== +FAIL: test_discard (__main__.TestSetSubclass) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "../Lib/test/test_set.py", line 302, in test_discard + self.assert_(self.thetype(self.word) in s) +AssertionError + +====================================================================== +FAIL: test_hash (__main__.TestSetSubclass) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "../Lib/test/test_set.py", line 265, in test_hash + self.assertRaises(TypeError, hash, self.s) +AssertionError: TypeError not raised + +====================================================================== +FAIL: test_remove (__main__.TestSetSubclass) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "../Lib/test/test_set.py", line 291, in test_remove + self.assert_(self.thetype(self.word) in s) +AssertionError From python-3000-checkins at python.org Fri Aug 18 01:09:58 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Fri, 18 Aug 2006 01:09:58 +0200 (CEST) Subject: [Python-3000-checkins] r51348 - python/branches/p3yk/Objects/typeobject.c Message-ID: <20060817230958.217241E4004@bag.python.org> Author: guido.van.rossum Date: Fri Aug 18 01:09:57 2006 New Revision: 51348 Modified: python/branches/p3yk/Objects/typeobject.c Log: Fix non-C89-compatible syntax. Modified: python/branches/p3yk/Objects/typeobject.c ============================================================================== --- python/branches/p3yk/Objects/typeobject.c (original) +++ python/branches/p3yk/Objects/typeobject.c Fri Aug 18 01:09:57 2006 @@ -4420,7 +4420,7 @@ static long slot_tp_hash(PyObject *self) { - PyObject *func; + PyObject *func, *res; static PyObject *hash_str; long h; @@ -4438,7 +4438,7 @@ return -1; } - PyObject *res = PyEval_CallObject(func, NULL); + res = PyEval_CallObject(func, NULL); Py_DECREF(func); if (res == NULL) return -1; From python-3000-checkins at python.org Fri Aug 18 01:29:09 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Fri, 18 Aug 2006 01:29:09 +0200 (CEST) Subject: [Python-3000-checkins] r51349 - python/branches/p3yk/Lib/bsddb/dbutils.py Message-ID: <20060817232909.7E1361E4004@bag.python.org> Author: guido.van.rossum Date: Fri Aug 18 01:29:08 2006 New Revision: 51349 Modified: python/branches/p3yk/Lib/bsddb/dbutils.py Log: Fix another relative import. Modified: python/branches/p3yk/Lib/bsddb/dbutils.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/dbutils.py (original) +++ python/branches/p3yk/Lib/bsddb/dbutils.py Fri Aug 18 01:29:08 2006 @@ -26,7 +26,7 @@ # from time import sleep as _sleep -import db +from . import db # always sleep at least N seconds between retrys _deadlock_MinSleepTime = 1.0/128 From python-3000-checkins at python.org Fri Aug 18 02:44:46 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Fri, 18 Aug 2006 02:44:46 +0200 (CEST) Subject: [Python-3000-checkins] r51350 - python/branches/p3yk/Lib/bsddb/dbobj.py Message-ID: <20060818004446.C6CD11E4004@bag.python.org> Author: guido.van.rossum Date: Fri Aug 18 02:44:46 2006 New Revision: 51350 Modified: python/branches/p3yk/Lib/bsddb/dbobj.py Log: Delete merge turd. Modified: python/branches/p3yk/Lib/bsddb/dbobj.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/dbobj.py (original) +++ python/branches/p3yk/Lib/bsddb/dbobj.py Fri Aug 18 02:44:46 2006 @@ -251,4 +251,3 @@ return apply(self._cobj.get_flags, args, kwargs) def get_range(self, *args, **kwargs): return apply(self._cobj.get_range, args, kwargs) ->>>>>>> .merge-right.r46752 From python-3000-checkins at python.org Fri Aug 18 03:37:38 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Fri, 18 Aug 2006 03:37:38 +0200 (CEST) Subject: [Python-3000-checkins] r51351 - python/branches/p3yk/Lib/bsddb/dbobj.py Message-ID: <20060818013738.AC9D01E4005@bag.python.org> Author: guido.van.rossum Date: Fri Aug 18 03:37:37 2006 New Revision: 51351 Modified: python/branches/p3yk/Lib/bsddb/dbobj.py Log: Get rid of the apply() calls here, to make the unit test pass. Modified: python/branches/p3yk/Lib/bsddb/dbobj.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/dbobj.py (original) +++ python/branches/p3yk/Lib/bsddb/dbobj.py Fri Aug 18 03:37:37 2006 @@ -97,7 +97,7 @@ if db.version() >= (4,0): def log_stat(self, *args, **kwargs): - return apply(self._cobj.log_stat, args, kwargs) + return self._cobj.log_stat(*args, **kwargs) if db.version() >= (4,1): def dbremove(self, *args, **kwargs): @@ -109,7 +109,7 @@ if db.version() >= (4,4): def lsn_reset(self, *args, **kwargs): - return apply(self._cobj.lsn_reset, args, kwargs) + return self._cobj.lsn_reset(*args, **kwargs) class DB(DictMixin): @@ -221,33 +221,33 @@ class DBSequence: def __init__(self, *args, **kwargs): - self._cobj = apply(db.DBSequence, args, kwargs) + self._cobj = db.DBSequence(*args, **kwargs) def close(self, *args, **kwargs): - return apply(self._cobj.close, args, kwargs) + return self._cobj.close(*args, **kwargs) def get(self, *args, **kwargs): - return apply(self._cobj.get, args, kwargs) + return self._cobj.get(*args, **kwargs) def get_dbp(self, *args, **kwargs): - return apply(self._cobj.get_dbp, args, kwargs) + return self._cobj.get_dbp(*args, **kwargs) def get_key(self, *args, **kwargs): - return apply(self._cobj.get_key, args, kwargs) + return self._cobj.get_key(*args, **kwargs) def init_value(self, *args, **kwargs): - return apply(self._cobj.init_value, args, kwargs) + return self._cobj.init_value(*args, **kwargs) def open(self, *args, **kwargs): - return apply(self._cobj.open, args, kwargs) + return self._cobj.open(*args, **kwargs) def remove(self, *args, **kwargs): - return apply(self._cobj.remove, args, kwargs) + return self._cobj.remove(*args, **kwargs) def stat(self, *args, **kwargs): - return apply(self._cobj.stat, args, kwargs) + return self._cobj.stat(*args, **kwargs) def set_cachesize(self, *args, **kwargs): - return apply(self._cobj.set_cachesize, args, kwargs) + return self._cobj.set_cachesize(*args, **kwargs) def set_flags(self, *args, **kwargs): - return apply(self._cobj.set_flags, args, kwargs) + return self._cobj.set_flags(*args, **kwargs) def set_range(self, *args, **kwargs): - return apply(self._cobj.set_range, args, kwargs) + return self._cobj.set_range(*args, **kwargs) def get_cachesize(self, *args, **kwargs): - return apply(self._cobj.get_cachesize, args, kwargs) + return self._cobj.get_cachesize(*args, **kwargs) def get_flags(self, *args, **kwargs): - return apply(self._cobj.get_flags, args, kwargs) + return self._cobj.get_flags(*args, **kwargs) def get_range(self, *args, **kwargs): - return apply(self._cobj.get_range, args, kwargs) + return self._cobj.get_range(*args, **kwargs) From python-3000-checkins at python.org Fri Aug 18 03:39:55 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Fri, 18 Aug 2006 03:39:55 +0200 (CEST) Subject: [Python-3000-checkins] r51352 - python/branches/p3yk/Lib/test/regrtest.py Message-ID: <20060818013955.034931E4004@bag.python.org> Author: guido.van.rossum Date: Fri Aug 18 03:39:54 2006 New Revision: 51352 Modified: python/branches/p3yk/Lib/test/regrtest.py Log: test_bsddb runs fine on darwin. Modified: python/branches/p3yk/Lib/test/regrtest.py ============================================================================== --- python/branches/p3yk/Lib/test/regrtest.py (original) +++ python/branches/p3yk/Lib/test/regrtest.py Fri Aug 18 03:39:54 2006 @@ -1034,7 +1034,6 @@ 'darwin': """ test_al - test_bsddb test_bsddb3 test_cd test_cl From python-3000-checkins at python.org Fri Aug 18 18:29:55 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Fri, 18 Aug 2006 18:29:55 +0200 (CEST) Subject: [Python-3000-checkins] r51388 - in python/branches/p3yk: Lib/test/test_long.py Objects/longobject.c Message-ID: <20060818162955.4E3FD1E4005@bag.python.org> Author: guido.van.rossum Date: Fri Aug 18 18:29:54 2006 New Revision: 51388 Modified: python/branches/p3yk/Lib/test/test_long.py python/branches/p3yk/Objects/longobject.c Log: repr() of a long int no longer produces a trailing 'L'. More unit tests probably need fixing; later... Modified: python/branches/p3yk/Lib/test/test_long.py ============================================================================== --- python/branches/p3yk/Lib/test/test_long.py (original) +++ python/branches/p3yk/Lib/test/test_long.py Fri Aug 18 18:29:54 2006 @@ -196,7 +196,7 @@ def slow_format(self, x, base): if (x, base) == (0, 8): # this is an oddball! - return "0L" + return "0" digits = [] sign = 0 if x < 0: @@ -208,7 +208,7 @@ digits = digits or [0] return '-'[:sign] + \ {8: '0', 10: '', 16: '0x'}[base] + \ - "".join(map(lambda i: "0123456789abcdef"[i], digits)) + "L" + "".join(map(lambda i: "0123456789abcdef"[i], digits)) def check_format_1(self, x): for base, mapper in (8, oct), (10, repr), (16, hex): @@ -221,7 +221,7 @@ # str() has to be checked a little differently since there's no # trailing "L" got = str(x) - expected = self.slow_format(x, 10)[:-1] + expected = self.slow_format(x, 10) msg = Frm("%s returned %r but expected %r for %r", mapper.__name__, got, expected, x) self.assertEqual(got, expected, msg) Modified: python/branches/p3yk/Objects/longobject.c ============================================================================== --- python/branches/p3yk/Objects/longobject.c (original) +++ python/branches/p3yk/Objects/longobject.c Fri Aug 18 18:29:54 2006 @@ -35,7 +35,7 @@ static PyLongObject *mul1(PyLongObject *, wdigit); static PyLongObject *muladd1(PyLongObject *, wdigit, wdigit); static PyLongObject *divrem1(PyLongObject *, digit, digit *); -static PyObject *long_format(PyObject *aa, int base, int addL); +static PyObject *long_format(PyObject *aa, int base); #define SIGCHECK(PyTryBlock) \ if (--_Py_Ticker < 0) { \ @@ -1198,7 +1198,7 @@ If base is 8 or 16, add the proper prefix '0' or '0x'. */ static PyObject * -long_format(PyObject *aa, int base, int addL) +long_format(PyObject *aa, int base) { register PyLongObject *a = (PyLongObject *)aa; PyStringObject *str; @@ -1222,14 +1222,12 @@ ++bits; i >>= 1; } - i = 5 + (addL ? 1 : 0) + (size_a*SHIFT + bits-1) / bits; + i = 5 + (size_a*SHIFT + bits-1) / bits; str = (PyStringObject *) PyString_FromStringAndSize((char *)0, i); if (str == NULL) return NULL; p = PyString_AS_STRING(str) + i; *p = '\0'; - if (addL) - *--p = 'L'; if (a->ob_size < 0) sign = '-'; @@ -1890,13 +1888,7 @@ static PyObject * long_repr(PyObject *v) { - return long_format(v, 10, 1); -} - -static PyObject * -long_str(PyObject *v) -{ - return long_format(v, 10, 0); + return long_format(v, 10); } static int @@ -3255,13 +3247,13 @@ static PyObject * long_oct(PyObject *v) { - return long_format(v, 8, 1); + return long_format(v, 8); } static PyObject * long_hex(PyObject *v) { - return long_format(v, 16, 1); + return long_format(v, 16); } static PyObject * @@ -3407,7 +3399,7 @@ 0, /* tp_as_mapping */ (hashfunc)long_hash, /* tp_hash */ 0, /* tp_call */ - long_str, /* tp_str */ + 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ From python-3000-checkins at python.org Sat Aug 19 00:13:16 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sat, 19 Aug 2006 00:13:16 +0200 (CEST) Subject: [Python-3000-checkins] r51390 - in python/branches/p3yk: Include/abstract.h Lib/DocXMLRPCServer.py Lib/SimpleXMLRPCServer.py Lib/UserDict.py Lib/asyncore.py Lib/bdb.py Lib/bsddb/__init__.py Lib/bsddb/dbobj.py Lib/bsddb/dbshelve.py Lib/bsddb/dbutils.py Lib/bsddb/test/test_all.py Lib/bsddb/test/test_associate.py Lib/bsddb/test/test_basics.py Lib/bsddb/test/test_compare.py Lib/bsddb/test/test_compat.py Lib/bsddb/test/test_dbshelve.py Lib/bsddb/test/test_dbtables.py Lib/bsddb/test/test_env_close.py Lib/bsddb/test/test_get_none.py Lib/bsddb/test/test_join.py Lib/bsddb/test/test_lock.py Lib/bsddb/test/test_queue.py Lib/bsddb/test/test_recno.py Lib/bsddb/test/test_sequence.py Lib/bsddb/test/test_thread.py Lib/cgi.py Lib/difflib.py Lib/distutils/archive_util.py Lib/distutils/ccompiler.py Lib/distutils/command/build_ext.py Lib/distutils/core.py Lib/distutils/dist.py Lib/distutils/fancy_getopt.py Lib/distutils/sysconfig.py Lib/distutils/text_file.py Lib/distutils/util.py Lib/dumbdbm.py Lib/mailbox.py Lib/modulefinder.py Lib/optparse.py Lib/os.py Lib/pickle.py Lib/pickletools.py Lib/platform.py Lib/profile.py Lib/pstats.py Lib/rfc822.py Lib/sets.py Lib/shelve.py Lib/test/mapping_tests.py Lib/test/regrtest.py Lib/test/test___all__.py Lib/test/test_bool.py Lib/test/test_bsddb.py Lib/test/test_builtin.py Lib/test/test_call.py Lib/test/test_cgi.py Lib/test/test_dbm.py Lib/test/test_dict.py Lib/test/test_gdbm.py Lib/test/test_grammar.py Lib/test/test_mailbox.py Lib/test/test_multibytecodec_support.py Lib/test/test_operations.py Lib/test/test_pkgimport.py Lib/test/test_pyclbr.py Lib/test/test_rfc822.py Lib/test/test_sax.py Lib/test/test_scope.py Lib/test/test_site.py Lib/test/test_struct.py Lib/test/test_time.py Lib/test/test_urllib2.py Lib/test/test_userdict.py Lib/test/test_weakref.py Lib/test/test_wsgiref.py Lib/trace.py Lib/unittest.py Lib/urllib.py Lib/urllib2.py Lib/weakref.py Lib/wsgiref/handlers.py Lib/wsgiref/headers.py Lib/wsgiref/util.py Lib/wsgiref/validate.py Lib/xmlrpclib.py Modules/bsddbmodule.c Modules/dbmmodule.c Modules/gdbmmodule.c Objects/descrobject.c Objects/dictobject.c Objects/typeobject.c setup.py Message-ID: <20060818221316.E8E711E4004@bag.python.org> Author: guido.van.rossum Date: Sat Aug 19 00:13:04 2006 New Revision: 51390 Modified: python/branches/p3yk/Include/abstract.h python/branches/p3yk/Lib/DocXMLRPCServer.py python/branches/p3yk/Lib/SimpleXMLRPCServer.py python/branches/p3yk/Lib/UserDict.py python/branches/p3yk/Lib/asyncore.py python/branches/p3yk/Lib/bdb.py python/branches/p3yk/Lib/bsddb/__init__.py python/branches/p3yk/Lib/bsddb/dbobj.py python/branches/p3yk/Lib/bsddb/dbshelve.py python/branches/p3yk/Lib/bsddb/dbutils.py python/branches/p3yk/Lib/bsddb/test/test_all.py python/branches/p3yk/Lib/bsddb/test/test_associate.py python/branches/p3yk/Lib/bsddb/test/test_basics.py python/branches/p3yk/Lib/bsddb/test/test_compare.py python/branches/p3yk/Lib/bsddb/test/test_compat.py python/branches/p3yk/Lib/bsddb/test/test_dbshelve.py python/branches/p3yk/Lib/bsddb/test/test_dbtables.py python/branches/p3yk/Lib/bsddb/test/test_env_close.py python/branches/p3yk/Lib/bsddb/test/test_get_none.py python/branches/p3yk/Lib/bsddb/test/test_join.py python/branches/p3yk/Lib/bsddb/test/test_lock.py python/branches/p3yk/Lib/bsddb/test/test_queue.py python/branches/p3yk/Lib/bsddb/test/test_recno.py python/branches/p3yk/Lib/bsddb/test/test_sequence.py python/branches/p3yk/Lib/bsddb/test/test_thread.py python/branches/p3yk/Lib/cgi.py python/branches/p3yk/Lib/difflib.py python/branches/p3yk/Lib/distutils/archive_util.py python/branches/p3yk/Lib/distutils/ccompiler.py python/branches/p3yk/Lib/distutils/command/build_ext.py python/branches/p3yk/Lib/distutils/core.py python/branches/p3yk/Lib/distutils/dist.py python/branches/p3yk/Lib/distutils/fancy_getopt.py python/branches/p3yk/Lib/distutils/sysconfig.py python/branches/p3yk/Lib/distutils/text_file.py python/branches/p3yk/Lib/distutils/util.py python/branches/p3yk/Lib/dumbdbm.py python/branches/p3yk/Lib/mailbox.py python/branches/p3yk/Lib/modulefinder.py python/branches/p3yk/Lib/optparse.py python/branches/p3yk/Lib/os.py python/branches/p3yk/Lib/pickle.py python/branches/p3yk/Lib/pickletools.py python/branches/p3yk/Lib/platform.py python/branches/p3yk/Lib/profile.py python/branches/p3yk/Lib/pstats.py python/branches/p3yk/Lib/rfc822.py python/branches/p3yk/Lib/sets.py python/branches/p3yk/Lib/shelve.py python/branches/p3yk/Lib/test/mapping_tests.py python/branches/p3yk/Lib/test/regrtest.py python/branches/p3yk/Lib/test/test___all__.py python/branches/p3yk/Lib/test/test_bool.py python/branches/p3yk/Lib/test/test_bsddb.py python/branches/p3yk/Lib/test/test_builtin.py python/branches/p3yk/Lib/test/test_call.py python/branches/p3yk/Lib/test/test_cgi.py python/branches/p3yk/Lib/test/test_dbm.py python/branches/p3yk/Lib/test/test_dict.py python/branches/p3yk/Lib/test/test_gdbm.py python/branches/p3yk/Lib/test/test_grammar.py python/branches/p3yk/Lib/test/test_mailbox.py python/branches/p3yk/Lib/test/test_multibytecodec_support.py python/branches/p3yk/Lib/test/test_operations.py python/branches/p3yk/Lib/test/test_pkgimport.py python/branches/p3yk/Lib/test/test_pyclbr.py python/branches/p3yk/Lib/test/test_rfc822.py python/branches/p3yk/Lib/test/test_sax.py python/branches/p3yk/Lib/test/test_scope.py python/branches/p3yk/Lib/test/test_site.py python/branches/p3yk/Lib/test/test_struct.py python/branches/p3yk/Lib/test/test_time.py python/branches/p3yk/Lib/test/test_urllib2.py python/branches/p3yk/Lib/test/test_userdict.py python/branches/p3yk/Lib/test/test_weakref.py python/branches/p3yk/Lib/test/test_wsgiref.py python/branches/p3yk/Lib/trace.py python/branches/p3yk/Lib/unittest.py python/branches/p3yk/Lib/urllib.py python/branches/p3yk/Lib/urllib2.py python/branches/p3yk/Lib/weakref.py python/branches/p3yk/Lib/wsgiref/handlers.py python/branches/p3yk/Lib/wsgiref/headers.py python/branches/p3yk/Lib/wsgiref/util.py python/branches/p3yk/Lib/wsgiref/validate.py python/branches/p3yk/Lib/xmlrpclib.py python/branches/p3yk/Modules/bsddbmodule.c python/branches/p3yk/Modules/dbmmodule.c python/branches/p3yk/Modules/gdbmmodule.c python/branches/p3yk/Objects/descrobject.c python/branches/p3yk/Objects/dictobject.c python/branches/p3yk/Objects/typeobject.c python/branches/p3yk/setup.py Log: Get rid of dict.has_key(). Boy this has a lot of repercussions! Not all code has been fixed yet; this is just a checkpoint... The C API still has PyDict_HasKey() and _HasKeyString(); not sure if I want to change those just yet. Modified: python/branches/p3yk/Include/abstract.h ============================================================================== --- python/branches/p3yk/Include/abstract.h (original) +++ python/branches/p3yk/Include/abstract.h Sat Aug 19 00:13:04 2006 @@ -1115,7 +1115,7 @@ /* On success, return 1 if the mapping object has the key, key, and 0 otherwise. This is equivalent to the Python expression: - o.has_key(key). + key in o. This function always succeeds. */ @@ -1125,7 +1125,7 @@ /* Return 1 if the mapping object has the key, key, and 0 otherwise. This is equivalent to the Python expression: - o.has_key(key). + key in o. This function always succeeds. Modified: python/branches/p3yk/Lib/DocXMLRPCServer.py ============================================================================== --- python/branches/p3yk/Lib/DocXMLRPCServer.py (original) +++ python/branches/p3yk/Lib/DocXMLRPCServer.py Sat Aug 19 00:13:04 2006 @@ -174,7 +174,7 @@ methods = {} for method_name in self.system_listMethods(): - if self.funcs.has_key(method_name): + if method_name in self.funcs: method = self.funcs[method_name] elif self.instance is not None: method_info = [None, None] # argspec, documentation Modified: python/branches/p3yk/Lib/SimpleXMLRPCServer.py ============================================================================== --- python/branches/p3yk/Lib/SimpleXMLRPCServer.py (original) +++ python/branches/p3yk/Lib/SimpleXMLRPCServer.py Sat Aug 19 00:13:04 2006 @@ -313,7 +313,7 @@ Returns a string containing documentation for the specified method.""" method = None - if self.funcs.has_key(method_name): + if method_name in self.funcs: method = self.funcs[method_name] elif self.instance is not None: # Instance can implement _methodHelp to return help for a method Modified: python/branches/p3yk/Lib/UserDict.py ============================================================================== --- python/branches/p3yk/Lib/UserDict.py (original) +++ python/branches/p3yk/Lib/UserDict.py Sat Aug 19 00:13:04 2006 @@ -41,7 +41,6 @@ def iterkeys(self): return self.data.iterkeys() def itervalues(self): return self.data.itervalues() def values(self): return self.data.values() - def has_key(self, key): return self.data.has_key(key) def update(self, dict=None, **kwargs): if dict is None: pass @@ -55,11 +54,11 @@ if len(kwargs): self.data.update(kwargs) def get(self, key, failobj=None): - if not self.has_key(key): + if key not in self: return failobj return self[key] def setdefault(self, key, failobj=None): - if not self.has_key(key): + if key not in self: self[key] = failobj return self[key] def pop(self, key, *args): @@ -91,14 +90,12 @@ def __iter__(self): for k in self.keys(): yield k - def has_key(self, key): + def __contains__(self, key): try: value = self[key] except KeyError: return False return True - def __contains__(self, key): - return self.has_key(key) # third level takes advantage of second level definitions def iteritems(self): Modified: python/branches/p3yk/Lib/asyncore.py ============================================================================== --- python/branches/p3yk/Lib/asyncore.py (original) +++ python/branches/p3yk/Lib/asyncore.py Sat Aug 19 00:13:04 2006 @@ -247,7 +247,7 @@ fd = self._fileno if map is None: map = self._map - if map.has_key(fd): + if fd in map: #self.log_info('closing channel %d:%s' % (fd, self)) del map[fd] self._fileno = None Modified: python/branches/p3yk/Lib/bdb.py ============================================================================== --- python/branches/p3yk/Lib/bdb.py (original) +++ python/branches/p3yk/Lib/bdb.py Sat Aug 19 00:13:04 2006 @@ -133,8 +133,7 @@ raise NotImplementedError, "subclass of bdb must implement do_clear()" def break_anywhere(self, frame): - return self.breaks.has_key( - self.canonic(frame.f_code.co_filename)) + return self.canonic(frame.f_code.co_filename) in self.breaks # Derived classes should override the user_* methods # to gain control. @@ -245,7 +244,7 @@ # pair, then remove the breaks entry for bp in Breakpoint.bplist[filename, lineno][:]: bp.deleteMe() - if not Breakpoint.bplist.has_key((filename, lineno)): + if (filename, lineno) not in Breakpoint.bplist: self.breaks[filename].remove(lineno) if not self.breaks[filename]: del self.breaks[filename] @@ -453,7 +452,7 @@ Breakpoint.next = Breakpoint.next + 1 # Build the two lists self.bpbynumber.append(self) - if self.bplist.has_key((file, line)): + if (file, line) in self.bplist: self.bplist[file, line].append(self) else: self.bplist[file, line] = [self] Modified: python/branches/p3yk/Lib/bsddb/__init__.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/__init__.py (original) +++ python/branches/p3yk/Lib/bsddb/__init__.py Sat Aug 19 00:13:04 2006 @@ -255,6 +255,8 @@ self._checkOpen() return _DeadlockWrap(self.db.has_key, key) + __contains__ = has_key + def set_location(self, key): self._checkOpen() self._checkCursor() Modified: python/branches/p3yk/Lib/bsddb/dbobj.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/dbobj.py (original) +++ python/branches/p3yk/Lib/bsddb/dbobj.py Sat Aug 19 00:13:04 2006 @@ -21,7 +21,7 @@ # added to _bsddb.c. # -import db +from . import db try: from UserDict import DictMixin @@ -161,6 +161,8 @@ return self._cobj.key_range(*args, **kwargs) def has_key(self, *args, **kwargs): return self._cobj.has_key(*args, **kwargs) + def __contains__(self, key): + return self._cobj.has_key(key) def items(self, *args, **kwargs): return self._cobj.items(*args, **kwargs) def keys(self, *args, **kwargs): Modified: python/branches/p3yk/Lib/bsddb/dbshelve.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/dbshelve.py (original) +++ python/branches/p3yk/Lib/bsddb/dbshelve.py Sat Aug 19 00:13:04 2006 @@ -35,7 +35,7 @@ except ImportError: # DictMixin is new in Python 2.3 class DictMixin: pass -import db +from . import db #------------------------------------------------------------------------ @@ -197,6 +197,10 @@ raise NotImplementedError + def __contains__(self, key): + return self.has_key(key) + + #---------------------------------------------- # Methods allowed to pass-through to self.db # Modified: python/branches/p3yk/Lib/bsddb/dbutils.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/dbutils.py (original) +++ python/branches/p3yk/Lib/bsddb/dbutils.py Sat Aug 19 00:13:04 2006 @@ -55,7 +55,7 @@ """ sleeptime = _deadlock_MinSleepTime max_retries = _kwargs.get('max_retries', -1) - if _kwargs.has_key('max_retries'): + if 'max_tries' in _kwargs: del _kwargs['max_retries'] while True: try: Modified: python/branches/p3yk/Lib/bsddb/test/test_all.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_all.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_all.py Sat Aug 19 00:13:04 2006 @@ -41,8 +41,12 @@ # This little hack is for when this module is run as main and all the # other modules import it so they will still be able to get the right # verbose setting. It's confusing but it works. -import test_all -test_all.verbose = verbose +try: + import test_all +except ImportError: + pass +else: + test_all.verbose = verbose def suite(): Modified: python/branches/p3yk/Lib/bsddb/test/test_associate.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_associate.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_associate.py Sat Aug 19 00:13:04 2006 @@ -14,7 +14,7 @@ have_threads = 0 import unittest -from test_all import verbose +from .test_all import verbose try: # For Pythons w/distutils pybsddb Modified: python/branches/p3yk/Lib/bsddb/test/test_basics.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_basics.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_basics.py Sat Aug 19 00:13:04 2006 @@ -20,7 +20,7 @@ # For Python 2.3 from bsddb import db -from test_all import verbose +from .test_all import verbose DASH = '-' Modified: python/branches/p3yk/Lib/bsddb/test/test_compare.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_compare.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_compare.py Sat Aug 19 00:13:04 2006 @@ -3,9 +3,10 @@ """ import sys, os, re -import test_all from cStringIO import StringIO +from . import test_all + import unittest try: # For Pythons w/distutils pybsddb Modified: python/branches/p3yk/Lib/bsddb/test/test_compat.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_compat.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_compat.py Sat Aug 19 00:13:04 2006 @@ -7,7 +7,7 @@ import unittest import tempfile -from test_all import verbose +from .test_all import verbose try: # For Pythons w/distutils pybsddb Modified: python/branches/p3yk/Lib/bsddb/test/test_dbshelve.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_dbshelve.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_dbshelve.py Sat Aug 19 00:13:04 2006 @@ -15,7 +15,7 @@ # For Python 2.3 from bsddb import db, dbshelve -from test_all import verbose +from .test_all import verbose #---------------------------------------------------------------------- Modified: python/branches/p3yk/Lib/bsddb/test/test_dbtables.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_dbtables.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_dbtables.py Sat Aug 19 00:13:04 2006 @@ -28,7 +28,7 @@ import pickle import unittest -from test_all import verbose +from .test_all import verbose try: # For Pythons w/distutils pybsddb Modified: python/branches/p3yk/Lib/bsddb/test/test_env_close.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_env_close.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_env_close.py Sat Aug 19 00:13:04 2006 @@ -15,7 +15,7 @@ # For Python 2.3 from bsddb import db -from test_all import verbose +from .test_all import verbose # We're going to get warnings in this module about trying to close the db when # its env is already closed. Let's just ignore those. Modified: python/branches/p3yk/Lib/bsddb/test/test_get_none.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_get_none.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_get_none.py Sat Aug 19 00:13:04 2006 @@ -14,7 +14,7 @@ # For Python 2.3 from bsddb import db -from test_all import verbose +from .test_all import verbose #---------------------------------------------------------------------- Modified: python/branches/p3yk/Lib/bsddb/test/test_join.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_join.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_join.py Sat Aug 19 00:13:04 2006 @@ -13,7 +13,7 @@ have_threads = 0 import unittest -from test_all import verbose +from .test_all import verbose try: # For Pythons w/distutils pybsddb Modified: python/branches/p3yk/Lib/bsddb/test/test_lock.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_lock.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_lock.py Sat Aug 19 00:13:04 2006 @@ -15,7 +15,7 @@ import unittest -from test_all import verbose +from .test_all import verbose try: # For Pythons w/distutils pybsddb Modified: python/branches/p3yk/Lib/bsddb/test/test_queue.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_queue.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_queue.py Sat Aug 19 00:13:04 2006 @@ -14,7 +14,7 @@ # For Python 2.3 from bsddb import db -from test_all import verbose +from .test_all import verbose #---------------------------------------------------------------------- Modified: python/branches/p3yk/Lib/bsddb/test/test_recno.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_recno.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_recno.py Sat Aug 19 00:13:04 2006 @@ -8,7 +8,7 @@ from pprint import pprint import unittest -from test_all import verbose +from .test_all import verbose try: # For Pythons w/distutils pybsddb Modified: python/branches/p3yk/Lib/bsddb/test/test_sequence.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_sequence.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_sequence.py Sat Aug 19 00:13:04 2006 @@ -10,7 +10,7 @@ except ImportError: from bsddb import db -from test_all import verbose +from .test_all import verbose class DBSequenceTest(unittest.TestCase): Modified: python/branches/p3yk/Lib/bsddb/test/test_thread.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_thread.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_thread.py Sat Aug 19 00:13:04 2006 @@ -31,7 +31,7 @@ pass import unittest -from test_all import verbose +from .test_all import verbose try: # For Pythons w/distutils pybsddb Modified: python/branches/p3yk/Lib/cgi.py ============================================================================== --- python/branches/p3yk/Lib/cgi.py (original) +++ python/branches/p3yk/Lib/cgi.py Sat Aug 19 00:13:04 2006 @@ -608,14 +608,6 @@ if item.name not in keys: keys.append(item.name) return keys - def has_key(self, key): - """Dictionary style has_key() method.""" - if self.list is None: - raise TypeError, "not indexable" - for item in self.list: - if item.name == key: return True - return False - def __contains__(self, key): """Dictionary style __contains__ method.""" if self.list is None: Modified: python/branches/p3yk/Lib/difflib.py ============================================================================== --- python/branches/p3yk/Lib/difflib.py (original) +++ python/branches/p3yk/Lib/difflib.py Sat Aug 19 00:13:04 2006 @@ -199,7 +199,7 @@ # DON'T USE! Only __chain_b uses this. Use isbjunk. # isbjunk # for x in b, isbjunk(x) == isjunk(x) but much faster; - # it's really the has_key method of a hidden dict. + # it's really the __contains__ method of a hidden dict. # DOES NOT WORK for x in a! # isbpopular # for x in b, isbpopular(x) is true iff b is reasonably long @@ -341,8 +341,8 @@ # lot of junk in the sequence, the number of *unique* junk # elements is probably small. So the memory burden of keeping # this dict alive is likely trivial compared to the size of b2j. - self.isbjunk = junkdict.has_key - self.isbpopular = populardict.has_key + self.isbjunk = junkdict.__contains__ + self.isbpopular = populardict.__contains__ def find_longest_match(self, alo, ahi, blo, bhi): """Find longest matching block in a[alo:ahi] and b[blo:bhi]. @@ -674,7 +674,7 @@ # avail[x] is the number of times x appears in 'b' less the # number of times we've seen it in 'a' so far ... kinda avail = {} - availhas, matches = avail.has_key, 0 + availhas, matches = avail.__contains__, 0 for elt in self.a: if availhas(elt): numb = avail[elt] Modified: python/branches/p3yk/Lib/distutils/archive_util.py ============================================================================== --- python/branches/p3yk/Lib/distutils/archive_util.py (original) +++ python/branches/p3yk/Lib/distutils/archive_util.py Sat Aug 19 00:13:04 2006 @@ -124,7 +124,7 @@ def check_archive_formats (formats): for format in formats: - if not ARCHIVE_FORMATS.has_key(format): + if format not in ARCHIVE_FORMATS: return format else: return None Modified: python/branches/p3yk/Lib/distutils/ccompiler.py ============================================================================== --- python/branches/p3yk/Lib/distutils/ccompiler.py (original) +++ python/branches/p3yk/Lib/distutils/ccompiler.py Sat Aug 19 00:13:04 2006 @@ -159,7 +159,7 @@ # basically the same things with Unix C compilers. for key in args.keys(): - if not self.executables.has_key(key): + if key not in self.executables: raise ValueError, \ "unknown executable '%s' for class %s" % \ (key, self.__class__.__name__) Modified: python/branches/p3yk/Lib/distutils/command/build_ext.py ============================================================================== --- python/branches/p3yk/Lib/distutils/command/build_ext.py (original) +++ python/branches/p3yk/Lib/distutils/command/build_ext.py Sat Aug 19 00:13:04 2006 @@ -341,7 +341,7 @@ # Medium-easy stuff: same syntax/semantics, different names. ext.runtime_library_dirs = build_info.get('rpath') - if build_info.has_key('def_file'): + if 'def_file' in build_info: log.warn("'def_file' element of build info dict " "no longer supported") Modified: python/branches/p3yk/Lib/distutils/core.py ============================================================================== --- python/branches/p3yk/Lib/distutils/core.py (original) +++ python/branches/p3yk/Lib/distutils/core.py Sat Aug 19 00:13:04 2006 @@ -101,9 +101,9 @@ else: klass = Distribution - if not attrs.has_key('script_name'): + if 'script_name' not in attrs: attrs['script_name'] = os.path.basename(sys.argv[0]) - if not attrs.has_key('script_args'): + if 'script_args' not in attrs: attrs['script_args'] = sys.argv[1:] # Create the Distribution instance, using the remaining arguments @@ -111,7 +111,7 @@ try: _setup_distribution = dist = klass(attrs) except DistutilsSetupError, msg: - if attrs.has_key('name'): + if 'name' not in attrs: raise SystemExit, "error in %s setup command: %s" % \ (attrs['name'], msg) else: Modified: python/branches/p3yk/Lib/distutils/dist.py ============================================================================== --- python/branches/p3yk/Lib/distutils/dist.py (original) +++ python/branches/p3yk/Lib/distutils/dist.py Sat Aug 19 00:13:04 2006 @@ -239,7 +239,7 @@ for (opt, val) in cmd_options.items(): opt_dict[opt] = ("setup script", val) - if attrs.has_key('licence'): + if 'licence' in attrs: attrs['license'] = attrs['licence'] del attrs['licence'] msg = "'licence' distribution option is deprecated; use 'license'" @@ -343,7 +343,7 @@ user_filename = "pydistutils.cfg" # And look for the user config file - if os.environ.has_key('HOME'): + if 'HOME' in os.environ: user_file = os.path.join(os.environ.get('HOME'), user_filename) if os.path.isfile(user_file): files.append(user_file) @@ -388,7 +388,7 @@ # If there was a "global" section in the config file, use it # to set Distribution options. - if self.command_options.has_key('global'): + if 'global' in self.command_options: for (opt, (src, val)) in self.command_options['global'].items(): alias = self.negative_opt.get(opt) try: @@ -907,7 +907,7 @@ try: is_string = type(value) is StringType - if neg_opt.has_key(option) and is_string: + if option in neg_opt and is_string: setattr(command_obj, neg_opt[option], not strtobool(value)) elif option in bool_opts and is_string: setattr(command_obj, option, strtobool(value)) Modified: python/branches/p3yk/Lib/distutils/fancy_getopt.py ============================================================================== --- python/branches/p3yk/Lib/distutils/fancy_getopt.py (original) +++ python/branches/p3yk/Lib/distutils/fancy_getopt.py Sat Aug 19 00:13:04 2006 @@ -97,7 +97,7 @@ self._build_index() def add_option (self, long_option, short_option=None, help_string=None): - if self.option_index.has_key(long_option): + if long_option in self.option_index: raise DistutilsGetoptError, \ "option conflict: already an option '%s'" % long_option else: @@ -109,7 +109,7 @@ def has_option (self, long_option): """Return true if the option table for this parser has an option with long name 'long_option'.""" - return self.option_index.has_key(long_option) + return long_option in self.option_index def get_attr_name (self, long_option): """Translate long option name 'long_option' to the form it @@ -121,11 +121,11 @@ def _check_alias_dict (self, aliases, what): assert type(aliases) is DictionaryType for (alias, opt) in aliases.items(): - if not self.option_index.has_key(alias): + if alias not in self.option_index: raise DistutilsGetoptError, \ ("invalid %s '%s': " "option '%s' not defined") % (what, alias, alias) - if not self.option_index.has_key(opt): + if opt not in self.option_index: raise DistutilsGetoptError, \ ("invalid %s '%s': " "aliased option '%s' not defined") % (what, alias, opt) Modified: python/branches/p3yk/Lib/distutils/sysconfig.py ============================================================================== --- python/branches/p3yk/Lib/distutils/sysconfig.py (original) +++ python/branches/p3yk/Lib/distutils/sysconfig.py Sat Aug 19 00:13:04 2006 @@ -150,22 +150,22 @@ get_config_vars('CC', 'CXX', 'OPT', 'CFLAGS', 'CCSHARED', 'LDSHARED', 'SO') - if os.environ.has_key('CC'): + if 'CC' in os.environ: cc = os.environ['CC'] - if os.environ.has_key('CXX'): + if 'CXX' in os.environ: cxx = os.environ['CXX'] - if os.environ.has_key('LDSHARED'): + if 'LDSHARED' in os.environ: ldshared = os.environ['LDSHARED'] - if os.environ.has_key('CPP'): + if 'CPP' in os.environ: cpp = os.environ['CPP'] else: cpp = cc + " -E" # not always - if os.environ.has_key('LDFLAGS'): + if 'LDFLAGS' in os.environ: ldshared = ldshared + ' ' + os.environ['LDFLAGS'] - if os.environ.has_key('CFLAGS'): + if 'CFLAGS' in os.environ: cflags = opt + ' ' + os.environ['CFLAGS'] ldshared = ldshared + ' ' + os.environ['CFLAGS'] - if os.environ.has_key('CPPFLAGS'): + if 'CPPFLAGS' in os.environ: cpp = cpp + ' ' + os.environ['CPPFLAGS'] cflags = cflags + ' ' + os.environ['CPPFLAGS'] ldshared = ldshared + ' ' + os.environ['CPPFLAGS'] @@ -277,12 +277,12 @@ if m: n = m.group(1) found = True - if done.has_key(n): + if n in done: item = str(done[n]) - elif notdone.has_key(n): + elif n in notdone: # get it on a subsequent round found = False - elif os.environ.has_key(n): + elif n in os.environ: # do it like make: fall back to environment item = os.environ[n] else: @@ -366,7 +366,7 @@ # MACOSX_DEPLOYMENT_TARGET: configure bases some choices on it so # it needs to be compatible. # If it isn't set we set it to the configure-time value - if sys.platform == 'darwin' and g.has_key('MACOSX_DEPLOYMENT_TARGET'): + if sys.platform == 'darwin' and 'MACOSX_DEPLOYMENT_TARGET' in g: cfg_target = g['MACOSX_DEPLOYMENT_TARGET'] cur_target = os.getenv('MACOSX_DEPLOYMENT_TARGET', '') if cur_target == '': Modified: python/branches/p3yk/Lib/distutils/text_file.py ============================================================================== --- python/branches/p3yk/Lib/distutils/text_file.py (original) +++ python/branches/p3yk/Lib/distutils/text_file.py Sat Aug 19 00:13:04 2006 @@ -89,7 +89,7 @@ # set values for all options -- either from client option hash # or fallback to default_options for opt in self.default_options.keys(): - if options.has_key (opt): + if opt in options: setattr (self, opt, options[opt]) else: @@ -97,7 +97,7 @@ # sanity check client option hash for opt in options.keys(): - if not self.default_options.has_key (opt): + if opt not in self.default_options: raise KeyError, "invalid TextFile option '%s'" % opt if file is None: Modified: python/branches/p3yk/Lib/distutils/util.py ============================================================================== --- python/branches/p3yk/Lib/distutils/util.py (original) +++ python/branches/p3yk/Lib/distutils/util.py Sat Aug 19 00:13:04 2006 @@ -200,11 +200,11 @@ if _environ_checked: return - if os.name == 'posix' and not os.environ.has_key('HOME'): + if os.name == 'posix' and 'HOME' not in os.environ: import pwd os.environ['HOME'] = pwd.getpwuid(os.getuid())[5] - if not os.environ.has_key('PLAT'): + if 'PLAT' not in os.environ: os.environ['PLAT'] = get_platform() _environ_checked = 1 @@ -222,7 +222,7 @@ check_environ() def _subst (match, local_vars=local_vars): var_name = match.group(1) - if local_vars.has_key(var_name): + if var_name in local_vars: return str(local_vars[var_name]) else: return os.environ[var_name] Modified: python/branches/p3yk/Lib/dumbdbm.py ============================================================================== --- python/branches/p3yk/Lib/dumbdbm.py (original) +++ python/branches/p3yk/Lib/dumbdbm.py Sat Aug 19 00:13:04 2006 @@ -195,9 +195,6 @@ def keys(self): return self._index.keys() - def has_key(self, key): - return key in self._index - def __contains__(self, key): return key in self._index Modified: python/branches/p3yk/Lib/mailbox.py ============================================================================== --- python/branches/p3yk/Lib/mailbox.py (original) +++ python/branches/p3yk/Lib/mailbox.py Sat Aug 19 00:13:04 2006 @@ -120,13 +120,10 @@ """Return a list of (key, message) tuples. Memory intensive.""" return list(self.iteritems()) - def has_key(self, key): + def __contains__(self, key): """Return True if the keyed message exists, False otherwise.""" raise NotImplementedError('Method must be implemented by subclass') - def __contains__(self, key): - return self.has_key(key) - def __len__(self): """Return a count of messages in the mailbox.""" raise NotImplementedError('Method must be implemented by subclass') @@ -330,7 +327,7 @@ continue yield key - def has_key(self, key): + def __contains__(self, key): """Return True if the keyed message exists, False otherwise.""" self._refresh() return key in self._toc @@ -515,7 +512,7 @@ for key in self._toc.keys(): yield key - def has_key(self, key): + def __contains__(self, key): """Return True if the keyed message exists, False otherwise.""" self._lookup() return key in self._toc @@ -902,7 +899,7 @@ return iter(sorted(int(entry) for entry in os.listdir(self._path) if entry.isdigit())) - def has_key(self, key): + def __contains__(self, key): """Return True if the keyed message exists, False otherwise.""" return os.path.exists(os.path.join(self._path, str(key))) Modified: python/branches/p3yk/Lib/modulefinder.py ============================================================================== --- python/branches/p3yk/Lib/modulefinder.py (original) +++ python/branches/p3yk/Lib/modulefinder.py Sat Aug 19 00:13:04 2006 @@ -242,7 +242,7 @@ else: self.msgout(3, "import_module ->", m) return m - if self.badmodules.has_key(fqname): + if fqname in self.badmodules: self.msgout(3, "import_module -> None") return None if parent and parent.__path__ is None: @@ -388,7 +388,7 @@ return m def add_module(self, fqname): - if self.modules.has_key(fqname): + if fqname in self.modules: return self.modules[fqname] self.modules[fqname] = m = Module(fqname) return m Modified: python/branches/p3yk/Lib/optparse.py ============================================================================== --- python/branches/p3yk/Lib/optparse.py (original) +++ python/branches/p3yk/Lib/optparse.py Sat Aug 19 00:13:04 2006 @@ -602,7 +602,7 @@ def _set_attrs(self, attrs): for attr in self.ATTRS: - if attrs.has_key(attr): + if attr in attrs: setattr(self, attr, attrs[attr]) del attrs[attr] else: @@ -854,7 +854,7 @@ are silently ignored. """ for attr in dir(self): - if dict.has_key(attr): + if attr in dict: dval = dict[attr] if dval is not None: setattr(self, attr, dval) @@ -974,10 +974,10 @@ def _check_conflict(self, option): conflict_opts = [] for opt in option._short_opts: - if self._short_opt.has_key(opt): + if opt in self._short_opt: conflict_opts.append((opt, self._short_opt[opt])) for opt in option._long_opts: - if self._long_opt.has_key(opt): + if opt in self._long_opt: conflict_opts.append((opt, self._long_opt[opt])) if conflict_opts: @@ -1023,7 +1023,7 @@ if option.dest is not None: # option has a dest, we need a default if option.default is not NO_DEFAULT: self.defaults[option.dest] = option.default - elif not self.defaults.has_key(option.dest): + elif option.dest not in self.defaults: self.defaults[option.dest] = None return option @@ -1039,8 +1039,8 @@ self._long_opt.get(opt_str)) def has_option(self, opt_str): - return (self._short_opt.has_key(opt_str) or - self._long_opt.has_key(opt_str)) + return (opt_str in self._short_opt or + opt_str) in self._long_opt def remove_option(self, opt_str): option = self._short_opt.get(opt_str) @@ -1658,7 +1658,7 @@ 'words', raise BadOptionError. """ # Is there an exact match? - if wordmap.has_key(s): + if s in wordmap: return s else: # Isolate all words with s as a prefix. Modified: python/branches/p3yk/Lib/os.py ============================================================================== --- python/branches/p3yk/Lib/os.py (original) +++ python/branches/p3yk/Lib/os.py Sat Aug 19 00:13:04 2006 @@ -436,8 +436,6 @@ def __delitem__(self, key): unsetenv(key) del self.data[key.upper()] - def has_key(self, key): - return key.upper() in self.data def __contains__(self, key): return key.upper() in self.data def get(self, key, failobj=None): Modified: python/branches/p3yk/Lib/pickle.py ============================================================================== --- python/branches/p3yk/Lib/pickle.py (original) +++ python/branches/p3yk/Lib/pickle.py Sat Aug 19 00:13:04 2006 @@ -1287,19 +1287,19 @@ r"""Decode a long from a two's complement little-endian binary string. >>> decode_long('') - 0L + 0 >>> decode_long("\xff\x00") - 255L + 255 >>> decode_long("\xff\x7f") - 32767L + 32767 >>> decode_long("\x00\xff") - -256L + -256 >>> decode_long("\x00\x80") - -32768L + -32768 >>> decode_long("\x80") - -128L + -128 >>> decode_long("\x7f") - 127L + 127 """ nbytes = len(data) Modified: python/branches/p3yk/Lib/pickletools.py ============================================================================== --- python/branches/p3yk/Lib/pickletools.py (original) +++ python/branches/p3yk/Lib/pickletools.py Sat Aug 19 00:13:04 2006 @@ -517,23 +517,14 @@ r""" >>> import StringIO - >>> read_decimalnl_long(StringIO.StringIO("1234\n56")) - Traceback (most recent call last): - ... - ValueError: trailing 'L' required in '1234' - - Someday the trailing 'L' will probably go away from this output. - >>> read_decimalnl_long(StringIO.StringIO("1234L\n56")) - 1234L + 1234 >>> read_decimalnl_long(StringIO.StringIO("123456789012345678901234L\n6")) - 123456789012345678901234L + 123456789012345678901234 """ s = read_stringnl(f, decode=False, stripquotes=False) - if not s.endswith("L"): - raise ValueError("trailing 'L' required in %r" % s) return long(s) @@ -625,15 +616,15 @@ r""" >>> import StringIO >>> read_long1(StringIO.StringIO("\x00")) - 0L + 0 >>> read_long1(StringIO.StringIO("\x02\xff\x00")) - 255L + 255 >>> read_long1(StringIO.StringIO("\x02\xff\x7f")) - 32767L + 32767 >>> read_long1(StringIO.StringIO("\x02\x00\xff")) - -256L + -256 >>> read_long1(StringIO.StringIO("\x02\x00\x80")) - -32768L + -32768 """ n = read_uint1(f) @@ -657,15 +648,15 @@ r""" >>> import StringIO >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\xff\x00")) - 255L + 255 >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\xff\x7f")) - 32767L + 32767 >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\x00\xff")) - -256L + -256 >>> read_long4(StringIO.StringIO("\x02\x00\x00\x00\x00\x80")) - -32768L + -32768 >>> read_long1(StringIO.StringIO("\x00\x00\x00\x00")) - 0L + 0 """ n = read_int4(f) Modified: python/branches/p3yk/Lib/platform.py ============================================================================== --- python/branches/p3yk/Lib/platform.py (original) +++ python/branches/p3yk/Lib/platform.py Sat Aug 19 00:13:04 2006 @@ -877,7 +877,7 @@ executable == sys.executable: # "file" command did not return anything; we'll try to provide # some sensible defaults then... - if _default_architecture.has_key(sys.platform): + if sys.platform in _default_architecture: b,l = _default_architecture[sys.platform] if b: bits = b Modified: python/branches/p3yk/Lib/profile.py ============================================================================== --- python/branches/p3yk/Lib/profile.py (original) +++ python/branches/p3yk/Lib/profile.py Sat Aug 19 00:13:04 2006 @@ -318,7 +318,7 @@ fn = ("", 0, self.c_func_name) self.cur = (t, 0, 0, fn, frame, self.cur) timings = self.timings - if timings.has_key(fn): + if fn in timings: cc, ns, tt, ct, callers = timings[fn] timings[fn] = cc, ns+1, tt, ct, callers else: Modified: python/branches/p3yk/Lib/pstats.py ============================================================================== --- python/branches/p3yk/Lib/pstats.py (original) +++ python/branches/p3yk/Lib/pstats.py Sat Aug 19 00:13:04 2006 @@ -140,7 +140,7 @@ self.total_calls += nc self.prim_calls += cc self.total_tt += tt - if callers.has_key(("jprofile", 0, "profiler")): + if ("jprofile", 0, "profiler") in callers: self.top_level[func] = None if len(func_std_string(func)) > self.max_name_len: self.max_name_len = len(func_std_string(func)) Modified: python/branches/p3yk/Lib/rfc822.py ============================================================================== --- python/branches/p3yk/Lib/rfc822.py (original) +++ python/branches/p3yk/Lib/rfc822.py Sat Aug 19 00:13:04 2006 @@ -428,10 +428,6 @@ self.dict[lowername] = default return default - def has_key(self, name): - """Determine whether a message contains the named header.""" - return name.lower() in self.dict - def __contains__(self, name): """Determine whether a message contains the named header.""" return name.lower() in self.dict Modified: python/branches/p3yk/Lib/sets.py ============================================================================== --- python/branches/p3yk/Lib/sets.py (original) +++ python/branches/p3yk/Lib/sets.py Sat Aug 19 00:13:04 2006 @@ -231,7 +231,7 @@ little, big = self, other else: little, big = other, self - common = ifilter(big._data.has_key, little) + common = ifilter(big._data.__contains__, little) return self.__class__(common) def __xor__(self, other): @@ -256,9 +256,9 @@ otherdata = other._data except AttributeError: otherdata = Set(other)._data - for elt in ifilterfalse(otherdata.has_key, selfdata): + for elt in ifilterfalse(otherdata.__contains__, selfdata): data[elt] = value - for elt in ifilterfalse(selfdata.has_key, otherdata): + for elt in ifilterfalse(selfdata.__contains__, otherdata): data[elt] = value return result @@ -283,7 +283,7 @@ except AttributeError: otherdata = Set(other)._data value = True - for elt in ifilterfalse(otherdata.has_key, self): + for elt in ifilterfalse(otherdata.__contains__, self): data[elt] = value return result @@ -309,7 +309,7 @@ self._binary_sanity_check(other) if len(self) > len(other): # Fast check for obvious cases return False - for elt in ifilterfalse(other._data.has_key, self): + for elt in ifilterfalse(other._data.__contains__, self): return False return True @@ -318,7 +318,7 @@ self._binary_sanity_check(other) if len(self) < len(other): # Fast check for obvious cases return False - for elt in ifilterfalse(self._data.has_key, other): + for elt in ifilterfalse(self._data.__contains__, other): return False return True @@ -501,7 +501,7 @@ other = Set(other) if self is other: self.clear() - for elt in ifilter(data.has_key, other): + for elt in ifilter(data.__contains__, other): del data[elt] # Python dict-like mass mutations: update, clear Modified: python/branches/p3yk/Lib/shelve.py ============================================================================== --- python/branches/p3yk/Lib/shelve.py (original) +++ python/branches/p3yk/Lib/shelve.py Sat Aug 19 00:13:04 2006 @@ -20,7 +20,7 @@ # access returns a *copy* of the entry! del d[key] # delete data stored at key (raises KeyError # if no such key) - flag = d.has_key(key) # true if the key exists; same as "key in d" + flag = key in d # true if the key exists list = d.keys() # a list of all existing keys (slow!) d.close() # close it @@ -94,14 +94,11 @@ def __len__(self): return len(self.dict) - def has_key(self, key): - return self.dict.has_key(key) - def __contains__(self, key): - return self.dict.has_key(key) + return key in self.dict def get(self, key, default=None): - if self.dict.has_key(key): + if key in self.dict: return self[key] return default Modified: python/branches/p3yk/Lib/test/mapping_tests.py ============================================================================== --- python/branches/p3yk/Lib/test/mapping_tests.py (original) +++ python/branches/p3yk/Lib/test/mapping_tests.py Sat Aug 19 00:13:04 2006 @@ -54,12 +54,10 @@ #len self.assertEqual(len(p), 0) self.assertEqual(len(d), len(self.reference)) - #has_key + #__contains__ for k in self.reference: - self.assert_(d.has_key(k)) self.assert_(k in d) for k in self.other: - self.failIf(d.has_key(k)) self.failIf(k in d) #cmp self.assertEqual(cmp(p,p), 0) @@ -333,16 +331,6 @@ d = self._full_mapping({1:2}) self.assertEqual(d.items(), [(1, 2)]) - def test_has_key(self): - d = self._empty_mapping() - self.assert_(not d.has_key('a')) - d = self._full_mapping({'a': 1, 'b': 2}) - k = d.keys() - k.sort() - self.assertEqual(k, ['a', 'b']) - - self.assertRaises(TypeError, d.has_key) - def test_contains(self): d = self._empty_mapping() self.assert_(not ('a' in d)) Modified: python/branches/p3yk/Lib/test/regrtest.py ============================================================================== --- python/branches/p3yk/Lib/test/regrtest.py (original) +++ python/branches/p3yk/Lib/test/regrtest.py Sat Aug 19 00:13:04 2006 @@ -1034,7 +1034,6 @@ 'darwin': """ test_al - test_bsddb3 test_cd test_cl test_gdbm Modified: python/branches/p3yk/Lib/test/test___all__.py ============================================================================== --- python/branches/p3yk/Lib/test/test___all__.py (original) +++ python/branches/p3yk/Lib/test/test___all__.py Sat Aug 19 00:13:04 2006 @@ -24,7 +24,7 @@ "%s has no __all__ attribute" % modname) names = {} exec "from %s import *" % modname in names - if names.has_key("__builtins__"): + if "__builtins__" in names: del names["__builtins__"] keys = set(names) all = set(sys.modules[modname].__all__) Modified: python/branches/p3yk/Lib/test/test_bool.py ============================================================================== --- python/branches/p3yk/Lib/test/test_bool.py (original) +++ python/branches/p3yk/Lib/test/test_bool.py Sat Aug 19 00:13:04 2006 @@ -183,9 +183,9 @@ self.assertIs(issubclass(bool, int), True) self.assertIs(issubclass(int, bool), False) - def test_haskey(self): - self.assertIs({}.has_key(1), False) - self.assertIs({1:1}.has_key(1), True) + def test_contains(self): + self.assertIs(1 in {}, False) + self.assertIs(1 in {1:1}, True) def test_string(self): self.assertIs("xyz".endswith("z"), True) Modified: python/branches/p3yk/Lib/test/test_bsddb.py ============================================================================== --- python/branches/p3yk/Lib/test/test_bsddb.py (original) +++ python/branches/p3yk/Lib/test/test_bsddb.py Sat Aug 19 00:13:04 2006 @@ -135,11 +135,6 @@ self.assert_(k in self.f) self.assert_('not here' not in self.f) - def test_has_key(self): - for k in self.d: - self.assert_(self.f.has_key(k)) - self.assert_(not self.f.has_key('not here')) - def test_clear(self): self.f.clear() self.assertEqual(len(self.f), 0) Modified: python/branches/p3yk/Lib/test/test_builtin.py ============================================================================== --- python/branches/p3yk/Lib/test/test_builtin.py (original) +++ python/branches/p3yk/Lib/test/test_builtin.py Sat Aug 19 00:13:04 2006 @@ -630,9 +630,9 @@ def test_hex(self): self.assertEqual(hex(16), '0x10') - self.assertEqual(hex(16L), '0x10L') + self.assertEqual(hex(16L), '0x10') self.assertEqual(hex(-16), '-0x10') - self.assertEqual(hex(-16L), '-0x10L') + self.assertEqual(hex(-16L), '-0x10') self.assertRaises(TypeError, hex, {}) def test_id(self): @@ -1240,9 +1240,9 @@ def test_oct(self): self.assertEqual(oct(100), '0144') - self.assertEqual(oct(100L), '0144L') + self.assertEqual(oct(100L), '0144') self.assertEqual(oct(-100), '-0144') - self.assertEqual(oct(-100L), '-0144L') + self.assertEqual(oct(-100L), '-0144') self.assertRaises(TypeError, oct, ()) def write_testfile(self): @@ -1441,7 +1441,7 @@ def test_repr(self): self.assertEqual(repr(''), '\'\'') self.assertEqual(repr(0), '0') - self.assertEqual(repr(0L), '0L') + self.assertEqual(repr(0L), '0') self.assertEqual(repr(()), '()') self.assertEqual(repr([]), '[]') self.assertEqual(repr({}), '{}') Modified: python/branches/p3yk/Lib/test/test_call.py ============================================================================== --- python/branches/p3yk/Lib/test/test_call.py (original) +++ python/branches/p3yk/Lib/test/test_call.py Sat Aug 19 00:13:04 2006 @@ -9,39 +9,39 @@ class CFunctionCalls(unittest.TestCase): def test_varargs0(self): - self.assertRaises(TypeError, {}.has_key) + self.assertRaises(TypeError, {}.__contains__) def test_varargs1(self): - {}.has_key(0) + {}.__contains__(0) def test_varargs2(self): - self.assertRaises(TypeError, {}.has_key, 0, 1) + self.assertRaises(TypeError, {}.__contains__, 0, 1) def test_varargs0_ext(self): try: - {}.has_key(*()) + {}.__contains__(*()) except TypeError: pass def test_varargs1_ext(self): - {}.has_key(*(0,)) + {}.__contains__(*(0,)) def test_varargs2_ext(self): try: - {}.has_key(*(1, 2)) + {}.__contains__(*(1, 2)) except TypeError: pass else: raise RuntimeError def test_varargs0_kw(self): - self.assertRaises(TypeError, {}.has_key, x=2) + self.assertRaises(TypeError, {}.__contains__, x=2) def test_varargs1_kw(self): - self.assertRaises(TypeError, {}.has_key, x=2) + self.assertRaises(TypeError, {}.__contains__, x=2) def test_varargs2_kw(self): - self.assertRaises(TypeError, {}.has_key, x=2, y=2) + self.assertRaises(TypeError, {}.__contains__, x=2, y=2) def test_oldargs0_0(self): {}.keys() Modified: python/branches/p3yk/Lib/test/test_cgi.py ============================================================================== --- python/branches/p3yk/Lib/test/test_cgi.py (original) +++ python/branches/p3yk/Lib/test/test_cgi.py Sat Aug 19 00:13:04 2006 @@ -158,10 +158,10 @@ # test individual fields for key in expect.keys(): expect_val = expect[key] - verify(fcd.has_key(key)) + verify(key in fcd) verify(norm(fcd[key]) == norm(expect[key])) verify(fcd.get(key, "default") == fcd[key]) - verify(fs.has_key(key)) + verify(key in fs) if len(expect_val) > 1: single_value = 0 else: Modified: python/branches/p3yk/Lib/test/test_dbm.py ============================================================================== --- python/branches/p3yk/Lib/test/test_dbm.py (original) +++ python/branches/p3yk/Lib/test/test_dbm.py Sat Aug 19 00:13:04 2006 @@ -28,7 +28,7 @@ d['a'] = 'b' d['12345678910'] = '019237410982340912840198242' d.keys() - if d.has_key('a'): + if 'a' in d: if verbose: print 'Test dbm keys: ', d.keys() Modified: python/branches/p3yk/Lib/test/test_dict.py ============================================================================== --- python/branches/p3yk/Lib/test/test_dict.py (original) +++ python/branches/p3yk/Lib/test/test_dict.py Sat Aug 19 00:13:04 2006 @@ -21,8 +21,8 @@ self.assertEqual(d.keys(), []) d = {'a': 1, 'b': 2} k = d.keys() - self.assert_(d.has_key('a')) - self.assert_(d.has_key('b')) + self.assert_('a' in d) + self.assert_('b' in d) self.assertRaises(TypeError, d.keys, None) @@ -43,16 +43,6 @@ self.assertRaises(TypeError, d.items, None) - def test_has_key(self): - d = {} - self.assert_(not d.has_key('a')) - d = {'a': 1, 'b': 2} - k = d.keys() - k.sort() - self.assertEqual(k, ['a', 'b']) - - self.assertRaises(TypeError, d.has_key) - def test_contains(self): d = {} self.assert_(not ('a' in d)) Modified: python/branches/p3yk/Lib/test/test_gdbm.py ============================================================================== --- python/branches/p3yk/Lib/test/test_gdbm.py (original) +++ python/branches/p3yk/Lib/test/test_gdbm.py Sat Aug 19 00:13:04 2006 @@ -17,7 +17,7 @@ if verbose: print 'Test gdbm file keys: ', a -g.has_key('a') +'a' in g g.close() try: g['a'] Modified: python/branches/p3yk/Lib/test/test_grammar.py ============================================================================== --- python/branches/p3yk/Lib/test/test_grammar.py (original) +++ python/branches/p3yk/Lib/test/test_grammar.py Sat Aug 19 00:13:04 2006 @@ -472,7 +472,7 @@ f() g = {} exec 'z = 1' in g -if g.has_key('__builtins__'): del g['__builtins__'] +if '__builtins__' in g: del g['__builtins__'] if g != {'z': 1}: raise TestFailed, 'exec \'z = 1\' in g' g = {} l = {} @@ -480,8 +480,8 @@ import warnings warnings.filterwarnings("ignore", "global statement", module="") exec 'global a; a = 1; b = 2' in g, l -if g.has_key('__builtins__'): del g['__builtins__'] -if l.has_key('__builtins__'): del l['__builtins__'] +if '__builtins__' in g: del g['__builtins__'] +if '__builtins__' in l: del l['__builtins__'] if (g, l) != ({'a':1}, {'b':2}): raise TestFailed, 'exec ... in g (%s), l (%s)' %(g,l) Modified: python/branches/p3yk/Lib/test/test_mailbox.py ============================================================================== --- python/branches/p3yk/Lib/test/test_mailbox.py (original) +++ python/branches/p3yk/Lib/test/test_mailbox.py Sat Aug 19 00:13:04 2006 @@ -229,16 +229,9 @@ count += 1 self.assert_(len(values) == count) - def test_has_key(self): - # Check existence of keys using has_key() - self._test_has_key_or_contains(self._box.has_key) - def test_contains(self): # Check existence of keys using __contains__() - self._test_has_key_or_contains(self._box.__contains__) - - def _test_has_key_or_contains(self, method): - # (Used by test_has_key() and test_contains().) + method = self._box.__contains__ self.assert_(not method('foo')) key0 = self._box.add(self._template % 0) self.assert_(method(key0)) @@ -442,7 +435,7 @@ self.assertRaises(NotImplementedError, lambda: box.get_message('')) self.assertRaises(NotImplementedError, lambda: box.get_string('')) self.assertRaises(NotImplementedError, lambda: box.get_file('')) - self.assertRaises(NotImplementedError, lambda: box.has_key('')) + self.assertRaises(NotImplementedError, lambda: '' in box) self.assertRaises(NotImplementedError, lambda: box.__contains__('')) self.assertRaises(NotImplementedError, lambda: box.__len__()) self.assertRaises(NotImplementedError, lambda: box.clear()) Modified: python/branches/p3yk/Lib/test/test_multibytecodec_support.py ============================================================================== --- python/branches/p3yk/Lib/test/test_multibytecodec_support.py (original) +++ python/branches/p3yk/Lib/test/test_multibytecodec_support.py Sat Aug 19 00:13:04 2006 @@ -297,7 +297,7 @@ continue unich = unichrs(data[1]) - if ord(unich) == 0xfffd or urt_wa.has_key(unich): + if ord(unich) == 0xfffd or unich in urt_wa: continue urt_wa[unich] = csetch Modified: python/branches/p3yk/Lib/test/test_operations.py ============================================================================== --- python/branches/p3yk/Lib/test/test_operations.py (original) +++ python/branches/p3yk/Lib/test/test_operations.py Sat Aug 19 00:13:04 2006 @@ -25,7 +25,6 @@ for stmt in ['d[x2] = 2', 'z = d[x2]', 'x2 in d', - 'd.has_key(x2)', 'd.get(x2)', 'd.setdefault(x2, 42)', 'd.pop(x2)', Modified: python/branches/p3yk/Lib/test/test_pkgimport.py ============================================================================== --- python/branches/p3yk/Lib/test/test_pkgimport.py (original) +++ python/branches/p3yk/Lib/test/test_pkgimport.py Sat Aug 19 00:13:04 2006 @@ -6,14 +6,14 @@ def __init__(self, *args, **kw): self.package_name = 'PACKAGE_' - while sys.modules.has_key(self.package_name): + while self.package_name in sys.modules: self.package_name += random.choose(string.letters) self.module_name = self.package_name + '.foo' unittest.TestCase.__init__(self, *args, **kw) def remove_modules(self): for module_name in (self.package_name, self.module_name): - if sys.modules.has_key(module_name): + if module_name in sys.modules: del sys.modules[module_name] def setUp(self): @@ -52,7 +52,7 @@ try: __import__(self.module_name) except SyntaxError: pass else: raise RuntimeError, 'Failed to induce SyntaxError' - self.assert_(not sys.modules.has_key(self.module_name) and + self.assert_(self.module_name not in sys.modules and not hasattr(sys.modules[self.package_name], 'foo')) # ...make up a variable name that isn't bound in __builtins__ Modified: python/branches/p3yk/Lib/test/test_pyclbr.py ============================================================================== --- python/branches/p3yk/Lib/test/test_pyclbr.py (original) +++ python/branches/p3yk/Lib/test/test_pyclbr.py Sat Aug 19 00:13:04 2006 @@ -40,11 +40,11 @@ def assertHaskey(self, obj, key, ignore): - ''' succeed iff obj.has_key(key) or key in ignore. ''' + ''' succeed iff key in obj or key in ignore. ''' if key in ignore: return - if not obj.has_key(key): + if key not in obj: print >>sys.stderr, "***",key - self.failUnless(obj.has_key(key)) + self.failUnless(key) in obj def assertEqualsOrIgnored(self, a, b, ignore): ''' succeed iff a == b or a in ignore or b in ignore ''' Modified: python/branches/p3yk/Lib/test/test_rfc822.py ============================================================================== --- python/branches/p3yk/Lib/test/test_rfc822.py (original) +++ python/branches/p3yk/Lib/test/test_rfc822.py Sat Aug 19 00:13:04 2006 @@ -25,7 +25,7 @@ def test_setdefault(self): msg = self.create_message( 'To: "last, first" \n\ntest\n') - self.assert_(not msg.has_key("New-Header")) + self.assert_("New-Header" not in msg) self.assert_(msg.setdefault("New-Header", "New-Value") == "New-Value") self.assert_(msg.setdefault("New-Header", "Different-Value") == "New-Value") Modified: python/branches/p3yk/Lib/test/test_sax.py ============================================================================== --- python/branches/p3yk/Lib/test/test_sax.py (original) +++ python/branches/p3yk/Lib/test/test_sax.py Sat Aug 19 00:13:04 2006 @@ -357,7 +357,7 @@ attrs.getNames() == [(ns_uri, "attr")] and \ (attrs.getQNames() == [] or attrs.getQNames() == ["ns:attr"]) and \ len(attrs) == 1 and \ - attrs.has_key((ns_uri, "attr")) and \ + (ns_uri, "attr") in attrs and \ attrs.keys() == [(ns_uri, "attr")] and \ attrs.get((ns_uri, "attr")) == "val" and \ attrs.get((ns_uri, "attr"), 25) == "val" and \ @@ -571,7 +571,7 @@ attrs.getNames() == [] and \ attrs.getQNames() == [] and \ len(attrs) == 0 and \ - not attrs.has_key("attr") and \ + "attr" not in attrs and \ attrs.keys() == [] and \ attrs.get("attrs") is None and \ attrs.get("attrs", 25) == 25 and \ @@ -584,7 +584,7 @@ attrs.getNames() == ["attr"] and \ attrs.getQNames() == ["attr"] and \ len(attrs) == 1 and \ - attrs.has_key("attr") and \ + "attr" in attrs and \ attrs.keys() == ["attr"] and \ attrs.get("attr") == "val" and \ attrs.get("attr", 25) == "val" and \ @@ -639,7 +639,7 @@ attrs.getNames() == [] and \ attrs.getQNames() == [] and \ len(attrs) == 0 and \ - not attrs.has_key((ns_uri, "attr")) and \ + (ns_uri, "attr") not in attrs and \ attrs.keys() == [] and \ attrs.get((ns_uri, "attr")) is None and \ attrs.get((ns_uri, "attr"), 25) == 25 and \ @@ -658,7 +658,7 @@ attrs.getNames() == [(ns_uri, "attr")] and \ attrs.getQNames() == ["ns:attr"] and \ len(attrs) == 1 and \ - attrs.has_key((ns_uri, "attr")) and \ + (ns_uri, "attr") in attrs and \ attrs.keys() == [(ns_uri, "attr")] and \ attrs.get((ns_uri, "attr")) == "val" and \ attrs.get((ns_uri, "attr"), 25) == "val" and \ Modified: python/branches/p3yk/Lib/test/test_scope.py ============================================================================== --- python/branches/p3yk/Lib/test/test_scope.py (original) +++ python/branches/p3yk/Lib/test/test_scope.py Sat Aug 19 00:13:04 2006 @@ -472,7 +472,7 @@ return g d = f(2)(4) -verify(d.has_key('h')) +verify('h' in d) del d['h'] vereq(d, {'x': 2, 'y': 7, 'w': 6}) Modified: python/branches/p3yk/Lib/test/test_site.py ============================================================================== --- python/branches/p3yk/Lib/test/test_site.py (original) +++ python/branches/p3yk/Lib/test/test_site.py Sat Aug 19 00:13:04 2006 @@ -216,7 +216,7 @@ def test_sitecustomize_executed(self): # If sitecustomize is available, it should have been imported. - if not sys.modules.has_key("sitecustomize"): + if "sitecustomize" not in sys.modules: try: import sitecustomize except ImportError: Modified: python/branches/p3yk/Lib/test/test_struct.py ============================================================================== --- python/branches/p3yk/Lib/test/test_struct.py (original) +++ python/branches/p3yk/Lib/test/test_struct.py Sat Aug 19 00:13:04 2006 @@ -266,7 +266,7 @@ if x < 0: expected += 1L << self.bitsize assert expected > 0 - expected = hex(expected)[2:-1] # chop "0x" and trailing 'L' + expected = hex(expected)[2:] # chop "0x" if len(expected) & 1: expected = "0" + expected expected = unhexlify(expected) @@ -322,7 +322,7 @@ # Try big-endian. format = ">" + code expected = long(x) - expected = hex(expected)[2:-1] # chop "0x" and trailing 'L' + expected = hex(expected)[2:] # chop "0x" if len(expected) & 1: expected = "0" + expected expected = unhexlify(expected) Modified: python/branches/p3yk/Lib/test/test_time.py ============================================================================== --- python/branches/p3yk/Lib/test/test_time.py (original) +++ python/branches/p3yk/Lib/test/test_time.py Sat Aug 19 00:13:04 2006 @@ -180,7 +180,7 @@ # rely on it. if org_TZ is not None: environ['TZ'] = org_TZ - elif environ.has_key('TZ'): + elif 'TZ' in environ: del environ['TZ'] time.tzset() Modified: python/branches/p3yk/Lib/test/test_urllib2.py ============================================================================== --- python/branches/p3yk/Lib/test/test_urllib2.py (original) +++ python/branches/p3yk/Lib/test/test_urllib2.py Sat Aug 19 00:13:04 2006 @@ -653,7 +653,7 @@ r.info; r.geturl # addinfourl methods r.code, r.msg == 200, "OK" # added from MockHTTPClass.getreply() hdrs = r.info() - hdrs.get; hdrs.has_key # r.info() gives dict from .getreply() + hdrs.get; hdrs.__contains__ # r.info() gives dict from .getreply() self.assertEqual(r.geturl(), url) self.assertEqual(http.host, "example.com") Modified: python/branches/p3yk/Lib/test/test_userdict.py ============================================================================== --- python/branches/p3yk/Lib/test/test_userdict.py (original) +++ python/branches/p3yk/Lib/test/test_userdict.py Sat Aug 19 00:13:04 2006 @@ -94,13 +94,10 @@ self.assertEqual(u2.items(), d2.items()) self.assertEqual(u2.values(), d2.values()) - # Test has_key and "in". + # Test "in". for i in u2.keys(): - self.assert_(u2.has_key(i)) self.assert_(i in u2) - self.assertEqual(u1.has_key(i), d1.has_key(i)) self.assertEqual(i in u1, i in d1) - self.assertEqual(u0.has_key(i), d0.has_key(i)) self.assertEqual(i in u0, i in d0) # Test update @@ -132,7 +129,7 @@ # Test setdefault t = UserDict.UserDict() self.assertEqual(t.setdefault("x", 42), 42) - self.assert_(t.has_key("x")) + self.assert_("x" in t) self.assertEqual(t.setdefault("x", 23), 42) # Test pop @@ -269,9 +266,6 @@ self.assertEqual(s.keys(), [10, 30]) ## Now, test the DictMixin methods one by one - # has_key - self.assert_(s.has_key(10)) - self.assert_(not s.has_key(20)) # __contains__ self.assert_(10 in s) Modified: python/branches/p3yk/Lib/test/test_weakref.py ============================================================================== --- python/branches/p3yk/Lib/test/test_weakref.py (original) +++ python/branches/p3yk/Lib/test/test_weakref.py Sat Aug 19 00:13:04 2006 @@ -739,7 +739,7 @@ def test_weak_keys(self): # # This exercises d.copy(), d.items(), d[] = v, d[], del d[], - # len(d), d.has_key(). + # len(d), k in d. # dict, objects = self.make_weak_keyed_dict() for o in objects: @@ -761,8 +761,8 @@ "deleting the keys did not clear the dictionary") o = Object(42) dict[o] = "What is the meaning of the universe?" - self.assert_(dict.has_key(o)) - self.assert_(not dict.has_key(34)) + self.assert_(o in dict) + self.assert_(34 not in dict) def test_weak_keyed_iters(self): dict, objects = self.make_weak_keyed_dict() @@ -774,7 +774,7 @@ objects2 = list(objects) for wr in refs: ob = wr() - self.assert_(dict.has_key(ob)) + self.assert_(ob in dict) self.assert_(ob in dict) self.assertEqual(ob.arg, dict[ob]) objects2.remove(ob) @@ -785,7 +785,7 @@ self.assertEqual(len(list(dict.iterkeyrefs())), len(objects)) for wr in dict.iterkeyrefs(): ob = wr() - self.assert_(dict.has_key(ob)) + self.assert_(ob in dict) self.assert_(ob in dict) self.assertEqual(ob.arg, dict[ob]) objects2.remove(ob) @@ -900,13 +900,13 @@ weakdict = klass() o = weakdict.setdefault(key, value1) self.assert_(o is value1) - self.assert_(weakdict.has_key(key)) + self.assert_(key in weakdict) self.assert_(weakdict.get(key) is value1) self.assert_(weakdict[key] is value1) o = weakdict.setdefault(key, value2) self.assert_(o is value1) - self.assert_(weakdict.has_key(key)) + self.assert_(key in weakdict) self.assert_(weakdict.get(key) is value1) self.assert_(weakdict[key] is value1) @@ -920,20 +920,20 @@ def check_update(self, klass, dict): # - # This exercises d.update(), len(d), d.keys(), d.has_key(), + # This exercises d.update(), len(d), d.keys(), k in d, # d.get(), d[]. # weakdict = klass() weakdict.update(dict) self.assert_(len(weakdict) == len(dict)) for k in weakdict.keys(): - self.assert_(dict.has_key(k), + self.assert_(k in dict, "mysterious new key appeared in weak dict") v = dict.get(k) self.assert_(v is weakdict[k]) self.assert_(v is weakdict.get(k)) for k in dict.keys(): - self.assert_(weakdict.has_key(k), + self.assert_(k in weakdict, "original key disappeared in weak dict") v = dict[k] self.assert_(v is weakdict[k]) Modified: python/branches/p3yk/Lib/test/test_wsgiref.py ============================================================================== --- python/branches/p3yk/Lib/test/test_wsgiref.py (original) +++ python/branches/p3yk/Lib/test/test_wsgiref.py Sat Aug 19 00:13:04 2006 @@ -341,7 +341,7 @@ del h['foo'] # should not raise an error h['Foo'] = 'bar' - for m in h.has_key, h.__contains__, h.get, h.get_all, h.__getitem__: + for m in h.__contains__, h.get, h.get_all, h.__getitem__: self.failUnless(m('foo')) self.failUnless(m('Foo')) self.failUnless(m('FOO')) @@ -424,10 +424,10 @@ env = handler.environ from os import environ for k,v in environ.items(): - if not empty.has_key(k): + if k not in empty: self.assertEqual(env[k],v) for k,v in empty.items(): - self.failUnless(env.has_key(k)) + self.failUnless(k in env) def testEnviron(self): h = TestHandler(X="Y") @@ -440,7 +440,7 @@ h = BaseCGIHandler(None,None,None,{}) h.setup_environ() for key in 'wsgi.url_scheme', 'wsgi.input', 'wsgi.errors': - self.assert_(h.environ.has_key(key)) + self.assert_(key in h.environ) def testScheme(self): h=TestHandler(HTTPS="on"); h.setup_environ() Modified: python/branches/p3yk/Lib/trace.py ============================================================================== --- python/branches/p3yk/Lib/trace.py (original) +++ python/branches/p3yk/Lib/trace.py Sat Aug 19 00:13:04 2006 @@ -120,7 +120,7 @@ self._ignore = { '': 1 } def names(self, filename, modulename): - if self._ignore.has_key(modulename): + if modulename in self._ignore: return self._ignore[modulename] # haven't seen this one before, so see if the module name is Modified: python/branches/p3yk/Lib/unittest.py ============================================================================== --- python/branches/p3yk/Lib/unittest.py (original) +++ python/branches/p3yk/Lib/unittest.py Sat Aug 19 00:13:04 2006 @@ -153,7 +153,7 @@ return ''.join(traceback.format_exception(exctype, value, tb)) def _is_relevant_tb_level(self, tb): - return tb.tb_frame.f_globals.has_key('__unittest') + return '__unittest' in tb.tb_frame.f_globals def _count_relevant_tb_levels(self, tb): length = 0 Modified: python/branches/p3yk/Lib/urllib.py ============================================================================== --- python/branches/p3yk/Lib/urllib.py (original) +++ python/branches/p3yk/Lib/urllib.py Sat Aug 19 00:13:04 2006 @@ -114,7 +114,7 @@ def __init__(self, proxies=None, **x509): if proxies is None: proxies = getproxies() - assert hasattr(proxies, 'has_key'), "proxies must be a mapping" + assert hasattr(proxies, 'keys'), "proxies must be a mapping" self.proxies = proxies self.key_file = x509.get('key_file') self.cert_file = x509.get('cert_file') Modified: python/branches/p3yk/Lib/urllib2.py ============================================================================== --- python/branches/p3yk/Lib/urllib2.py (original) +++ python/branches/p3yk/Lib/urllib2.py Sat Aug 19 00:13:04 2006 @@ -660,7 +660,7 @@ def __init__(self, proxies=None): if proxies is None: proxies = getproxies() - assert hasattr(proxies, 'has_key'), "proxies must be a mapping" + assert hasattr(proxies, 'keys'), "proxies must be a mapping" self.proxies = proxies for type, url in proxies.items(): setattr(self, '%s_open' % type, Modified: python/branches/p3yk/Lib/weakref.py ============================================================================== --- python/branches/p3yk/Lib/weakref.py (original) +++ python/branches/p3yk/Lib/weakref.py Sat Aug 19 00:13:04 2006 @@ -64,13 +64,6 @@ return False return o is not None - def has_key(self, key): - try: - o = self.data[key]() - except KeyError: - return False - return o is not None - def __repr__(self): return "" % id(self) @@ -259,13 +252,6 @@ def get(self, key, default=None): return self.data.get(ref(key),default) - def has_key(self, key): - try: - wr = ref(key) - except TypeError: - return 0 - return wr in self.data - def __contains__(self, key): try: wr = ref(key) Modified: python/branches/p3yk/Lib/wsgiref/handlers.py ============================================================================== --- python/branches/p3yk/Lib/wsgiref/handlers.py (original) +++ python/branches/p3yk/Lib/wsgiref/handlers.py Sat Aug 19 00:13:04 2006 @@ -159,7 +159,7 @@ Subclasses can extend this to add other defaults. """ - if not self.headers.has_key('Content-Length'): + if 'Content-Length' not in self.headers: self.set_content_length() def start_response(self, status, headers,exc_info=None): @@ -194,11 +194,11 @@ if self.origin_server: if self.client_is_modern(): self._write('HTTP/%s %s\r\n' % (self.http_version,self.status)) - if not self.headers.has_key('Date'): + if 'Date' not in self.headers: self._write( 'Date: %s\r\n' % format_date_time(time.time()) ) - if self.server_software and not self.headers.has_key('Server'): + if self.server_software and 'Server' not in self.headers: self._write('Server: %s\r\n' % self.server_software) else: self._write('Status: %s\r\n' % self.status) Modified: python/branches/p3yk/Lib/wsgiref/headers.py ============================================================================== --- python/branches/p3yk/Lib/wsgiref/headers.py (original) +++ python/branches/p3yk/Lib/wsgiref/headers.py Sat Aug 19 00:13:04 2006 @@ -80,12 +80,10 @@ - def has_key(self, name): + def __contains__(self, name): """Return true if the message contains the header.""" return self.get(name) is not None - __contains__ = has_key - def get_all(self, name): """Return a list of all the values for the named field. Modified: python/branches/p3yk/Lib/wsgiref/util.py ============================================================================== --- python/branches/p3yk/Lib/wsgiref/util.py (original) +++ python/branches/p3yk/Lib/wsgiref/util.py Sat Aug 19 00:13:04 2006 @@ -166,7 +166,7 @@ 'connection':1, 'keep-alive':1, 'proxy-authenticate':1, 'proxy-authorization':1, 'te':1, 'trailers':1, 'transfer-encoding':1, 'upgrade':1 -}.has_key +}.__contains__ def is_hop_by_hop(header_name): """Return true if 'header_name' is an HTTP/1.1 "Hop-by-Hop" header""" Modified: python/branches/p3yk/Lib/wsgiref/validate.py ============================================================================== --- python/branches/p3yk/Lib/wsgiref/validate.py (original) +++ python/branches/p3yk/Lib/wsgiref/validate.py Sat Aug 19 00:13:04 2006 @@ -345,7 +345,7 @@ "Invalid CONTENT_LENGTH: %r" % environ['CONTENT_LENGTH']) if not environ.get('SCRIPT_NAME'): - assert_(environ.has_key('PATH_INFO'), + assert_('PATH_INFO' in environ, "One of SCRIPT_NAME or PATH_INFO are required (PATH_INFO " "should at least be '/' if SCRIPT_NAME is empty)") assert_(environ.get('SCRIPT_NAME') != '/', Modified: python/branches/p3yk/Lib/xmlrpclib.py ============================================================================== --- python/branches/p3yk/Lib/xmlrpclib.py (original) +++ python/branches/p3yk/Lib/xmlrpclib.py Sat Aug 19 00:13:04 2006 @@ -686,7 +686,7 @@ def dump_array(self, value, write): i = id(value) - if self.memo.has_key(i): + if i in self.memo: raise TypeError, "cannot marshal recursive sequences" self.memo[i] = None dump = self.__dump @@ -700,7 +700,7 @@ def dump_struct(self, value, write, escape=escape): i = id(value) - if self.memo.has_key(i): + if i in self.memo: raise TypeError, "cannot marshal recursive dictionaries" self.memo[i] = None dump = self.__dump Modified: python/branches/p3yk/Modules/bsddbmodule.c ============================================================================== --- python/branches/p3yk/Modules/bsddbmodule.c (original) +++ python/branches/p3yk/Modules/bsddbmodule.c Sat Aug 19 00:13:04 2006 @@ -461,7 +461,7 @@ } static PyObject * -bsddb_has_key(bsddbobject *dp, PyObject *args) +bsddb_contains(bsddbobject *dp, PyObject *args) { DBT krec, drec; int status; @@ -640,7 +640,7 @@ static PyMethodDef bsddb_methods[] = { {"close", (PyCFunction)bsddb_close, METH_NOARGS}, {"keys", (PyCFunction)bsddb_keys, METH_NOARGS}, - {"has_key", (PyCFunction)bsddb_has_key, METH_VARARGS}, + {"__contains__", (PyCFunction)bsddb_contains, METH_VARARGS}, {"set_location", (PyCFunction)bsddb_set_location, METH_VARARGS}, {"next", (PyCFunction)bsddb_next, METH_NOARGS}, {"previous", (PyCFunction)bsddb_previous, METH_NOARGS}, Modified: python/branches/p3yk/Modules/dbmmodule.c ============================================================================== --- python/branches/p3yk/Modules/dbmmodule.c (original) +++ python/branches/p3yk/Modules/dbmmodule.c Sat Aug 19 00:13:04 2006 @@ -206,12 +206,12 @@ } static PyObject * -dbm_has_key(register dbmobject *dp, PyObject *args) +dbm_contains(register dbmobject *dp, PyObject *args) { datum key, val; int tmp_size; - if (!PyArg_ParseTuple(args, "s#:has_key", &key.dptr, &tmp_size)) + if (!PyArg_ParseTuple(args, "s#:__contains__", &key.dptr, &tmp_size)) return NULL; key.dsize = tmp_size; check_dbmobject_open(dp); @@ -277,8 +277,8 @@ "close()\nClose the database."}, {"keys", (PyCFunction)dbm_keys, METH_NOARGS, "keys() -> list\nReturn a list of all keys in the database."}, - {"has_key", (PyCFunction)dbm_has_key, METH_VARARGS, - "has_key(key} -> boolean\nReturn true iff key is in the database."}, + {"__contains__",(PyCFunction)dbm_contains, METH_VARARGS, + "__contains__(key} -> boolean\True iff key is in the database."}, {"get", (PyCFunction)dbm_get, METH_VARARGS, "get(key[, default]) -> value\n" "Return the value for key if present, otherwise default."}, Modified: python/branches/p3yk/Modules/gdbmmodule.c ============================================================================== --- python/branches/p3yk/Modules/gdbmmodule.c (original) +++ python/branches/p3yk/Modules/gdbmmodule.c Sat Aug 19 00:13:04 2006 @@ -241,16 +241,16 @@ return v; } -PyDoc_STRVAR(dbm_has_key__doc__, -"has_key(key) -> boolean\n\ +PyDoc_STRVAR(dbm_contains__doc__, +"__contains__(key) -> bool\n\ Find out whether or not the database contains a given key."); static PyObject * -dbm_has_key(register dbmobject *dp, PyObject *args) +dbm_contains(register dbmobject *dp, PyObject *args) { datum key; - if (!PyArg_ParseTuple(args, "s#:has_key", &key.dptr, &key.dsize)) + if (!PyArg_ParseTuple(args, "s#:contains", &key.dptr, &key.dsize)) return NULL; check_dbmobject_open(dp); return PyInt_FromLong((long) gdbm_exists(dp->di_dbm, key)); @@ -355,7 +355,7 @@ static PyMethodDef dbm_methods[] = { {"close", (PyCFunction)dbm_close, METH_NOARGS, dbm_close__doc__}, {"keys", (PyCFunction)dbm_keys, METH_NOARGS, dbm_keys__doc__}, - {"has_key", (PyCFunction)dbm_has_key, METH_VARARGS, dbm_has_key__doc__}, + {"__contains__",(PyCFunction)dbm_contains,METH_VARARGS, dbm_contains__doc__}, {"firstkey", (PyCFunction)dbm_firstkey,METH_NOARGS, dbm_firstkey__doc__}, {"nextkey", (PyCFunction)dbm_nextkey, METH_VARARGS, dbm_nextkey__doc__}, {"reorganize",(PyCFunction)dbm_reorganize,METH_NOARGS, dbm_reorganize__doc__}, Modified: python/branches/p3yk/Objects/descrobject.c ============================================================================== --- python/branches/p3yk/Objects/descrobject.c (original) +++ python/branches/p3yk/Objects/descrobject.c Sat Aug 19 00:13:04 2006 @@ -701,15 +701,6 @@ }; static PyObject * -proxy_has_key(proxyobject *pp, PyObject *key) -{ - int res = PyDict_Contains(pp->dict, key); - if (res < 0) - return NULL; - return PyBool_FromLong(res); -} - -static PyObject * proxy_get(proxyobject *pp, PyObject *args) { PyObject *key, *def = Py_None; @@ -761,10 +752,8 @@ } static PyMethodDef proxy_methods[] = { - {"has_key", (PyCFunction)proxy_has_key, METH_O, - PyDoc_STR("D.has_key(k) -> True if D has a key k, else False")}, {"get", (PyCFunction)proxy_get, METH_VARARGS, - PyDoc_STR("D.get(k[,d]) -> D[k] if D.has_key(k), else d." + PyDoc_STR("D.get(k[,d]) -> D[k] if k in D, else d." " d defaults to None.")}, {"keys", (PyCFunction)proxy_keys, METH_NOARGS, PyDoc_STR("D.keys() -> list of D's keys")}, Modified: python/branches/p3yk/Objects/dictobject.c ============================================================================== --- python/branches/p3yk/Objects/dictobject.c (original) +++ python/branches/p3yk/Objects/dictobject.c Sat Aug 19 00:13:04 2006 @@ -1621,7 +1621,7 @@ } static PyObject * -dict_has_key(register dictobject *mp, PyObject *key) +dict_contains(register dictobject *mp, PyObject *key) { long hash; dictentry *ep; @@ -1856,9 +1856,6 @@ } -PyDoc_STRVAR(has_key__doc__, -"D.has_key(k) -> True if D has a key k, else False"); - PyDoc_STRVAR(contains__doc__, "D.__contains__(k) -> True if D has a key k, else False"); @@ -1911,12 +1908,10 @@ "D.iteritems() -> an iterator over the (key, value) items of D"); static PyMethodDef mapp_methods[] = { - {"__contains__",(PyCFunction)dict_has_key, METH_O | METH_COEXIST, + {"__contains__",(PyCFunction)dict_contains, METH_O | METH_COEXIST, contains__doc__}, {"__getitem__", (PyCFunction)dict_subscript, METH_O | METH_COEXIST, getitem__doc__}, - {"has_key", (PyCFunction)dict_has_key, METH_O, - has_key__doc__}, {"get", (PyCFunction)dict_get, METH_VARARGS, get__doc__}, {"setdefault", (PyCFunction)dict_setdefault, METH_VARARGS, Modified: python/branches/p3yk/Objects/typeobject.c ============================================================================== --- python/branches/p3yk/Objects/typeobject.c (original) +++ python/branches/p3yk/Objects/typeobject.c Sat Aug 19 00:13:04 2006 @@ -4432,7 +4432,6 @@ } if (func == NULL) { - PyErr_Clear(); PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'", self->ob_type->tp_name); return -1; Modified: python/branches/p3yk/setup.py ============================================================================== --- python/branches/p3yk/setup.py (original) +++ python/branches/p3yk/setup.py Sat Aug 19 00:13:04 2006 @@ -674,7 +674,7 @@ db_minor = int(m.group(1)) db_ver = (db_major, db_minor) - if ( (not db_ver_inc_map.has_key(db_ver)) and + if ( (db_ver not in db_ver_inc_map) and (db_ver <= max_db_ver and db_ver >= min_db_ver) ): # save the include directory with the db.h version # (first occurrance only) From python-3000-checkins at python.org Sat Aug 19 02:10:29 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sat, 19 Aug 2006 02:10:29 +0200 (CEST) Subject: [Python-3000-checkins] r51394 - python/branches/p3yk/Lib/site.py Message-ID: <20060819001029.24D0C1E4004@bag.python.org> Author: guido.van.rossum Date: Sat Aug 19 02:10:28 2006 New Revision: 51394 Modified: python/branches/p3yk/Lib/site.py Log: When sitecustomize.py fails, don't make all of site.py fail, unless PYTHONVERBOSE is set. Modified: python/branches/p3yk/Lib/site.py ============================================================================== --- python/branches/p3yk/Lib/site.py (original) +++ python/branches/p3yk/Lib/site.py Sat Aug 19 02:10:28 2006 @@ -385,6 +385,13 @@ import sitecustomize except ImportError: pass + except Exception, err: + if os.environ.get("PYTHONVERBOSE"): + raise + sys.stderr.write( + "Error in sitecustomize; set PYTHONVERBOSE for traceback:\n" + "%s: %s\n" % + (err.__class__.__name__, err)) def main(): From python-3000-checkins at python.org Sat Aug 19 04:32:45 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sat, 19 Aug 2006 04:32:45 +0200 (CEST) Subject: [Python-3000-checkins] r51395 - python/branches/p3yk/Lib/xml/etree Message-ID: <20060819023245.229761E4006@bag.python.org> Author: guido.van.rossum Date: Sat Aug 19 04:32:44 2006 New Revision: 51395 Modified: python/branches/p3yk/Lib/xml/etree/ (props changed) Log: Set the svn:ignore property. Why can't this be set once on the root directory? From python-3000-checkins at python.org Sat Aug 19 04:45:07 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sat, 19 Aug 2006 04:45:07 +0200 (CEST) Subject: [Python-3000-checkins] r51396 - in python/branches/p3yk/Lib: ctypes/__init__.py xml/dom/domreg.py xml/dom/minidom.py xml/dom/xmlbuilder.py xml/sax/__init__.py xml/sax/xmlreader.py Message-ID: <20060819024507.A08A81E4006@bag.python.org> Author: guido.van.rossum Date: Sat Aug 19 04:45:06 2006 New Revision: 51396 Modified: python/branches/p3yk/Lib/ctypes/__init__.py python/branches/p3yk/Lib/xml/dom/domreg.py python/branches/p3yk/Lib/xml/dom/minidom.py python/branches/p3yk/Lib/xml/dom/xmlbuilder.py python/branches/p3yk/Lib/xml/sax/__init__.py python/branches/p3yk/Lib/xml/sax/xmlreader.py Log: Fix some more has_key() uses. This could really use a tool to automate... Modified: python/branches/p3yk/Lib/ctypes/__init__.py ============================================================================== --- python/branches/p3yk/Lib/ctypes/__init__.py (original) +++ python/branches/p3yk/Lib/ctypes/__init__.py Sat Aug 19 04:45:06 2006 @@ -265,7 +265,7 @@ if _pointer_type_cache.get(cls, None) is not None: raise RuntimeError, \ "This type already exists in the cache" - if not _pointer_type_cache.has_key(id(pointer)): + if id(pointer) not in _pointer_type_cache: raise RuntimeError, \ "What's this???" pointer.set_type(cls) Modified: python/branches/p3yk/Lib/xml/dom/domreg.py ============================================================================== --- python/branches/p3yk/Lib/xml/dom/domreg.py (original) +++ python/branches/p3yk/Lib/xml/dom/domreg.py Sat Aug 19 04:45:06 2006 @@ -57,7 +57,7 @@ return mod.getDOMImplementation() elif name: return registered[name]() - elif os.environ.has_key("PYTHON_DOM"): + elif "PYTHON_DOM" in os.environ: return getDOMImplementation(name = os.environ["PYTHON_DOM"]) # User did not specify a name, try implementations in arbitrary Modified: python/branches/p3yk/Lib/xml/dom/minidom.py ============================================================================== --- python/branches/p3yk/Lib/xml/dom/minidom.py (original) +++ python/branches/p3yk/Lib/xml/dom/minidom.py Sat Aug 19 04:45:06 2006 @@ -243,7 +243,7 @@ except AttributeError: d = {} self._user_data = d - if d.has_key(key): + if key in d: old = d[key][0] if data is None: # ignore handlers passed for None @@ -494,11 +494,11 @@ L.append(((node.namespaceURI, node.localName), node.value)) return L - def has_key(self, key): + def __contains__(self, key): if isinstance(key, StringTypes): - return self._attrs.has_key(key) + return key in self._attrs else: - return self._attrsNS.has_key(key) + return key in self._attrsNS def keys(self): return self._attrs.keys() @@ -560,7 +560,7 @@ _clear_id_cache(self._ownerElement) del self._attrs[n.nodeName] del self._attrsNS[(n.namespaceURI, n.localName)] - if n.__dict__.has_key('ownerElement'): + if 'ownerElement' in n.__dict__: n.__dict__['ownerElement'] = None return n else: @@ -572,7 +572,7 @@ _clear_id_cache(self._ownerElement) del self._attrsNS[(n.namespaceURI, n.localName)] del self._attrs[n.nodeName] - if n.__dict__.has_key('ownerElement'): + if 'ownerElement' in n.__dict__: n.__dict__['ownerElement'] = None return n else: @@ -779,10 +779,10 @@ removeAttributeNodeNS = removeAttributeNode def hasAttribute(self, name): - return self._attrs.has_key(name) + return name in self._attrs def hasAttributeNS(self, namespaceURI, localName): - return self._attrsNS.has_key((namespaceURI, localName)) + return (namespaceURI, localName) in self._attrsNS def getElementsByTagName(self, name): return _get_elements_by_tagName_helper(self, name, NodeList()) @@ -1660,7 +1660,7 @@ return n def getElementById(self, id): - if self._id_cache.has_key(id): + if id in self._id_cache: return self._id_cache[id] if not (self._elem_info or self._magic_id_count): return None Modified: python/branches/p3yk/Lib/xml/dom/xmlbuilder.py ============================================================================== --- python/branches/p3yk/Lib/xml/dom/xmlbuilder.py (original) +++ python/branches/p3yk/Lib/xml/dom/xmlbuilder.py Sat Aug 19 04:45:06 2006 @@ -91,7 +91,7 @@ def canSetFeature(self, name, state): key = (_name_xform(name), state and 1 or 0) - return self._settings.has_key(key) + return key in self._settings # This dictionary maps from (feature,value) to a list of # (option,value) pairs that should be set on the Options object. @@ -247,7 +247,7 @@ def _guess_media_encoding(self, source): info = source.byteStream.info() - if info.has_key("Content-Type"): + if "Content-Type" in info: for param in info.getplist(): if param.startswith("charset="): return param.split("=", 1)[1].lower() Modified: python/branches/p3yk/Lib/xml/sax/__init__.py ============================================================================== --- python/branches/p3yk/Lib/xml/sax/__init__.py (original) +++ python/branches/p3yk/Lib/xml/sax/__init__.py Sat Aug 19 04:45:06 2006 @@ -59,7 +59,7 @@ import xml.sax.expatreader import os, sys -if os.environ.has_key("PY_SAX_PARSER"): +if "PY_SAX_PARSER" in os.environ: default_parser_list = os.environ["PY_SAX_PARSER"].split(",") del os @@ -81,7 +81,7 @@ return _create_parser(parser_name) except ImportError,e: import sys - if sys.modules.has_key(parser_name): + if parser_name in sys.modules: # The parser module was found, but importing it # failed unexpectedly, pass this exception through raise Modified: python/branches/p3yk/Lib/xml/sax/xmlreader.py ============================================================================== --- python/branches/p3yk/Lib/xml/sax/xmlreader.py (original) +++ python/branches/p3yk/Lib/xml/sax/xmlreader.py Sat Aug 19 04:45:06 2006 @@ -294,12 +294,12 @@ return self._attrs[name] def getNameByQName(self, name): - if not self._attrs.has_key(name): + if name not in self._attrs: raise KeyError, name return name def getQNameByName(self, name): - if not self._attrs.has_key(name): + if name not in self._attrs: raise KeyError, name return name @@ -318,11 +318,8 @@ def keys(self): return self._attrs.keys() - def has_key(self, name): - return self._attrs.has_key(name) - def __contains__(self, name): - return self._attrs.has_key(name) + return name in self._attrs def get(self, name, alternative=None): return self._attrs.get(name, alternative) From python-3000-checkins at python.org Sat Aug 19 17:28:38 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sat, 19 Aug 2006 17:28:38 +0200 (CEST) Subject: [Python-3000-checkins] r51406 - in python/branches/p3yk/Lib: compiler/misc.py compiler/pyassem.py compiler/symbols.py compiler/transformer.py compiler/visitor.py email/_parseaddr.py email/message.py Message-ID: <20060819152838.D626D1E4008@bag.python.org> Author: guido.van.rossum Date: Sat Aug 19 17:28:37 2006 New Revision: 51406 Modified: python/branches/p3yk/Lib/compiler/misc.py python/branches/p3yk/Lib/compiler/pyassem.py python/branches/p3yk/Lib/compiler/symbols.py python/branches/p3yk/Lib/compiler/transformer.py python/branches/p3yk/Lib/compiler/visitor.py python/branches/p3yk/Lib/email/_parseaddr.py python/branches/p3yk/Lib/email/message.py Log: Stomp out more hsa_key() calls. Modified: python/branches/p3yk/Lib/compiler/misc.py ============================================================================== --- python/branches/p3yk/Lib/compiler/misc.py (original) +++ python/branches/p3yk/Lib/compiler/misc.py Sat Aug 19 17:28:37 2006 @@ -14,13 +14,13 @@ def __len__(self): return len(self.elts) def __contains__(self, elt): - return self.elts.has_key(elt) + return elt in self.elts def add(self, elt): self.elts[elt] = elt def elements(self): return self.elts.keys() def has_elt(self, elt): - return self.elts.has_key(elt) + return elt in self.elts def remove(self, elt): del self.elts[elt] def copy(self): Modified: python/branches/p3yk/Lib/compiler/pyassem.py ============================================================================== --- python/branches/p3yk/Lib/compiler/pyassem.py (original) +++ python/branches/p3yk/Lib/compiler/pyassem.py Sat Aug 19 17:28:37 2006 @@ -210,7 +210,7 @@ order = [] seen[b] = b for c in b.get_children(): - if seen.has_key(c): + if c in seen: continue order = order + dfs_postorder(c, seen) order.append(b) @@ -406,7 +406,7 @@ seen = {} def max_depth(b, d): - if seen.has_key(b): + if b in seen: return d seen[b] = 1 d = d + depth[b] @@ -482,7 +482,7 @@ for name in self.cellvars: cells[name] = 1 self.cellvars = [name for name in self.varnames - if cells.has_key(name)] + if name in cells] for name in self.cellvars: del cells[name] self.cellvars = self.cellvars + cells.keys() Modified: python/branches/p3yk/Lib/compiler/symbols.py ============================================================================== --- python/branches/p3yk/Lib/compiler/symbols.py (original) +++ python/branches/p3yk/Lib/compiler/symbols.py Sat Aug 19 17:28:37 2006 @@ -49,9 +49,9 @@ def add_global(self, name): name = self.mangle(name) - if self.uses.has_key(name) or self.defs.has_key(name): + if name in self.uses or name in self.defs: pass # XXX warn about global following def/use - if self.params.has_key(name): + if name in self.params: raise SyntaxError, "%s in %s is global and parameter" % \ (name, self.name) self.globals[name] = 1 @@ -88,14 +88,14 @@ The scope of a name could be LOCAL, GLOBAL, FREE, or CELL. """ - if self.globals.has_key(name): + if name in self.globals: return SC_GLOBAL - if self.cells.has_key(name): + if name in self.cells: return SC_CELL - if self.defs.has_key(name): + if name in self.defs: return SC_LOCAL - if self.nested and (self.frees.has_key(name) or - self.uses.has_key(name)): + if self.nested and (name in self.frees or + name in self.uses): return SC_FREE if self.nested: return SC_UNKNOWN @@ -108,8 +108,8 @@ free = {} free.update(self.frees) for name in self.uses.keys(): - if not (self.defs.has_key(name) or - self.globals.has_key(name)): + if not (name in self.defs or + name in self.globals): free[name] = 1 return free.keys() @@ -134,7 +134,7 @@ free. """ self.globals[name] = 1 - if self.frees.has_key(name): + if name in self.frees: del self.frees[name] for child in self.children: if child.check_name(name) == SC_FREE: Modified: python/branches/p3yk/Lib/compiler/transformer.py ============================================================================== --- python/branches/p3yk/Lib/compiler/transformer.py (original) +++ python/branches/p3yk/Lib/compiler/transformer.py Sat Aug 19 17:28:37 2006 @@ -82,7 +82,7 @@ def Node(*args): kind = args[0] - if nodes.has_key(kind): + if kind in nodes: try: return nodes[kind](*args[1:]) except TypeError: Modified: python/branches/p3yk/Lib/compiler/visitor.py ============================================================================== --- python/branches/p3yk/Lib/compiler/visitor.py (original) +++ python/branches/p3yk/Lib/compiler/visitor.py Sat Aug 19 17:28:37 2006 @@ -84,7 +84,7 @@ meth(node, *args) elif self.VERBOSE > 0: klass = node.__class__ - if not self.examples.has_key(klass): + if klass not in self.examples: self.examples[klass] = klass print print self.visitor Modified: python/branches/p3yk/Lib/email/_parseaddr.py ============================================================================== --- python/branches/p3yk/Lib/email/_parseaddr.py (original) +++ python/branches/p3yk/Lib/email/_parseaddr.py Sat Aug 19 17:28:37 2006 @@ -109,7 +109,7 @@ return None tzoffset = None tz = tz.upper() - if _timezones.has_key(tz): + if tz in _timezones: tzoffset = _timezones[tz] else: try: Modified: python/branches/p3yk/Lib/email/message.py ============================================================================== --- python/branches/p3yk/Lib/email/message.py (original) +++ python/branches/p3yk/Lib/email/message.py Sat Aug 19 17:28:37 2006 @@ -245,16 +245,16 @@ # BAW: should we accept strings that can serve as arguments to the # Charset constructor? self._charset = charset - if not self.has_key('MIME-Version'): + if 'MIME-Version' not in self: self.add_header('MIME-Version', '1.0') - if not self.has_key('Content-Type'): + if 'Content-Type' not in self: self.add_header('Content-Type', 'text/plain', charset=charset.get_output_charset()) else: self.set_param('charset', charset.get_output_charset()) if str(charset) <> charset.get_output_charset(): self._payload = charset.body_encode(self._payload) - if not self.has_key('Content-Transfer-Encoding'): + if 'Content-Transfer-Encoding' not in self: cte = charset.get_body_encoding() try: cte(self) @@ -547,7 +547,7 @@ VALUE item in the 3-tuple) is always unquoted, unless unquote is set to False. """ - if not self.has_key(header): + if header not in self: return failobj for k, v in self._get_params_preserve(failobj, header): if k.lower() == param.lower(): @@ -578,7 +578,7 @@ if not isinstance(value, tuple) and charset: value = (charset, language, value) - if not self.has_key(header) and header.lower() == 'content-type': + if header not in self and header.lower() == 'content-type': ctype = 'text/plain' else: ctype = self.get(header) @@ -613,7 +613,7 @@ False. Optional header specifies an alternative to the Content-Type header. """ - if not self.has_key(header): + if header not in self: return new_ctype = '' for p, v in self.get_params(header=header, unquote=requote): @@ -649,7 +649,7 @@ if header.lower() == 'content-type': del self['mime-version'] self['MIME-Version'] = '1.0' - if not self.has_key(header): + if header not in self: self[header] = type return params = self.get_params(header=header, unquote=requote) From python-3000-checkins at python.org Sat Aug 19 18:09:42 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sat, 19 Aug 2006 18:09:42 +0200 (CEST) Subject: [Python-3000-checkins] r51407 - in python/branches/p3yk/Lib: logging/__init__.py optparse.py Message-ID: <20060819160942.B34241E4008@bag.python.org> Author: guido.van.rossum Date: Sat Aug 19 18:09:41 2006 New Revision: 51407 Modified: python/branches/p3yk/Lib/logging/__init__.py python/branches/p3yk/Lib/optparse.py Log: More has_key() fixes. The optparse fix is a fix to the previous fix, which broke has_option(). Modified: python/branches/p3yk/Lib/logging/__init__.py ============================================================================== --- python/branches/p3yk/Lib/logging/__init__.py (original) +++ python/branches/p3yk/Lib/logging/__init__.py Sat Aug 19 18:09:41 2006 @@ -806,7 +806,7 @@ Add the specified logger as a child of this placeholder. """ #if alogger not in self.loggers: - if not self.loggerMap.has_key(alogger): + if alogger not in self.loggerMap: #self.loggers.append(alogger) self.loggerMap[alogger] = None @@ -863,7 +863,7 @@ rv = None _acquireLock() try: - if self.loggerDict.has_key(name): + if name in self.loggerDict: rv = self.loggerDict[name] if isinstance(rv, PlaceHolder): ph = rv @@ -891,7 +891,7 @@ rv = None while (i > 0) and not rv: substr = name[:i] - if not self.loggerDict.has_key(substr): + if substr not in self.loggerDict: self.loggerDict[substr] = PlaceHolder(alogger) else: obj = self.loggerDict[substr] Modified: python/branches/p3yk/Lib/optparse.py ============================================================================== --- python/branches/p3yk/Lib/optparse.py (original) +++ python/branches/p3yk/Lib/optparse.py Sat Aug 19 18:09:41 2006 @@ -1040,7 +1040,7 @@ def has_option(self, opt_str): return (opt_str in self._short_opt or - opt_str) in self._long_opt + opt_str in self._long_opt) def remove_option(self, opt_str): option = self._short_opt.get(opt_str) From python-3000-checkins at python.org Sat Aug 19 18:14:31 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sat, 19 Aug 2006 18:14:31 +0200 (CEST) Subject: [Python-3000-checkins] r51408 - python/branches/p3yk/Lib/test/output/test_operations Message-ID: <20060819161431.8F1681E4008@bag.python.org> Author: guido.van.rossum Date: Sat Aug 19 18:14:31 2006 New Revision: 51408 Modified: python/branches/p3yk/Lib/test/output/test_operations Log: Another has_key reference bites the dust. Modified: python/branches/p3yk/Lib/test/output/test_operations ============================================================================== --- python/branches/p3yk/Lib/test/output/test_operations (original) +++ python/branches/p3yk/Lib/test/output/test_operations Sat Aug 19 18:14:31 2006 @@ -9,8 +9,6 @@ raising error x2 in d: caught the RuntimeError outside raising error -d.has_key(x2): caught the RuntimeError outside -raising error d.get(x2): caught the RuntimeError outside raising error d.setdefault(x2, 42): caught the RuntimeError outside From python-3000-checkins at python.org Sat Aug 19 18:17:20 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sat, 19 Aug 2006 18:17:20 +0200 (CEST) Subject: [Python-3000-checkins] r51409 - in python/branches/p3yk/Lib: filecmp.py hotshot/log.py Message-ID: <20060819161720.707E61E4022@bag.python.org> Author: guido.van.rossum Date: Sat Aug 19 18:17:20 2006 New Revision: 51409 Modified: python/branches/p3yk/Lib/filecmp.py python/branches/p3yk/Lib/hotshot/log.py Log: Only three failing tests left: dbm, gdbm, tcl! Modified: python/branches/p3yk/Lib/filecmp.py ============================================================================== --- python/branches/p3yk/Lib/filecmp.py (original) +++ python/branches/p3yk/Lib/filecmp.py Sat Aug 19 18:17:20 2006 @@ -132,9 +132,9 @@ def phase1(self): # Compute common names a = dict(izip(imap(os.path.normcase, self.left_list), self.left_list)) b = dict(izip(imap(os.path.normcase, self.right_list), self.right_list)) - self.common = map(a.__getitem__, ifilter(b.has_key, a)) - self.left_only = map(a.__getitem__, ifilterfalse(b.has_key, a)) - self.right_only = map(b.__getitem__, ifilterfalse(a.has_key, b)) + self.common = map(a.__getitem__, ifilter(b.__contains__, a)) + self.left_only = map(a.__getitem__, ifilterfalse(b.__contains__, a)) + self.right_only = map(b.__getitem__, ifilterfalse(a.__contains__, b)) def phase2(self): # Distinguish files, directories, funnies self.common_dirs = [] Modified: python/branches/p3yk/Lib/hotshot/log.py ============================================================================== --- python/branches/p3yk/Lib/hotshot/log.py (original) +++ python/branches/p3yk/Lib/hotshot/log.py Sat Aug 19 18:17:20 2006 @@ -31,7 +31,7 @@ self._reader = _hotshot.logreader(logfn) self._nextitem = self._reader.next self._info = self._reader.info - if self._info.has_key('current-directory'): + if 'current-directory' in self._info: self.cwd = self._info['current-directory'] else: self.cwd = None From python-3000-checkins at python.org Sat Aug 19 18:53:46 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sat, 19 Aug 2006 18:53:46 +0200 (CEST) Subject: [Python-3000-checkins] r51410 - python/branches/p3yk/Lib/lib-tk/FileDialog.py python/branches/p3yk/Lib/lib-tk/FixTk.py python/branches/p3yk/Lib/lib-tk/Tix.py python/branches/p3yk/Lib/lib-tk/Tkinter.py python/branches/p3yk/Lib/lib-tk/tkSimpleDialog.py Message-ID: <20060819165346.DCB081E4008@bag.python.org> Author: guido.van.rossum Date: Sat Aug 19 18:53:45 2006 New Revision: 51410 Modified: python/branches/p3yk/Lib/lib-tk/FileDialog.py python/branches/p3yk/Lib/lib-tk/FixTk.py python/branches/p3yk/Lib/lib-tk/Tix.py python/branches/p3yk/Lib/lib-tk/Tkinter.py python/branches/p3yk/Lib/lib-tk/tkSimpleDialog.py Log: Couple more has_keys() going... Modified: python/branches/p3yk/Lib/lib-tk/FileDialog.py ============================================================================== --- python/branches/p3yk/Lib/lib-tk/FileDialog.py (original) +++ python/branches/p3yk/Lib/lib-tk/FileDialog.py Sat Aug 19 18:53:45 2006 @@ -107,7 +107,7 @@ self.top.bind('', self.cancel_command) def go(self, dir_or_file=os.curdir, pattern="*", default="", key=None): - if key and dialogstates.has_key(key): + if key and key in dialogstates: self.directory, pattern = dialogstates[key] else: dir_or_file = os.path.expanduser(dir_or_file) Modified: python/branches/p3yk/Lib/lib-tk/FixTk.py ============================================================================== --- python/branches/p3yk/Lib/lib-tk/FixTk.py (original) +++ python/branches/p3yk/Lib/lib-tk/FixTk.py Sat Aug 19 18:53:45 2006 @@ -13,7 +13,7 @@ prefix = os.path.join(sys.prefix,"tcl") # if this does not exist, no further search is needed if os.path.exists(prefix): - if not os.environ.has_key("TCL_LIBRARY"): + if "TCL_LIBRARY" not in os.environ: for name in os.listdir(prefix): if name.startswith("tcl"): tcldir = os.path.join(prefix,name) @@ -23,13 +23,13 @@ # as Tcl import _tkinter ver = str(_tkinter.TCL_VERSION) - if not os.environ.has_key("TK_LIBRARY"): + if "TK_LIBRARY" not in os.environ: v = os.path.join(prefix, 'tk'+ver) if os.path.exists(os.path.join(v, "tclIndex")): os.environ['TK_LIBRARY'] = v # We don't know the Tix version, so we must search the entire # directory - if not os.environ.has_key("TIX_LIBRARY"): + if "TIX_LIBRARY" not in os.environ: for name in os.listdir(prefix): if name.startswith("tix"): tixdir = os.path.join(prefix,name) Modified: python/branches/p3yk/Lib/lib-tk/Tix.py ============================================================================== --- python/branches/p3yk/Lib/lib-tk/Tix.py (original) +++ python/branches/p3yk/Lib/lib-tk/Tix.py Sat Aug 19 18:53:45 2006 @@ -321,7 +321,7 @@ # We can even do w.ok.invoke() because w.ok is subclassed from the # Button class if you go through the proper constructors def __getattr__(self, name): - if self.subwidget_list.has_key(name): + if name in self.subwidget_list: return self.subwidget_list[name] raise AttributeError, name @@ -446,9 +446,9 @@ # also destroys the parent NoteBook thus leading to an exception # in Tkinter when it finally calls Tcl to destroy the NoteBook for c in self.children.values(): c.destroy() - if self.master.children.has_key(self._name): + if self._name in self.master.children: del self.master.children[self._name] - if self.master.subwidget_list.has_key(self._name): + if self._name in self.master.subwidget_list: del self.master.subwidget_list[self._name] if self.destroy_physically: # This is bypassed only for a few widgets @@ -470,8 +470,8 @@ def __init__(self, itemtype, cnf={}, **kw): master = _default_root # global from Tkinter - if not master and cnf.has_key('refwindow'): master=cnf['refwindow'] - elif not master and kw.has_key('refwindow'): master= kw['refwindow'] + if not master and 'refwindow' in cnf: master=cnf['refwindow'] + elif not master and 'refwindow' in kw: master= kw['refwindow'] elif not master: raise RuntimeError, "Too early to create display style: no root window" self.tk = master.tk self.stylename = self.tk.call('tixDisplayStyle', itemtype, @@ -553,7 +553,7 @@ return btn def invoke(self, name): - if self.subwidget_list.has_key(name): + if name in self.subwidget_list: self.tk.call(self._w, 'invoke', name) class ComboBox(TixWidget): @@ -1413,7 +1413,7 @@ self.subwidget_list['help'] = _dummyButton(self, 'help') def invoke(self, name): - if self.subwidget_list.has_key(name): + if name in self.subwidget_list: self.tk.call(self._w, 'invoke', name) class TList(TixWidget): Modified: python/branches/p3yk/Lib/lib-tk/Tkinter.py ============================================================================== --- python/branches/p3yk/Lib/lib-tk/Tkinter.py (original) +++ python/branches/p3yk/Lib/lib-tk/Tkinter.py Sat Aug 19 18:53:45 2006 @@ -550,7 +550,7 @@ A widget specified for the optional displayof keyword argument specifies the target display.""" - if not kw.has_key('displayof'): kw['displayof'] = self._w + if 'displayof' not in kw: kw['displayof'] = self._w self.tk.call(('clipboard', 'clear') + self._options(kw)) def clipboard_append(self, string, **kw): """Append STRING to the Tk clipboard. @@ -558,7 +558,7 @@ A widget specified at the optional displayof keyword argument specifies the target display. The clipboard can be retrieved with selection_get.""" - if not kw.has_key('displayof'): kw['displayof'] = self._w + if 'displayof' not in kw: kw['displayof'] = self._w self.tk.call(('clipboard', 'append') + self._options(kw) + ('--', string)) # XXX grab current w/o window argument @@ -619,7 +619,7 @@ self.tk.call('option', 'readfile', fileName, priority) def selection_clear(self, **kw): """Clear the current X selection.""" - if not kw.has_key('displayof'): kw['displayof'] = self._w + if 'displayof' not in kw: kw['displayof'] = self._w self.tk.call(('selection', 'clear') + self._options(kw)) def selection_get(self, **kw): """Return the contents of the current X selection. @@ -628,7 +628,7 @@ the selection and defaults to PRIMARY. A keyword parameter displayof specifies a widget on the display to use.""" - if not kw.has_key('displayof'): kw['displayof'] = self._w + if 'displayof' not in kw: kw['displayof'] = self._w return self.tk.call(('selection', 'get') + self._options(kw)) def selection_handle(self, command, **kw): """Specify a function COMMAND to call if the X @@ -659,7 +659,7 @@ be provided: selection - name of the selection (default PRIMARY), type - type of the selection (e.g. STRING, FILE_NAME).""" - if not kw.has_key('displayof'): kw['displayof'] = self._w + if 'displayof' not in kw: kw['displayof'] = self._w name = self.tk.call(('selection', 'own') + self._options(kw)) if not name: return None return self._nametowidget(name) @@ -1692,7 +1692,7 @@ the Tcl Interpreter and calls execfile on BASENAME.py and CLASSNAME.py if such a file exists in the home directory.""" import os - if os.environ.has_key('HOME'): home = os.environ['HOME'] + if 'HOME' in os.environ: home = os.environ['HOME'] else: home = os.curdir class_tcl = os.path.join(home, '.%s.tcl' % className) class_py = os.path.join(home, '.%s.py' % className) @@ -1808,7 +1808,7 @@ into account """ for k in ['in_']: - if kw.has_key(k): + if k in kw: kw[k[:-1]] = kw[k] del kw[k] self.tk.call( @@ -1900,7 +1900,7 @@ self.master = master self.tk = master.tk name = None - if cnf.has_key('name'): + if 'name' in cnf: name = cnf['name'] del cnf['name'] if not name: @@ -1911,7 +1911,7 @@ else: self._w = master._w + '.' + name self.children = {} - if self.master.children.has_key(self._name): + if self._name in self.master.children: self.master.children[self._name].destroy() self.master.children[self._name] = self def __init__(self, master, widgetName, cnf={}, kw={}, extra=()): @@ -1934,7 +1934,7 @@ """Destroy this and all descendants widgets.""" for c in self.children.values(): c.destroy() self.tk.call('destroy', self._w) - if self.master.children.has_key(self._name): + if self._name in self.master.children: del self.master.children[self._name] Misc.destroy(self) def _do(self, name, args=()): @@ -1962,7 +1962,7 @@ extra = () for wmkey in ['screen', 'class_', 'class', 'visual', 'colormap']: - if cnf.has_key(wmkey): + if wmkey in cnf: val = cnf[wmkey] # TBD: a hack needed because some keys # are not valid as keyword arguments @@ -2433,10 +2433,10 @@ highlightcolor, highlightthickness, relief, takefocus, visual, width.""" cnf = _cnfmerge((cnf, kw)) extra = () - if cnf.has_key('class_'): + if 'class_' in cnf: extra = ('-class', cnf['class_']) del cnf['class_'] - elif cnf.has_key('class'): + elif 'class' in cnf: extra = ('-class', cnf['class']) del cnf['class'] Widget.__init__(self, master, 'frame', cnf, {}, extra) @@ -3179,7 +3179,7 @@ self.menuname = menu._w # 'command' is the only supported keyword callback = kwargs.get('command') - if kwargs.has_key('command'): + if 'command' in kwargs: del kwargs['command'] if kwargs: raise TclError, 'unknown option -'+kwargs.keys()[0] Modified: python/branches/p3yk/Lib/lib-tk/tkSimpleDialog.py ============================================================================== --- python/branches/p3yk/Lib/lib-tk/tkSimpleDialog.py (original) +++ python/branches/p3yk/Lib/lib-tk/tkSimpleDialog.py Sat Aug 19 18:53:45 2006 @@ -274,7 +274,7 @@ class _QueryString(_QueryDialog): def __init__(self, *args, **kw): - if kw.has_key("show"): + if "show" in kw: self.__show = kw["show"] del kw["show"] else: From python-3000-checkins at python.org Sun Aug 20 01:11:48 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sun, 20 Aug 2006 01:11:48 +0200 (CEST) Subject: [Python-3000-checkins] r51412 - python/branches/p3yk/Modules/dbmmodule.c Message-ID: <20060819231148.5F3E91E4008@bag.python.org> Author: guido.van.rossum Date: Sun Aug 20 01:11:47 2006 New Revision: 51412 Modified: python/branches/p3yk/Modules/dbmmodule.c Log: Fix this right for has_key(). This required adding tp_as_sequence. Modified: python/branches/p3yk/Modules/dbmmodule.c ============================================================================== --- python/branches/p3yk/Modules/dbmmodule.c (original) +++ python/branches/p3yk/Modules/dbmmodule.c Sun Aug 20 01:11:47 2006 @@ -205,20 +205,42 @@ return v; } -static PyObject * -dbm_contains(register dbmobject *dp, PyObject *args) +static int +dbm_contains(PyObject *self, PyObject *arg) { + dbmobject *dp = (dbmobject *)self; datum key, val; - int tmp_size; - - if (!PyArg_ParseTuple(args, "s#:__contains__", &key.dptr, &tmp_size)) - return NULL; - key.dsize = tmp_size; - check_dbmobject_open(dp); + + if ((dp)->di_dbm == NULL) { + PyErr_SetString(DbmError, + "DBM object has already been closed"); + return -1; + } + if (!PyString_Check(arg)) { + PyErr_Format(PyExc_TypeError, + "dbm key must be string, not %.100s", + arg->ob_type->tp_name); + return -1; + } + key.dptr = PyString_AS_STRING(arg); + key.dsize = PyString_GET_SIZE(arg); val = dbm_fetch(dp->di_dbm, key); - return PyInt_FromLong(val.dptr != NULL); + return val.dptr != NULL; } +static PySequenceMethods dbm_as_sequence = { + 0, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + dbm_contains, /* sq_contains */ + 0, /* sq_inplace_concat */ + 0, /* sq_inplace_repeat */ +}; + static PyObject * dbm_get(register dbmobject *dp, PyObject *args) { @@ -277,8 +299,6 @@ "close()\nClose the database."}, {"keys", (PyCFunction)dbm_keys, METH_NOARGS, "keys() -> list\nReturn a list of all keys in the database."}, - {"__contains__",(PyCFunction)dbm_contains, METH_VARARGS, - "__contains__(key} -> boolean\True iff key is in the database."}, {"get", (PyCFunction)dbm_get, METH_VARARGS, "get(key[, default]) -> value\n" "Return the value for key if present, otherwise default."}, @@ -308,7 +328,7 @@ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ + &dbm_as_sequence, /*tp_as_sequence*/ &dbm_as_mapping, /*tp_as_mapping*/ }; @@ -353,7 +373,8 @@ initdbm(void) { PyObject *m, *d, *s; - Dbmtype.ob_type = &PyType_Type; + if (PyType_Ready(&Dbmtype) < 0) + return; m = Py_InitModule("dbm", dbmmodule_methods); if (m == NULL) return; From python-3000-checkins at python.org Sun Aug 20 01:18:49 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sun, 20 Aug 2006 01:18:49 +0200 (CEST) Subject: [Python-3000-checkins] r51413 - python/branches/p3yk/Modules/gdbmmodule.c Message-ID: <20060819231849.27C2F1E4009@bag.python.org> Author: guido.van.rossum Date: Sun Aug 20 01:18:48 2006 New Revision: 51413 Modified: python/branches/p3yk/Modules/gdbmmodule.c Log: And the gdbm module's test now passes again. Modified: python/branches/p3yk/Modules/gdbmmodule.c ============================================================================== --- python/branches/p3yk/Modules/gdbmmodule.c (original) +++ python/branches/p3yk/Modules/gdbmmodule.c Sun Aug 20 01:18:48 2006 @@ -241,21 +241,41 @@ return v; } -PyDoc_STRVAR(dbm_contains__doc__, -"__contains__(key) -> bool\n\ -Find out whether or not the database contains a given key."); - -static PyObject * -dbm_contains(register dbmobject *dp, PyObject *args) +static int +dbm_contains(PyObject *self, PyObject *arg) { + dbmobject *dp = (dbmobject *)self; datum key; - if (!PyArg_ParseTuple(args, "s#:contains", &key.dptr, &key.dsize)) - return NULL; - check_dbmobject_open(dp); - return PyInt_FromLong((long) gdbm_exists(dp->di_dbm, key)); + if ((dp)->di_dbm == NULL) { + PyErr_SetString(DbmError, + "GDBM object has already been closed"); + return -1; + } + if (!PyString_Check(arg)) { + PyErr_Format(PyExc_TypeError, + "gdbm key must be string, not %.100s", + arg->ob_type->tp_name); + return -1; + } + key.dptr = PyString_AS_STRING(arg); + key.dsize = PyString_GET_SIZE(arg); + return gdbm_exists(dp->di_dbm, key); } +static PySequenceMethods dbm_as_sequence = { + 0, /* sq_length */ + 0, /* sq_concat */ + 0, /* sq_repeat */ + 0, /* sq_item */ + 0, /* sq_slice */ + 0, /* sq_ass_item */ + 0, /* sq_ass_slice */ + dbm_contains, /* sq_contains */ + 0, /* sq_inplace_concat */ + 0, /* sq_inplace_repeat */ +}; + PyDoc_STRVAR(dbm_firstkey__doc__, "firstkey() -> key\n\ It's possible to loop over every key in the database using this method\n\ @@ -355,7 +375,6 @@ static PyMethodDef dbm_methods[] = { {"close", (PyCFunction)dbm_close, METH_NOARGS, dbm_close__doc__}, {"keys", (PyCFunction)dbm_keys, METH_NOARGS, dbm_keys__doc__}, - {"__contains__",(PyCFunction)dbm_contains,METH_VARARGS, dbm_contains__doc__}, {"firstkey", (PyCFunction)dbm_firstkey,METH_NOARGS, dbm_firstkey__doc__}, {"nextkey", (PyCFunction)dbm_nextkey, METH_VARARGS, dbm_nextkey__doc__}, {"reorganize",(PyCFunction)dbm_reorganize,METH_NOARGS, dbm_reorganize__doc__}, @@ -382,7 +401,7 @@ 0, /*tp_compare*/ 0, /*tp_repr*/ 0, /*tp_as_number*/ - 0, /*tp_as_sequence*/ + &dbm_as_sequence, /*tp_as_sequence*/ &dbm_as_mapping, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ @@ -498,7 +517,8 @@ initgdbm(void) { PyObject *m, *d, *s; - Dbmtype.ob_type = &PyType_Type; + if (PyType_Ready(&Dbmtype) < 0) + return; m = Py_InitModule4("gdbm", dbmmodule_methods, gdbmmodule__doc__, (PyObject *)NULL, PYTHON_API_VERSION); From python-3000-checkins at python.org Sun Aug 20 18:25:11 2006 From: python-3000-checkins at python.org (neal.norwitz) Date: Sun, 20 Aug 2006 18:25:11 +0200 (CEST) Subject: [Python-3000-checkins] r51418 - in python/branches/p3yk/Lib: distutils/dir_util.py distutils/msvccompiler.py encodings/__init__.py msilib/__init__.py plat-mac/EasyDialogs.py plat-mac/FrameWork.py plat-mac/MiniAEFrame.py plat-mac/aepack.py plat-mac/aetools.py plat-mac/aetypes.py plat-mac/bundlebuilder.py plat-mac/findertools.py plat-mac/gensuitemodule.py plat-mac/ic.py plat-mac/macresource.py plat-mac/pimp.py Message-ID: <20060820162511.E65FC1E4014@bag.python.org> Author: neal.norwitz Date: Sun Aug 20 18:25:10 2006 New Revision: 51418 Modified: python/branches/p3yk/Lib/distutils/dir_util.py python/branches/p3yk/Lib/distutils/msvccompiler.py python/branches/p3yk/Lib/encodings/__init__.py python/branches/p3yk/Lib/msilib/__init__.py python/branches/p3yk/Lib/plat-mac/EasyDialogs.py python/branches/p3yk/Lib/plat-mac/FrameWork.py python/branches/p3yk/Lib/plat-mac/MiniAEFrame.py python/branches/p3yk/Lib/plat-mac/aepack.py python/branches/p3yk/Lib/plat-mac/aetools.py python/branches/p3yk/Lib/plat-mac/aetypes.py python/branches/p3yk/Lib/plat-mac/bundlebuilder.py python/branches/p3yk/Lib/plat-mac/findertools.py python/branches/p3yk/Lib/plat-mac/gensuitemodule.py python/branches/p3yk/Lib/plat-mac/ic.py python/branches/p3yk/Lib/plat-mac/macresource.py python/branches/p3yk/Lib/plat-mac/pimp.py Log: Get rid of a bunch more has_key() uses. We *really* need a tool for this. test_aepack now passes. IDLE still needs to be converted (among others). Modified: python/branches/p3yk/Lib/distutils/dir_util.py ============================================================================== --- python/branches/p3yk/Lib/distutils/dir_util.py (original) +++ python/branches/p3yk/Lib/distutils/dir_util.py Sun Aug 20 18:25:10 2006 @@ -207,7 +207,7 @@ cmd[0](cmd[1]) # remove dir from cache if it's already there abspath = os.path.abspath(cmd[1]) - if _path_created.has_key(abspath): + if abspath in _path_created: del _path_created[abspath] except (IOError, OSError), exc: log.warn(grok_environment_error( Modified: python/branches/p3yk/Lib/distutils/msvccompiler.py ============================================================================== --- python/branches/p3yk/Lib/distutils/msvccompiler.py (original) +++ python/branches/p3yk/Lib/distutils/msvccompiler.py Sun Aug 20 18:25:10 2006 @@ -239,7 +239,7 @@ def initialize(self): self.__paths = [] - if os.environ.has_key("DISTUTILS_USE_SDK") and os.environ.has_key("MSSdk") and self.find_exe("cl.exe"): + if "DISTUTILS_USE_SDK" in os.environ and "MSSdk" in os.environ and self.find_exe("cl.exe"): # Assume that the SDK set up everything alright; don't try to be # smarter self.cc = "cl.exe" Modified: python/branches/p3yk/Lib/encodings/__init__.py ============================================================================== --- python/branches/p3yk/Lib/encodings/__init__.py (original) +++ python/branches/p3yk/Lib/encodings/__init__.py Sun Aug 20 18:25:10 2006 @@ -144,7 +144,7 @@ pass else: for alias in codecaliases: - if not _aliases.has_key(alias): + if alias not in _aliases: _aliases[alias] = modname # Return the registry entry Modified: python/branches/p3yk/Lib/msilib/__init__.py ============================================================================== --- python/branches/p3yk/Lib/msilib/__init__.py (original) +++ python/branches/p3yk/Lib/msilib/__init__.py Sun Aug 20 18:25:10 2006 @@ -326,7 +326,7 @@ file = os.path.basename(file) absolute = os.path.join(self.absolute, src) assert not re.search(r'[\?|><:/*]"', file) # restrictions on long names - if self.keyfiles.has_key(file): + if file in self.keyfiles: logical = self.keyfiles[file] else: logical = None Modified: python/branches/p3yk/Lib/plat-mac/EasyDialogs.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/EasyDialogs.py (original) +++ python/branches/p3yk/Lib/plat-mac/EasyDialogs.py Sun Aug 20 18:25:10 2006 @@ -577,9 +577,9 @@ if args[k] is None: del args[k] # Set some defaults, and modify some arguments - if not args.has_key('dialogOptionFlags'): + if 'dialogOptionFlags' not in args: args['dialogOptionFlags'] = dftflags - if args.has_key('defaultLocation') and \ + if 'defaultLocation' in args and \ not isinstance(args['defaultLocation'], Carbon.AE.AEDesc): defaultLocation = args['defaultLocation'] if isinstance(defaultLocation, (Carbon.File.FSSpec, Carbon.File.FSRef)): @@ -587,7 +587,7 @@ else: defaultLocation = Carbon.File.FSRef(defaultLocation) args['defaultLocation'] = aepack.pack(defaultLocation) - if args.has_key('typeList') and not isinstance(args['typeList'], Carbon.Res.ResourceType): + if 'typeList' in args and not isinstance(args['typeList'], Carbon.Res.ResourceType): typeList = args['typeList'][:] # Workaround for OSX typeless files: if 'TEXT' in typeList and not '\0\0\0\0' in typeList: @@ -597,7 +597,7 @@ data = data+type args['typeList'] = Carbon.Res.Handle(data) tpwanted = str - if args.has_key('wanted'): + if 'wanted' in args: tpwanted = args['wanted'] del args['wanted'] return args, tpwanted Modified: python/branches/p3yk/Lib/plat-mac/FrameWork.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/FrameWork.py (original) +++ python/branches/p3yk/Lib/plat-mac/FrameWork.py Sun Aug 20 18:25:10 2006 @@ -216,7 +216,7 @@ if self.do_dialogevent(event): return (what, message, when, where, modifiers) = event - if eventname.has_key(what): + if what in eventname: name = "do_" + eventname[what] else: name = "do_%d" % what @@ -247,7 +247,7 @@ gotone, dlg, item = DialogSelect(event) if gotone: window = dlg.GetDialogWindow() - if self._windows.has_key(window): + if window in self._windows: self._windows[window].do_itemhit(item, event) else: print 'Dialog event for unknown dialog' @@ -261,7 +261,7 @@ # # Find the correct name. # - if partname.has_key(partcode): + if partcode in partname: name = "do_" + partname[partcode] else: name = "do_%d" % partcode @@ -276,7 +276,7 @@ if hasattr(MacOS, 'HandleEvent'): MacOS.HandleEvent(event) return - elif self._windows.has_key(wid): + elif wid in self._windows: # It is a window. Hand off to correct window. window = self._windows[wid] try: @@ -363,7 +363,7 @@ else: # See whether the front window wants it w = MyFrontWindow() - if w and self._windows.has_key(w): + if w and w in self._windows: window = self._windows[w] try: do_char = window.do_char @@ -378,7 +378,7 @@ def do_updateEvt(self, event): (what, message, when, where, modifiers) = event wid = WhichWindow(message) - if wid and self._windows.has_key(wid): + if wid and wid in self._windows: window = self._windows[wid] window.do_rawupdate(wid, event) else: @@ -388,7 +388,7 @@ def do_activateEvt(self, event): (what, message, when, where, modifiers) = event wid = WhichWindow(message) - if wid and self._windows.has_key(wid): + if wid and wid in self._windows: window = self._windows[wid] window.do_activate(modifiers & 1, event) else: @@ -408,7 +408,7 @@ def do_suspendresume(self, event): (what, message, when, where, modifiers) = event wid = MyFrontWindow() - if wid and self._windows.has_key(wid): + if wid and wid in self._windows: window = self._windows[wid] window.do_activate(message & 1, event) @@ -432,7 +432,7 @@ def printevent(self, event): (what, message, when, where, modifiers) = event nicewhat = repr(what) - if eventname.has_key(what): + if what in eventname: nicewhat = eventname[what] print nicewhat, if what == kHighLevelEvent: @@ -512,7 +512,7 @@ label, shortcut, callback, kind = menu.items[i] if type(callback) == types.StringType: wid = MyFrontWindow() - if wid and self.parent._windows.has_key(wid): + if wid and wid in self.parent._windows: window = self.parent._windows[wid] if hasattr(window, "domenu_" + callback): menu.menu.EnableMenuItem(i + 1) @@ -528,7 +528,7 @@ pass def dispatch(self, id, item, window, event): - if self.menus.has_key(id): + if id in self.menus: self.menus[id].dispatch(id, item, window, event) else: if DEBUG: print "MenuBar.dispatch(%d, %d, %s, %s)" % \ @@ -607,7 +607,7 @@ else: # callback is string wid = MyFrontWindow() - if wid and self.bar.parent._windows.has_key(wid): + if wid and wid in self.bar.parent._windows: window = self.bar.parent._windows[wid] if hasattr(window, "domenu_" + callback): menuhandler = getattr(window, "domenu_" + callback) Modified: python/branches/p3yk/Lib/plat-mac/MiniAEFrame.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/MiniAEFrame.py (original) +++ python/branches/p3yk/Lib/plat-mac/MiniAEFrame.py Sun Aug 20 18:25:10 2006 @@ -134,11 +134,11 @@ _class = _attributes['evcl'].type _type = _attributes['evid'].type - if self.ae_handlers.has_key((_class, _type)): + if (_class, _type) in self.ae_handlers: _function = self.ae_handlers[(_class, _type)] - elif self.ae_handlers.has_key((_class, '****')): + elif (_class, '****') in self.ae_handlers: _function = self.ae_handlers[(_class, '****')] - elif self.ae_handlers.has_key(('****', '****')): + elif ('****', '****') in self.ae_handlers: _function = self.ae_handlers[('****', '****')] else: raise 'Cannot happen: AE callback without handler', (_class, _type) @@ -148,7 +148,7 @@ _parameters['_attributes'] = _attributes _parameters['_class'] = _class _parameters['_type'] = _type - if _parameters.has_key('----'): + if '----' in _parameters: _object = _parameters['----'] del _parameters['----'] # The try/except that used to be here can mask programmer errors. Modified: python/branches/p3yk/Lib/plat-mac/aepack.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/aepack.py (original) +++ python/branches/p3yk/Lib/plat-mac/aepack.py Sun Aug 20 18:25:10 2006 @@ -129,7 +129,7 @@ """Unpack an AE descriptor to a python object""" t = desc.type - if unpacker_coercions.has_key(t): + if t in unpacker_coercions: desc = desc.AECoerceDesc(unpacker_coercions[t]) t = desc.type # This is a guess by Jack.... Modified: python/branches/p3yk/Lib/plat-mac/aetools.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/aetools.py (original) +++ python/branches/p3yk/Lib/plat-mac/aetools.py Sun Aug 20 18:25:10 2006 @@ -107,7 +107,7 @@ """Replace long name keys by their 4-char counterparts, and check""" ok = keydict.values() for k in arguments.keys(): - if keydict.has_key(k): + if k in keydict: v = arguments[k] del arguments[k] arguments[keydict[k]] = v @@ -116,11 +116,11 @@ def enumsubst(arguments, key, edict): """Substitute a single enum keyword argument, if it occurs""" - if not arguments.has_key(key) or edict is None: + if key not in arguments or edict is None: return v = arguments[key] ok = edict.values() - if edict.has_key(v): + if v in edict: arguments[key] = Enum(edict[v]) elif not v in ok: raise TypeError, 'Unknown enumerator: %s'%v @@ -129,11 +129,11 @@ """Create the 'best' argument for a raise MacOS.Error""" errn = arguments['errn'] err_a1 = errn - if arguments.has_key('errs'): + if 'errs' in arguments: err_a2 = arguments['errs'] else: err_a2 = MacOS.GetErrorString(errn) - if arguments.has_key('erob'): + if 'erob' in arguments: err_a3 = arguments['erob'] else: err_a3 = None @@ -248,10 +248,10 @@ _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) - if _arguments.has_key('errn'): + if 'errn' in _arguments: raise Error, decodeerror(_arguments) - if _arguments.has_key('----'): + if '----' in _arguments: return _arguments['----'] if asfile: item.__class__ = asfile @@ -281,7 +281,7 @@ if _arguments.get('errn', 0): raise Error, decodeerror(_arguments) # XXXX Optionally decode result - if _arguments.has_key('----'): + if '----' in _arguments: return _arguments['----'] set = _set @@ -290,10 +290,10 @@ # like the "application" class in OSA. def __getattr__(self, name): - if self._elemdict.has_key(name): + if name in self._elemdict: cls = self._elemdict[name] return DelayedComponentItem(cls, None) - if self._propdict.has_key(name): + if name in self._propdict: cls = self._propdict[name] return cls() raise AttributeError, name @@ -315,10 +315,10 @@ _reply, _arguments, _attributes = self.send(_code, _subcode, _arguments, _attributes) - if _arguments.has_key('errn'): + if 'errn' in _arguments: raise Error, decodeerror(_arguments) # XXXX Optionally decode result - if _arguments.has_key('----'): + if '----' in _arguments: return _arguments['----'] #pass Modified: python/branches/p3yk/Lib/plat-mac/aetypes.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/aetypes.py (original) +++ python/branches/p3yk/Lib/plat-mac/aetypes.py Sun Aug 20 18:25:10 2006 @@ -530,10 +530,10 @@ return s def __getattr__(self, name): - if self._elemdict.has_key(name): + if name in self._elemdict: cls = self._elemdict[name] return DelayedComponentItem(cls, self) - if self._propdict.has_key(name): + if name in self._propdict: cls = self._propdict[name] return cls(self) raise AttributeError, name Modified: python/branches/p3yk/Lib/plat-mac/bundlebuilder.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/bundlebuilder.py (original) +++ python/branches/p3yk/Lib/plat-mac/bundlebuilder.py Sun Aug 20 18:25:10 2006 @@ -481,7 +481,7 @@ if self.standalone or self.semi_standalone: self.includeModules.append("argvemulator") self.includeModules.append("os") - if not self.plist.has_key("CFBundleDocumentTypes"): + if "CFBundleDocumentTypes" not in self.plist: self.plist["CFBundleDocumentTypes"] = [ { "CFBundleTypeOSTypes" : [ "****", Modified: python/branches/p3yk/Lib/plat-mac/findertools.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/findertools.py (original) +++ python/branches/p3yk/Lib/plat-mac/findertools.py Sun Aug 20 18:25:10 2006 @@ -139,9 +139,9 @@ args['----'] = aeobj_01 args["data"] = comment _reply, args, attrs = finder.send("core", "setd", args, attrs) - if args.has_key('errn'): + if 'errn' in args: raise Error, aetools.decodeerror(args) - if args.has_key('----'): + if '----' in args: return args['----'] def _getcomment(object_alias): @@ -152,9 +152,9 @@ aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('comt'), fr=aeobj_00) args['----'] = aeobj_01 _reply, args, attrs = finder.send("core", "getd", args, attrs) - if args.has_key('errn'): + if 'errn' in args: raise Error, aetools.decodeerror(args) - if args.has_key('----'): + if '----' in args: return args['----'] @@ -174,10 +174,10 @@ ## get the processnames or else the processnumbers args['----'] = aetypes.ObjectSpecifier(want=aetypes.Type('prcs'), form="indx", seld=aetypes.Unknown('abso', "all "), fr=None) _reply, args, attrs = finder.send('core', 'getd', args, attrs) - if args.has_key('errn'): + if 'errn' in args: raise Error, aetools.decodeerror(args) p = [] - if args.has_key('----'): + if '----' in args: p = args['----'] for proc in p: if hasattr(proc, 'seld'): @@ -193,9 +193,9 @@ aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('prcs'), form="indx", seld=aetypes.Unknown('abso', "all "), fr=None) args['----'] = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('fcrt'), fr=aeobj_0) _reply, args, attrs = finder.send('core', 'getd', args, attrs) - if args.has_key('errn'): + if 'errn' in args: raise Error, aetools.decodeerror(_arg) - if args.has_key('----'): + if '----' in args: p = args['----'] creators = p[:] ## concatenate in one dict @@ -248,9 +248,9 @@ aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type(property), fr=aeobj_00) args['----'] = aeobj_01 _reply, args, attrs = finder.send("core", "getd", args, attrs) - if args.has_key('errn'): + if 'errn' in args: raise Error, aetools.decodeerror(args) - if args.has_key('----'): + if '----' in args: return args['----'] @@ -269,7 +269,7 @@ aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'), form="alis", seld=object_alias, fr=None) args['----'] = aeobj_0 _reply, args, attrs = finder.send(_code, _subcode, args, attrs) - if args.has_key('errn'): + if 'errn' in args: raise Error, aetools.decodeerror(args) def closewindow(object): @@ -284,7 +284,7 @@ aeobj_0 = aetypes.ObjectSpecifier(want=aetypes.Type('cfol'), form="alis", seld=object_alias, fr=None) args['----'] = aeobj_0 _reply, args, attrs = finder.send(_code, _subcode, args, attrs) - if args.has_key('errn'): + if 'errn' in args: raise Error, aetools.decodeerror(args) def location(object, pos=None): @@ -306,7 +306,7 @@ args['----'] = aeobj_01 args["data"] = [x, y] _reply, args, attrs = finder.send("core", "setd", args, attrs) - if args.has_key('errn'): + if 'errn' in args: raise Error, aetools.decodeerror(args) return (x,y) @@ -319,9 +319,9 @@ aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('posn'), fr=aeobj_00) args['----'] = aeobj_01 _reply, args, attrs = finder.send("core", "getd", args, attrs) - if args.has_key('errn'): + if 'errn' in args: raise Error, aetools.decodeerror(args) - if args.has_key('----'): + if '----' in args: pos = args['----'] return pos.h, pos.v @@ -344,9 +344,9 @@ aeobj_01 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('labi'), fr=aeobj_00) args['----'] = aeobj_01 _reply, args, attrs = finder.send("core", "getd", args, attrs) - if args.has_key('errn'): + if 'errn' in args: raise Error, aetools.decodeerror(args) - if args.has_key('----'): + if '----' in args: return args['----'] def _setlabel(object_alias, index): @@ -363,7 +363,7 @@ args['----'] = aeobj_1 args["data"] = index _reply, args, attrs = finder.send(_code, _subcode, args, attrs) - if args.has_key('errn'): + if 'errn' in args: raise Error, aetools.decodeerror(args) return index @@ -403,9 +403,9 @@ args['----'] = aeobj_2 args['data'] = aeobj_3 _reply, args, attrs = finder.send(_code, _subcode, args, attrs) - if args.has_key('errn'): + if 'errn' in args: raise Error, aetools.decodeerror(args) - if args.has_key('----'): + if '----' in args: return args['----'] def _getwindowview(folder_alias): @@ -420,10 +420,10 @@ aeobj_02 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('pvew'), fr=aeobj_01) args['----'] = aeobj_02 _reply, args, attrs = finder.send("core", "getd", args, attrs) - if args.has_key('errn'): + if 'errn' in args: raise Error, aetools.decodeerror(args) views = {'iimg':0, 'pnam':1, 'lgbu':2} - if args.has_key('----'): + if '----' in args: return views[args['----'].enum] def windowsize(folder, size=None): @@ -455,7 +455,7 @@ args['----'] = aeobj_2 args["data"] = aevar00 _reply, args, attrs = finder.send(_code, _subcode, args, attrs) - if args.has_key('errn'): + if 'errn' in args: raise Error, aetools.decodeerror(args) return (w, h) @@ -472,9 +472,9 @@ form="prop", seld=aetypes.Type('posn'), fr=aeobj_1) args['----'] = aeobj_2 _reply, args, attrs = finder.send('core', 'getd', args, attrs) - if args.has_key('errn'): + if 'errn' in args: raise Error, aetools.decodeerror(args) - if args.has_key('----'): + if '----' in args: return args['----'] def windowposition(folder, pos=None): @@ -503,9 +503,9 @@ args['----'] = aeobj_2 args["data"] = [x, y] _reply, args, attrs = finder.send('core', 'setd', args, attrs) - if args.has_key('errn'): + if 'errn' in args: raise Error, aetools.decodeerror(args) - if args.has_key('----'): + if '----' in args: return args['----'] def _getwindowposition(folder_alias): @@ -521,9 +521,9 @@ form="prop", seld=aetypes.Type('ptsz'), fr=aeobj_1) args['----'] = aeobj_2 _reply, args, attrs = finder.send('core', 'getd', args, attrs) - if args.has_key('errn'): + if 'errn' in args: raise Error, aetools.decodeerror(args) - if args.has_key('----'): + if '----' in args: return args['----'] def icon(object, icondata=None): @@ -548,9 +548,9 @@ form="prop", seld=aetypes.Type('iimg'), fr=aeobj_00) args['----'] = aeobj_01 _reply, args, attrs = finder.send("core", "getd", args, attrs) - if args.has_key('errn'): + if 'errn' in args: raise Error, aetools.decodeerror(args) - if args.has_key('----'): + if '----' in args: return args['----'] def _seticon(object_alias, icondata): @@ -565,9 +565,9 @@ args['----'] = aeobj_01 args["data"] = icondata _reply, args, attrs = finder.send("core", "setd", args, attrs) - if args.has_key('errn'): + if 'errn' in args: raise Error, aetools.decodeerror(args) - if args.has_key('----'): + if '----' in args: return args['----'].data @@ -590,9 +590,9 @@ args["SRVR"] = server args['----'] = volume _reply, args, attrs = finder.send("aevt", "mvol", args, attrs) - if args.has_key('errn'): + if 'errn' in args: raise Error, aetools.decodeerror(args) - if args.has_key('----'): + if '----' in args: return args['----'] def unmountvolume(volume): @@ -606,9 +606,9 @@ attrs = {} args['----'] = aetypes.ObjectSpecifier(want=aetypes.Type('cdis'), form="name", seld=object, fr=None) _reply, args, attrs = talker.send("fndr", "ptwy", args, attrs) - if args.has_key('errn'): + if 'errn' in args: raise Error, aetools.decodeerror(args) - if args.has_key('----'): + if '----' in args: return args['----'] @@ -627,9 +627,9 @@ level = 7 args['----'] = level _reply, args, attrs = finder.send("aevt", "stvl", args, attrs) - if args.has_key('errn'): + if 'errn' in args: raise Error, aetools.decodeerror(args) - if args.has_key('----'): + if '----' in args: return args['----'] def OSversion(): @@ -640,9 +640,9 @@ aeobj_00 = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('ver2'), fr=None) args['----'] = aeobj_00 _reply, args, attrs = finder.send("core", "getd", args, attrs) - if args.has_key('errn'): + if 'errn' in args: raise Error, aetools.decodeerror(args) - if args.has_key('----'): + if '----' in args: return args['----'] def filesharing(): @@ -657,9 +657,9 @@ attrs = {} args['----'] = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('fshr'), fr=None) _reply, args, attrs = finder.send("core", "getd", args, attrs) - if args.has_key('errn'): + if 'errn' in args: raise Error, aetools.decodeerror(args) - if args.has_key('----'): + if '----' in args: if args['----'] == 0: status = -1 else: @@ -669,9 +669,9 @@ attrs = {} args['----'] = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('fsup'), fr=None) _reply, args, attrs = finder.send("core", "getd", args, attrs) - if args.has_key('errn'): + if 'errn' in args: raise Error, aetools.decodeerror(args) - if args.has_key('----'): + if '----' in args: if args['----'] == 1: status = 0 return status @@ -689,7 +689,7 @@ attrs = {} args['----'] = aetypes.ObjectSpecifier(want=aetypes.Type('prop'), form="prop", seld=aetypes.Type('trsh'), fr=None) _reply, args, attrs = finder.send("fndr", "empt", args, attrs) - if args.has_key('errn'): + if 'errn' in args: raise aetools.Error, aetools.decodeerror(args) Modified: python/branches/p3yk/Lib/plat-mac/gensuitemodule.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/gensuitemodule.py (original) +++ python/branches/p3yk/Lib/plat-mac/gensuitemodule.py Sun Aug 20 18:25:10 2006 @@ -589,7 +589,7 @@ self.modname = os.path.splitext(os.path.split(self.pathname)[1])[0] - if self.basepackage and self.basepackage._code_to_module.has_key(code): + if self.basepackage and code in self.basepackage._code_to_module: # We are an extension of a baseclass (usually an application extending # Standard_Suite or so). Import everything from our base module basemodule = self.basepackage._code_to_module[code] @@ -656,12 +656,12 @@ fp.write('import aetools\n') fp.write('import MacOS\n\n') fp.write("_code = %r\n\n"% (code,)) - if self.basepackage and self.basepackage._code_to_module.has_key(code): + if self.basepackage and code in self.basepackage._code_to_module: # We are an extension of a baseclass (usually an application extending # Standard_Suite or so). Import everything from our base module fp.write('from %s import *\n'%self.basepackage._code_to_fullname[code][0]) basemodule = self.basepackage._code_to_module[code] - elif self.basepackage and self.basepackage._code_to_module.has_key(code.lower()): + elif self.basepackage and code.lower() in self.basepackage._code_to_module: # This is needed by CodeWarrior and some others. fp.write('from %s import *\n'%self.basepackage._code_to_fullname[code.lower()][0]) basemodule = self.basepackage._code_to_module[code.lower()] @@ -798,7 +798,7 @@ # # Decode result # - fp.write(" if _arguments.has_key('----'):\n") + fp.write(" if '----' in _arguments:\n") if is_enum(returns): fp.write(" # XXXX Should do enum remapping here...\n") fp.write(" return _arguments['----']\n") @@ -842,17 +842,17 @@ def addnamecode(self, type, name, code): self.name2code[type][name] = code - if not self.code2name[type].has_key(code): + if code not in self.code2name[type]: self.code2name[type][code] = name def hasname(self, name): for dict in self.name2code.values(): - if dict.has_key(name): + if name in dict: return True return False def hascode(self, type, code): - return self.code2name[type].has_key(code) + return code in self.code2name[type] def findcodename(self, type, code): if not self.hascode(type, code): Modified: python/branches/p3yk/Lib/plat-mac/ic.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/ic.py (original) +++ python/branches/p3yk/Lib/plat-mac/ic.py Sun Aug 20 18:25:10 2006 @@ -138,7 +138,7 @@ key2 = key[:string.index(key, '\245')+1] else: key2 = key - if _decoder_table.has_key(key2): + if key2 in _decoder_table: decoder = _decoder_table[key2][0] else: decoder = _decode_default @@ -151,7 +151,7 @@ key2 = key[:string.index(key, '\245')+1] else: key2 = key - if _decoder_table.has_key(key2): + if key2 in _decoder_table: coder = _decoder_table[key2][1] else: coder = _code_default @@ -176,9 +176,6 @@ self.ic.ICEnd() return rv - def has_key(self, key): - return self.__contains__(key) - def __contains__(self, key): try: dummy = self.ic.ICFindPrefHandle(key, self.h) Modified: python/branches/p3yk/Lib/plat-mac/macresource.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/macresource.py (original) +++ python/branches/p3yk/Lib/plat-mac/macresource.py Sun Aug 20 18:25:10 2006 @@ -48,7 +48,7 @@ if modname == '__main__': # If we're main we look in the current directory searchdirs = [os.curdir] - if sys.modules.has_key(modname): + if modname in sys.modules: mod = sys.modules[modname] if hasattr(mod, '__file__'): searchdirs = [os.path.dirname(mod.__file__)] Modified: python/branches/p3yk/Lib/plat-mac/pimp.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/pimp.py (original) +++ python/branches/p3yk/Lib/plat-mac/pimp.py Sun Aug 20 18:25:10 2006 @@ -147,7 +147,7 @@ self.update("Downloading %s: opening connection" % url) keepgoing = True download = urllib2.urlopen(url) - if download.headers.has_key("content-length"): + if "content-length" in download.headers: length = long(download.headers['content-length']) else: length = -1 @@ -415,7 +415,7 @@ for p in packages: p = dict(p) - if p.has_key('Download-URL'): + if 'Download-URL' in p: p['Download-URL'] = urllib.basejoin(url, p['Download-URL']) flavor = p.get('Flavor') if flavor == 'source': @@ -547,9 +547,9 @@ installed through pimp, return the name in (parentheses).""" rv = self._dict['Name'] - if self._dict.has_key('Version'): + if 'Version' in self._dict: rv = rv + '-%s' % self._dict['Version'] - if self._dict.has_key('Flavor'): + if 'Flavor' in self._dict: rv = rv + '-%s' % self._dict['Flavor'] if self._dict.get('Flavor') == 'hidden': # Pseudo-package, show in parentheses @@ -642,9 +642,9 @@ descr = str(item) else: name = item['Name'] - if item.has_key('Version'): + if 'Version' in item: name = name + '-' + item['Version'] - if item.has_key('Flavor'): + if 'Flavor' in item: name = name + '-' + item['Flavor'] pkg = self._db.find(name) if not pkg: @@ -795,10 +795,10 @@ If output is given it should be a file-like object and it will receive a log of what happened.""" - if self._dict.has_key('Install-command'): + if 'Install-command' in self._dict: return "%s: Binary package cannot have Install-command" % self.fullname() - if self._dict.has_key('Pre-install-command'): + if 'Pre-install-command' in self._dict: if _cmd(output, '/tmp', self._dict['Pre-install-command']): return "pre-install %s: running \"%s\" failed" % \ (self.fullname(), self._dict['Pre-install-command']) @@ -831,7 +831,7 @@ self.afterInstall() - if self._dict.has_key('Post-install-command'): + if 'Post-install-command' in self._dict: if _cmd(output, '/tmp', self._dict['Post-install-command']): return "%s: post-install: running \"%s\" failed" % \ (self.fullname(), self._dict['Post-install-command']) @@ -856,7 +856,7 @@ If output is given it should be a file-like object and it will receive a log of what happened.""" - if self._dict.has_key('Pre-install-command'): + if 'Pre-install-command' in self._dict: if _cmd(output, self._buildDirname, self._dict['Pre-install-command']): return "pre-install %s: running \"%s\" failed" % \ (self.fullname(), self._dict['Pre-install-command']) @@ -893,7 +893,7 @@ self.afterInstall() - if self._dict.has_key('Post-install-command'): + if 'Post-install-command' in self._dict: if _cmd(output, self._buildDirname, self._dict['Post-install-command']): return "post-install %s: running \"%s\" failed" % \ (self.fullname(), self._dict['Post-install-command']) @@ -911,10 +911,10 @@ If output is given it should be a file-like object and it will receive a log of what happened.""" - if self._dict.has_key('Post-install-command'): + if 'Post-install-command' in self._dict: return "%s: Installer package cannot have Post-install-command" % self.fullname() - if self._dict.has_key('Pre-install-command'): + if 'Pre-install-command' in self._dict: if _cmd(output, '/tmp', self._dict['Pre-install-command']): return "pre-install %s: running \"%s\" failed" % \ (self.fullname(), self._dict['Pre-install-command']) From python-3000-checkins at python.org Mon Aug 21 02:21:48 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Mon, 21 Aug 2006 02:21:48 +0200 (CEST) Subject: [Python-3000-checkins] r51419 - in python/branches/p3yk/Lib/bsddb: dbshelve.py dbtables.py dbutils.py test/test_basics.py test/test_dbshelve.py Message-ID: <20060821002148.A1BB91E4002@bag.python.org> Author: guido.van.rossum Date: Mon Aug 21 02:21:47 2006 New Revision: 51419 Modified: python/branches/p3yk/Lib/bsddb/dbshelve.py python/branches/p3yk/Lib/bsddb/dbtables.py python/branches/p3yk/Lib/bsddb/dbutils.py python/branches/p3yk/Lib/bsddb/test/test_basics.py python/branches/p3yk/Lib/bsddb/test/test_dbshelve.py Log: Fixed to the point that all unit tests pass again. (However, I get 4 "exception in thread" messages, one about a killed locker, and three assertions.) Details: test/test_dbshelve.py: - kill reference to InstanceType test/test_basics.py: - use // for int division - use 'in' instead of has_key dbshelve.py: - fix bug in previous has_key fix, use self.db.has_key instead of self.has_key dbtables.py: - use 'in' instead of has_key dbutils.py: - fix bug in previous has_key fix, test for 'max_retries', not 'max_tries' Modified: python/branches/p3yk/Lib/bsddb/dbshelve.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/dbshelve.py (original) +++ python/branches/p3yk/Lib/bsddb/dbshelve.py Mon Aug 21 02:21:47 2006 @@ -198,7 +198,7 @@ def __contains__(self, key): - return self.has_key(key) + return self.db.has_key(key) #---------------------------------------------- Modified: python/branches/p3yk/Lib/bsddb/dbtables.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/dbtables.py (original) +++ python/branches/p3yk/Lib/bsddb/dbtables.py Mon Aug 21 02:21:47 2006 @@ -323,7 +323,7 @@ # column names newcolumnlist = copy.copy(oldcolumnlist) for c in columns: - if not oldcolumnhash.has_key(c): + if c not in oldcolumnhash: newcolumnlist.append(c) # store the table's new extended column list @@ -389,7 +389,7 @@ raise TableDBError, "unknown table" # check the validity of each column name - if not self.__tablecolumns.has_key(table): + if table not in self.__tablecolumns: self.__load_column_info(table) for column in rowdict.keys() : if not self.__tablecolumns[table].count(column): @@ -521,7 +521,7 @@ argument and returning a boolean. """ try: - if not self.__tablecolumns.has_key(table): + if table not in self.__tablecolumns: self.__load_column_info(table) if columns is None: columns = self.__tablecolumns[table] @@ -542,7 +542,7 @@ argument and returning a boolean. """ # check the validity of each column name - if not self.__tablecolumns.has_key(table): + if table not in self.__tablecolumns: self.__load_column_info(table) if columns is None: columns = self.tablecolumns[table] @@ -601,16 +601,16 @@ # extract the rowid from the key rowid = key[-_rowid_str_len:] - if not rejected_rowids.has_key(rowid): + if rowid not in rejected_rowids: # if no condition was specified or the condition # succeeds, add row to our match list. if not condition or condition(data): - if not matching_rowids.has_key(rowid): + if rowid not in matching_rowids: matching_rowids[rowid] = {} if savethiscolumndata: matching_rowids[rowid][column] = data else: - if matching_rowids.has_key(rowid): + if rowid in matching_rowids: del matching_rowids[rowid] rejected_rowids[rowid] = rowid @@ -631,7 +631,7 @@ if len(columns) > 0: for rowid, rowdata in matching_rowids.items(): for column in columns: - if rowdata.has_key(column): + if column in rowdata: continue try: rowdata[column] = self.db.get( @@ -697,7 +697,7 @@ txn.commit() txn = None - if self.__tablecolumns.has_key(table): + if table in self.__tablecolumns: del self.__tablecolumns[table] except DBError, dberror: Modified: python/branches/p3yk/Lib/bsddb/dbutils.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/dbutils.py (original) +++ python/branches/p3yk/Lib/bsddb/dbutils.py Mon Aug 21 02:21:47 2006 @@ -55,7 +55,7 @@ """ sleeptime = _deadlock_MinSleepTime max_retries = _kwargs.get('max_retries', -1) - if 'max_tries' in _kwargs: + if 'max_retries' in _kwargs: del _kwargs['max_retries'] while True: try: Modified: python/branches/p3yk/Lib/bsddb/test/test_basics.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_basics.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_basics.py Mon Aug 21 02:21:47 2006 @@ -114,14 +114,14 @@ def populateDB(self, _txn=None): d = self.d - for x in range(self._numKeys/2): + for x in range(self._numKeys//2): key = '%04d' % (self._numKeys - x) # insert keys in reverse order data = self.makeData(key) d.put(key, data, _txn) d.put('empty value', '', _txn) - for x in range(self._numKeys/2-1): + for x in range(self._numKeys//2-1): key = '%04d' % x # and now some in forward order data = self.makeData(key) d.put(key, data, _txn) @@ -686,10 +686,10 @@ if db.version() >= (4,0): statDict = self.env.log_stat(0); - assert statDict.has_key('magic') - assert statDict.has_key('version') - assert statDict.has_key('cur_file') - assert statDict.has_key('region_nowait') + assert 'magic' in statDict + assert 'version' in statDict + assert 'cur_file' in statDict + assert 'region_nowait' in statDict # must have at least one log file present: logs = self.env.log_archive(db.DB_ARCH_ABS | db.DB_ARCH_LOG) Modified: python/branches/p3yk/Lib/bsddb/test/test_dbshelve.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_dbshelve.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_dbshelve.py Mon Aug 21 02:21:47 2006 @@ -187,7 +187,6 @@ assert value == [x] * 10 elif key[0] == 'O': - assert type(value) == InstanceType assert value.S == 10 * x assert value.I == ord(x) assert value.L == [x] * 10 From python-3000-checkins at python.org Mon Aug 21 02:26:58 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Mon, 21 Aug 2006 02:26:58 +0200 (CEST) Subject: [Python-3000-checkins] r51420 - python/branches/p3yk/Lib/lib-tk/Canvas.py Message-ID: <20060821002658.A96E51E4002@bag.python.org> Author: guido.van.rossum Date: Mon Aug 21 02:26:58 2006 New Revision: 51420 Modified: python/branches/p3yk/Lib/lib-tk/Canvas.py Log: Don't define has_key(). Modified: python/branches/p3yk/Lib/lib-tk/Canvas.py ============================================================================== --- python/branches/p3yk/Lib/lib-tk/Canvas.py (original) +++ python/branches/p3yk/Lib/lib-tk/Canvas.py Mon Aug 21 02:26:58 2006 @@ -37,8 +37,6 @@ 'itemconfigure', (self.id,)))) return self._keys - def has_key(self, key): - return key in self.keys() def __contains__(self, key): return key in self.keys() def addtag(self, tag, option='withtag'): From python-3000-checkins at python.org Mon Aug 21 18:27:32 2006 From: python-3000-checkins at python.org (neal.norwitz) Date: Mon, 21 Aug 2006 18:27:32 +0200 (CEST) Subject: [Python-3000-checkins] r51430 - python/branches/p3yk/Lib/test/test_support.py Message-ID: <20060821162732.97B471E400A@bag.python.org> Author: neal.norwitz Date: Mon Aug 21 18:27:31 2006 New Revision: 51430 Modified: python/branches/p3yk/Lib/test/test_support.py Log: use isinstance instead of type. Use bool instead of int for flag. Modified: python/branches/p3yk/Lib/test/test_support.py ============================================================================== --- python/branches/p3yk/Lib/test/test_support.py (original) +++ python/branches/p3yk/Lib/test/test_support.py Mon Aug 21 18:27:31 2006 @@ -110,15 +110,14 @@ FUZZ = 1e-6 def fcmp(x, y): # fuzzy comparison function - if type(x) == type(0.0) or type(y) == type(0.0): + if isinstance(x, float) or isinstance(y, float): try: - x, y = coerce(x, y) fuzz = (abs(x) + abs(y)) * FUZZ if abs(x-y) <= fuzz: return 0 except: pass - elif type(x) == type(y) and type(x) in (type(()), type([])): + elif type(x) == type(y) and isinstance(x, (tuple, list)): for i in range(min(len(x), len(y))): outcome = fcmp(x[i], y[i]) if outcome != 0: @@ -128,9 +127,9 @@ try: unicode - have_unicode = 1 + have_unicode = True except NameError: - have_unicode = 0 + have_unicode = False is_jython = sys.platform.startswith('java') From python-3000-checkins at python.org Mon Aug 21 19:06:11 2006 From: python-3000-checkins at python.org (neal.norwitz) Date: Mon, 21 Aug 2006 19:06:11 +0200 (CEST) Subject: [Python-3000-checkins] r51431 - in python/branches/p3yk: BROKEN Doc/api/abstract.tex Doc/ref/ref3.tex Doc/tut/glossary.tex Include/abstract.h Include/object.h Lib/test/test_builtin.py Lib/test/test_complex.py Lib/test/test_descr.py Misc/NEWS Misc/cheatsheet Objects/abstract.c Objects/complexobject.c Objects/floatobject.c Objects/intobject.c Objects/object.c Objects/typeobject.c PC/_winreg.c Python/bltinmodule.c Message-ID: <20060821170611.E4C8B1E4009@bag.python.org> Author: neal.norwitz Date: Mon Aug 21 19:06:07 2006 New Revision: 51431 Modified: python/branches/p3yk/BROKEN python/branches/p3yk/Doc/api/abstract.tex python/branches/p3yk/Doc/ref/ref3.tex python/branches/p3yk/Doc/tut/glossary.tex python/branches/p3yk/Include/abstract.h python/branches/p3yk/Include/object.h python/branches/p3yk/Lib/test/test_builtin.py python/branches/p3yk/Lib/test/test_complex.py python/branches/p3yk/Lib/test/test_descr.py python/branches/p3yk/Misc/NEWS python/branches/p3yk/Misc/cheatsheet python/branches/p3yk/Objects/abstract.c python/branches/p3yk/Objects/complexobject.c python/branches/p3yk/Objects/floatobject.c python/branches/p3yk/Objects/intobject.c python/branches/p3yk/Objects/object.c python/branches/p3yk/Objects/typeobject.c python/branches/p3yk/PC/_winreg.c python/branches/p3yk/Python/bltinmodule.c Log: Get rid of most of the rest of coerce (slot is still there for now). Modified: python/branches/p3yk/BROKEN ============================================================================== --- python/branches/p3yk/BROKEN (original) +++ python/branches/p3yk/BROKEN Mon Aug 21 19:06:07 2006 @@ -110,3 +110,31 @@ File "../Lib/test/test_set.py", line 291, in test_remove self.assert_(self.thetype(self.word) in s) AssertionError + +//////////////////////////////////////////////////////////////////////// +test_compare +//////////////////////////////////////////////////////////////////////// +test test_compare failed -- Traceback (most recent call last): + File "/Users/nnorwitz/build/python/py3k.2/Lib/test/test_compare.py", line 28, in test_comparisons + self.assertEqual(a, b) +AssertionError: 2 != (2+0j) + +//////////////////////////////////////////////////////////////////////// +test_complex +//////////////////////////////////////////////////////////////////////// +====================================================================== +FAIL: test_pow (test.test_complex.ComplexTest) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/Users/nnorwitz/build/python/py3k.2/Lib/test/test_complex.py", line 130, in test_pow + self.assertEqual(a ** 0j, 1) +AssertionError: (1+0j) != 1 + +====================================================================== +FAIL: test_richcompare (test.test_complex.ComplexTest) +---------------------------------------------------------------------- +Traceback (most recent call last): + File "/Users/nnorwitz/build/python/py3k.2/Lib/test/test_complex.py", line 96, in test_richcompare + self.assertRaises(OverflowError, complex.__eq__, 1+1j, 1L<<10000) +AssertionError: OverflowError not raised + Modified: python/branches/p3yk/Doc/api/abstract.tex ============================================================================== --- python/branches/p3yk/Doc/api/abstract.tex (original) +++ python/branches/p3yk/Doc/api/abstract.tex Mon Aug 21 19:06:07 2006 @@ -654,20 +654,6 @@ statement \samp{\var{o1} |= \var{o2}}. \end{cfuncdesc} -\begin{cfuncdesc}{int}{PyNumber_Coerce}{PyObject **p1, PyObject **p2} - This function takes the addresses of two variables of type - \ctype{PyObject*}. If the objects pointed to by \code{*\var{p1}} - and \code{*\var{p2}} have the same type, increment their reference - count and return \code{0} (success). If the objects can be converted - to a common numeric type, replace \code{*p1} and \code{*p2} by their - converted value (with 'new' reference counts), and return \code{0}. - If no conversion is possible, or if some other error occurs, return - \code{-1} (failure) and don't increment the reference counts. The - call \code{PyNumber_Coerce(\&o1, \&o2)} is equivalent to the Python - statement \samp{\var{o1}, \var{o2} = coerce(\var{o1}, \var{o2})}. - \bifuncindex{coerce} -\end{cfuncdesc} - \begin{cfuncdesc}{PyObject*}{PyNumber_Int}{PyObject *o} Returns the \var{o} converted to an integer object on success, or \NULL{} on failure. If the argument is outside the integer range Modified: python/branches/p3yk/Doc/ref/ref3.tex ============================================================================== --- python/branches/p3yk/Doc/ref/ref3.tex (original) +++ python/branches/p3yk/Doc/ref/ref3.tex Mon Aug 21 19:06:07 2006 @@ -1645,7 +1645,7 @@ multiplication (meaning repetition) by defining the methods \method{__add__()}, \method{__radd__()}, \method{__iadd__()}, \method{__mul__()}, \method{__rmul__()} and \method{__imul__()} described -below; they should not define \method{__coerce__()} or other numerical +below; they should not define other numerical operators. It is recommended that both mappings and sequences implement the \method{__contains__()} method to allow efficient use of the \code{in} operator; for mappings, \code{in} should be equivalent @@ -1689,7 +1689,7 @@ \ttindex{__imul__()} \ttindex{__contains__()} \ttindex{__iter__()}} -\withsubitem{(numeric object method)}{\ttindex{__coerce__()}} +\withsubitem{(numeric object method)} \begin{methoddesc}[container object]{__len__}{self} Called to implement the built-in function @@ -2012,129 +2012,6 @@ \versionadded{2.5} \end{methoddesc} -\begin{methoddesc}[numeric object]{__coerce__}{self, other} -Called to implement ``mixed-mode'' numeric arithmetic. Should either -return a 2-tuple containing \var{self} and \var{other} converted to -a common numeric type, or \code{None} if conversion is impossible. When -the common type would be the type of \code{other}, it is sufficient to -return \code{None}, since the interpreter will also ask the other -object to attempt a coercion (but sometimes, if the implementation of -the other type cannot be changed, it is useful to do the conversion to -the other type here). A return value of \code{NotImplemented} is -equivalent to returning \code{None}. -\end{methoddesc} - -\subsection{Coercion rules\label{coercion-rules}} - -This section used to document the rules for coercion. As the language -has evolved, the coercion rules have become hard to document -precisely; documenting what one version of one particular -implementation does is undesirable. Instead, here are some informal -guidelines regarding coercion. In Python 3.0, coercion will not be -supported. - -\begin{itemize} - -\item - -If the left operand of a \% operator is a string or Unicode object, no -coercion takes place and the string formatting operation is invoked -instead. - -\item - -It is no longer recommended to define a coercion operation. -Mixed-mode operations on types that don't define coercion pass the -original arguments to the operation. - -\item - -New-style classes (those derived from \class{object}) never invoke the -\method{__coerce__()} method in response to a binary operator; the only -time \method{__coerce__()} is invoked is when the built-in function -\function{coerce()} is called. - -\item - -For most intents and purposes, an operator that returns -\code{NotImplemented} is treated the same as one that is not -implemented at all. - -\item - -Below, \method{__op__()} and \method{__rop__()} are used to signify -the generic method names corresponding to an operator; -\method{__iop__()} is used for the corresponding in-place operator. For -example, for the operator `\code{+}', \method{__add__()} and -\method{__radd__()} are used for the left and right variant of the -binary operator, and \method{__iadd__()} for the in-place variant. - -\item - -For objects \var{x} and \var{y}, first \code{\var{x}.__op__(\var{y})} -is tried. If this is not implemented or returns \code{NotImplemented}, -\code{\var{y}.__rop__(\var{x})} is tried. If this is also not -implemented or returns \code{NotImplemented}, a \exception{TypeError} -exception is raised. But see the following exception: - -\item - -Exception to the previous item: if the left operand is an instance of -a built-in type or a new-style class, and the right operand is an instance -of a proper subclass of that type or class and overrides the base's -\method{__rop__()} method, the right operand's \method{__rop__()} method -is tried \emph{before} the left operand's \method{__op__()} method. - -This is done so that a subclass can completely override binary operators. -Otherwise, the left operand's \method{__op__()} method would always -accept the right operand: when an instance of a given class is expected, -an instance of a subclass of that class is always acceptable. - -\item - -When either operand type defines a coercion, this coercion is called -before that type's \method{__op__()} or \method{__rop__()} method is -called, but no sooner. If the coercion returns an object of a -different type for the operand whose coercion is invoked, part of the -process is redone using the new object. - -\item - -When an in-place operator (like `\code{+=}') is used, if the left -operand implements \method{__iop__()}, it is invoked without any -coercion. When the operation falls back to \method{__op__()} and/or -\method{__rop__()}, the normal coercion rules apply. - -\item - -In \var{x}\code{+}\var{y}, if \var{x} is a sequence that implements -sequence concatenation, sequence concatenation is invoked. - -\item - -In \var{x}\code{*}\var{y}, if one operator is a sequence that -implements sequence repetition, and the other is an integer -(\class{int} or \class{long}), sequence repetition is invoked. - -\item - -Rich comparisons (implemented by methods \method{__eq__()} and so on) -never use coercion. Three-way comparison (implemented by -\method{__cmp__()}) does use coercion under the same conditions as -other binary operations use it. - -\item - -In the current implementation, the built-in numeric types \class{int}, -\class{long} and \class{float} do not use coercion; the type -\class{complex} however does use it. The difference can become -apparent when subclassing these types. Over time, the type -\class{complex} may be fixed to avoid coercion. All these types -implement a \method{__coerce__()} method, for use by the built-in -\function{coerce()} function. - -\end{itemize} - \subsection{With Statement Context Managers\label{context-managers}} \versionadded{2.5} Modified: python/branches/p3yk/Doc/tut/glossary.tex ============================================================================== --- python/branches/p3yk/Doc/tut/glossary.tex (original) +++ python/branches/p3yk/Doc/tut/glossary.tex Mon Aug 21 19:06:07 2006 @@ -35,21 +35,6 @@ Any class which does not inherit from \class{object}. See \emph{new-style class}. -\index{coercion} -\item[coercion] -The implicit conversion of an instance of one type to another during an -operation which involves two arguments of the same type. For example, -{}\code{int(3.15)} converts the floating point number to the integer -{}\code{3}, but in {}\code{3+4.5}, each argument is of a different type (one -int, one float), and both must be converted to the same type before they can -be added or it will raise a {}\code{TypeError}. Coercion between two -operands can be performed with the {}\code{coerce} builtin function; thus, -{}\code{3+4.5} is equivalent to calling {}\code{operator.add(*coerce(3, -4.5))} and results in {}\code{operator.add(3.0, 4.5)}. Without coercion, -all arguments of even compatible types would have to be normalized to the -same value by the programmer, e.g., {}\code{float(3)+4.5} rather than just -{}\code{3+4.5}. - \index{complex number} \item[complex number] An extension of the familiar real number system in which all numbers are @@ -106,17 +91,14 @@ \index{__future__} \item[__future__] A pseudo module which programmers can use to enable new language -features which are not compatible with the current interpreter. For -example, the expression \code{11/4} currently evaluates to \code{2}. -If the module in which it is executed had enabled \emph{true division} -by executing: +features which are not compatible with the current interpreter. +To enable \code{new_feature} \begin{verbatim} -from __future__ import division +from __future__ import new_feature \end{verbatim} -the expression \code{11/4} would evaluate to \code{2.75}. By -importing the \ulink{\module{__future__}}{../lib/module-future.html} +By importing the \ulink{\module{__future__}}{../lib/module-future.html} module and evaluating its variables, you can see when a new feature was first added to the language and when it will become the default: @@ -183,17 +165,10 @@ \index{integer division} \item[integer division] -Mathematical division discarding any remainder. For example, the -expression \code{11/4} currently evaluates to \code{2} in contrast -to the \code{2.75} returned by float division. Also called -{}\emph{floor division}. When dividing two integers the outcome will -always be another integer (having the floor function applied to it). -However, if one of the operands is another numeric type (such as a -{}\class{float}), the result will be coerced (see \emph{coercion}) to -a common type. For example, an integer divided by a float will result -in a float value, possibly with a decimal fraction. Integer division -can be forced by using the \code{//} operator instead of the \code{/} -operator. See also \emph{__future__}. +Mathematical division including any remainder. The result will always +be a float. For example, the expression \code{11/4} evaluates to \code{2.75}. +Integer division can be forced by using the \code{//} operator instead +of the \code{/} operator. \index{interactive} \item[interactive] Modified: python/branches/p3yk/Include/abstract.h ============================================================================== --- python/branches/p3yk/Include/abstract.h (original) +++ python/branches/p3yk/Include/abstract.h Mon Aug 21 19:06:07 2006 @@ -694,24 +694,6 @@ expression: o1|o2. */ - /* Implemented elsewhere: - - int PyNumber_Coerce(PyObject **p1, PyObject **p2); - - This function takes the addresses of two variables of type - PyObject*. - - If the objects pointed to by *p1 and *p2 have the same type, - increment their reference count and return 0 (success). - If the objects can be converted to a common numeric type, - replace *p1 and *p2 by their converted value (with 'new' - reference counts), and return 0. - If no conversion is possible, or if some other error occurs, - return -1 (failure) and don't increment the reference counts. - The call PyNumber_Coerce(&o1, &o2) is equivalent to the Python - statement o1, o2 = coerce(o1, o2). - */ - PyAPI_FUNC(Py_ssize_t) PyNumber_Index(PyObject *); /* Modified: python/branches/p3yk/Include/object.h ============================================================================== --- python/branches/p3yk/Include/object.h (original) +++ python/branches/p3yk/Include/object.h Mon Aug 21 19:06:07 2006 @@ -393,7 +393,6 @@ PyAPI_FUNC(int) PyObject_IsTrue(PyObject *); PyAPI_FUNC(int) PyObject_Not(PyObject *); PyAPI_FUNC(int) PyCallable_Check(PyObject *); -PyAPI_FUNC(int) PyNumber_Coerce(PyObject **, PyObject **); PyAPI_FUNC(int) PyNumber_CoerceEx(PyObject **, PyObject **); PyAPI_FUNC(void) PyObject_ClearWeakRefs(PyObject *); Modified: python/branches/p3yk/Lib/test/test_builtin.py ============================================================================== --- python/branches/p3yk/Lib/test/test_builtin.py (original) +++ python/branches/p3yk/Lib/test/test_builtin.py Mon Aug 21 19:06:07 2006 @@ -196,17 +196,6 @@ a.pop(); b.pop(); c.pop() self.assertRaises(TypeError, cmp) - def test_coerce(self): - self.assert_(not fcmp(coerce(1, 1.1), (1.0, 1.1))) - self.assertEqual(coerce(1, 1L), (1L, 1L)) - self.assert_(not fcmp(coerce(1L, 1.1), (1.0, 1.1))) - self.assertRaises(TypeError, coerce) - class BadNumber: - def __coerce__(self, other): - raise ValueError - self.assertRaises(ValueError, coerce, 42, BadNumber()) - self.assertRaises(OverflowError, coerce, 0.5, int("12345" * 1000)) - def test_compile(self): compile('print 1\n', '', 'exec') bom = '\xef\xbb\xbf' Modified: python/branches/p3yk/Lib/test/test_complex.py ============================================================================== --- python/branches/p3yk/Lib/test/test_complex.py (original) +++ python/branches/p3yk/Lib/test/test_complex.py Mon Aug 21 19:06:07 2006 @@ -92,9 +92,6 @@ self.assertAlmostEqual(complex.__floordiv__(3+0j, 1.5+0j), 2) self.assertRaises(ZeroDivisionError, complex.__floordiv__, 3+0j, 0+0j) - def test_coerce(self): - self.assertRaises(OverflowError, complex.__coerce__, 1+1j, 1L<<10000) - def test_richcompare(self): self.assertRaises(OverflowError, complex.__eq__, 1+1j, 1L<<10000) self.assertEqual(complex.__lt__(1+1j, None), NotImplemented) Modified: python/branches/p3yk/Lib/test/test_descr.py ============================================================================== --- python/branches/p3yk/Lib/test/test_descr.py (original) +++ python/branches/p3yk/Lib/test/test_descr.py Mon Aug 21 19:06:07 2006 @@ -2567,33 +2567,6 @@ verify(eval("x %s c[y]" % op) == eval("x %s y" % op), "x=%d, y=%d" % (x, y)) -def coercions(): - if verbose: print "Testing coercions..." - class I(int): pass - coerce(I(0), 0) - coerce(0, I(0)) - class L(long): pass - coerce(L(0), 0) - coerce(L(0), 0L) - coerce(0, L(0)) - coerce(0L, L(0)) - class F(float): pass - coerce(F(0), 0) - coerce(F(0), 0L) - coerce(F(0), 0.) - coerce(0, F(0)) - coerce(0L, F(0)) - coerce(0., F(0)) - class C(complex): pass - coerce(C(0), 0) - coerce(C(0), 0L) - coerce(C(0), 0.) - coerce(C(0), 0j) - coerce(0, C(0)) - coerce(0L, C(0)) - coerce(0., C(0)) - coerce(0j, C(0)) - def descrdoc(): if verbose: print "Testing descriptor doc strings..." def check(descr, what): @@ -3961,11 +3934,8 @@ ('__and__', 'x & y', 'x &= y'), ('__or__', 'x | y', 'x |= y'), ('__xor__', 'x ^ y', 'x ^= y'), - ('__coerce__', 'coerce(x, y)', None)]: - if name == '__coerce__': - rname = name - else: - rname = '__r' + name[2:] + ]: + rname = '__r' + name[2:] A = metaclass('A', (), {name: specialmethod}) B = metaclass('B', (), {rname: specialmethod}) a = A() @@ -4043,7 +4013,6 @@ str_subclass_as_dict_key() classic_comparisons() rich_comparisons() - coercions() descrdoc() setclass() setdict() Modified: python/branches/p3yk/Misc/NEWS ============================================================================== --- python/branches/p3yk/Misc/NEWS (original) +++ python/branches/p3yk/Misc/NEWS Mon Aug 21 19:06:07 2006 @@ -7,6 +7,87 @@ What's New in Python 3000? ========================== +*Release date: XX-XXX-200X* + +TO DO +----- + +- See PEP 3000. + +- Test merging certain changes from the 2.5 HEAD code. + +- Weed really old/weird stuff from the library. + +- Unify range() and xrange(). + +- Revamp the dict API: keys(), values(), items() return iterators, etc. + +- Add the bytes type. + +- Rework the standard I/O library to use bytes for binary files. + +- Make strings all Unicode. + +- Get rid of classic class implementation. + +- Get rid of various compatibility-related flags (e.g. division flags). + +Core and Builtins +----------------- + +- __coerce__ has been removed. + +- Classic classes are a thing of the past. All classes are new style. + +- Exceptions *must* derive from BaseException. + +- Integer division always returns a float. The -Q option is no more. + All the following are gone: + * PyNumber_Divide and PyNumber_InPlaceDivide + * __div__, __rdiv__, and __idiv__ + * nb_divide, nb_inplace_divide + * operator.div, operator.idiv, operator.__div__, operator.__idiv__ + (Only __truediv__ and __floordiv__ remain, not sure how to handle them + if we want to re-use __div__ and friends. If we do, it will make + it harder to write code for both 2.x and 3.x.) + +- 'as' and 'with' are keywords. + +- Absolute import is the default behavior for 'import foo' etc. + +- Removed these Python builtins: + apply(), coerce(), input(), raw_input() + +- Removed these Python slots: + __coerce__, __div__, __idiv__, __rdiv__ + +- Removed these attributes from Python modules: + * operator module: div, idiv, __div__, __idiv__ + +*** PyNumber_CoerceEx() and nb_coerce still need to be removed. + +- Removed these C APIs: + PyNumber_Coerce(), + +- Removed these C slots/fields: + nb_divide, nb_inplace_divide + +- Removed these macros: + staticforward, statichere, PyArg_GetInt, PyArg_NoArgs + +- Removed these typedefs: + intargfunc, intintargfunc, intobjargproc, intintobjargproc, + getreadbufferproc, getwritebufferproc, getsegcountproc, getcharbufferproc + +- Removed these opcodes: + BINARY_DIVIDE, INPLACE_DIVIDE + +Extension Modules +----------------- + +Library +------- + Build ----- Modified: python/branches/p3yk/Misc/cheatsheet ============================================================================== --- python/branches/p3yk/Misc/cheatsheet (original) +++ python/branches/p3yk/Misc/cheatsheet Mon Aug 21 19:06:07 2006 @@ -1188,7 +1188,6 @@ int(s) = __int__(s) long(s) = __long__(s) float(s) = __float__(s) complex(s) = __complex__(s) oct(s) = __oct__(s) hex(s) = __hex__(s) - coerce(s,o) = __coerce__(s,o) Right-hand-side equivalents for all binary operators exist; are called when class instance is on r-h-s of operator: a + 3 calls __add__(a, 3) Modified: python/branches/p3yk/Objects/abstract.c ============================================================================== --- python/branches/p3yk/Objects/abstract.c (original) +++ python/branches/p3yk/Objects/abstract.c Mon Aug 21 19:06:07 2006 @@ -339,8 +339,6 @@ /* Binary operators */ -/* New style number protocol support */ - #define NB_SLOT(x) offsetof(PyNumberMethods, x) #define NB_BINOP(nb_methods, slot) \ (*(binaryfunc*)(& ((char*)nb_methods)[slot])) @@ -350,23 +348,11 @@ /* Calling scheme used for binary operations: - v w Action - ------------------------------------------------------------------- - new new w.op(v,w)[*], v.op(v,w), w.op(v,w) - new old v.op(v,w), coerce(v,w), v.op(v,w) - old new w.op(v,w), coerce(v,w), v.op(v,w) - old old coerce(v,w), v.op(v,w) + Order operations are tried until either a valid result or error: + w.op(v,w)[*], v.op(v,w), w.op(v,w) [*] only when v->ob_type != w->ob_type && w->ob_type is a subclass of v->ob_type - - Legend: - ------- - * new == new style number - * old == old style number - * Action indicates the order in which operations are tried until either - a valid result is produced or an error occurs. - */ static PyObject * @@ -434,29 +420,8 @@ /* Calling scheme used for ternary operations: - *** In some cases, w.op is called before v.op; see binary_op1. *** - - v w z Action - ------------------------------------------------------------------- - new new new v.op(v,w,z), w.op(v,w,z), z.op(v,w,z) - new old new v.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z) - old new new w.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z) - old old new z.op(v,w,z), coerce(v,w,z), v.op(v,w,z) - new new old v.op(v,w,z), w.op(v,w,z), coerce(v,w,z), v.op(v,w,z) - new old old v.op(v,w,z), coerce(v,w,z), v.op(v,w,z) - old new old w.op(v,w,z), coerce(v,w,z), v.op(v,w,z) - old old old coerce(v,w,z), v.op(v,w,z) - - Legend: - ------- - * new == new style number - * old == old style number - * Action indicates the order in which operations are tried until either - a valid result is produced or an error occurs. - * coerce(v,w,z) actually does: coerce(v,w), coerce(v,z), coerce(w,z) and - only if z != Py_None; if z == Py_None, then it is treated as absent - variable and only coerce(v,w) is tried. - + Order operations are tried until either a valid result or error: + v.op(v,w,z), w.op(v,w,z), z.op(v,w,z) */ static PyObject * Modified: python/branches/p3yk/Objects/complexobject.c ============================================================================== --- python/branches/p3yk/Objects/complexobject.c (original) +++ python/branches/p3yk/Objects/complexobject.c Mon Aug 21 19:06:07 2006 @@ -573,65 +573,20 @@ return v->cval.real != 0.0 || v->cval.imag != 0.0; } -static int -complex_coerce(PyObject **pv, PyObject **pw) -{ - Py_complex cval; - cval.imag = 0.; - if (PyInt_Check(*pw)) { - cval.real = (double)PyInt_AsLong(*pw); - *pw = PyComplex_FromCComplex(cval); - Py_INCREF(*pv); - return 0; - } - else if (PyLong_Check(*pw)) { - cval.real = PyLong_AsDouble(*pw); - if (cval.real == -1.0 && PyErr_Occurred()) - return -1; - *pw = PyComplex_FromCComplex(cval); - Py_INCREF(*pv); - return 0; - } - else if (PyFloat_Check(*pw)) { - cval.real = PyFloat_AsDouble(*pw); - *pw = PyComplex_FromCComplex(cval); - Py_INCREF(*pv); - return 0; - } - else if (PyComplex_Check(*pw)) { - Py_INCREF(*pv); - Py_INCREF(*pw); - return 0; - } - return 1; /* Can't do it */ -} - static PyObject * complex_richcompare(PyObject *v, PyObject *w, int op) { - int c; Py_complex i, j; PyObject *res; - c = PyNumber_CoerceEx(&v, &w); - if (c < 0) - return NULL; - if (c > 0) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } /* Make sure both arguments are complex. */ if (!(PyComplex_Check(v) && PyComplex_Check(w))) { - Py_DECREF(v); - Py_DECREF(w); Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } i = ((PyComplexObject *)v)->cval; j = ((PyComplexObject *)w)->cval; - Py_DECREF(v); - Py_DECREF(w); if (op != Py_EQ && op != Py_NE) { PyErr_SetString(PyExc_TypeError, @@ -996,7 +951,7 @@ 0, /* nb_and */ 0, /* nb_xor */ 0, /* nb_or */ - complex_coerce, /* nb_coerce */ + (coercion)0, /* nb_coerce */ complex_int, /* nb_int */ complex_long, /* nb_long */ complex_float, /* nb_float */ Modified: python/branches/p3yk/Objects/floatobject.c ============================================================================== --- python/branches/p3yk/Objects/floatobject.c (original) +++ python/branches/p3yk/Objects/floatobject.c Mon Aug 21 19:06:07 2006 @@ -842,31 +842,6 @@ return v->ob_fval != 0.0; } -static int -float_coerce(PyObject **pv, PyObject **pw) -{ - if (PyInt_Check(*pw)) { - long x = PyInt_AsLong(*pw); - *pw = PyFloat_FromDouble((double)x); - Py_INCREF(*pv); - return 0; - } - else if (PyLong_Check(*pw)) { - double x = PyLong_AsDouble(*pw); - if (x == -1.0 && PyErr_Occurred()) - return -1; - *pw = PyFloat_FromDouble(x); - Py_INCREF(*pv); - return 0; - } - else if (PyFloat_Check(*pw)) { - Py_INCREF(*pv); - Py_INCREF(*pw); - return 0; - } - return 1; /* Can't do it */ -} - static PyObject * float_long(PyObject *v) { @@ -1119,7 +1094,7 @@ 0, /*nb_and*/ 0, /*nb_xor*/ 0, /*nb_or*/ - float_coerce, /*nb_coerce*/ + (coercion)0, /*nb_coerce*/ float_int, /*nb_int*/ float_long, /*nb_long*/ float_float, /*nb_float*/ Modified: python/branches/p3yk/Objects/intobject.c ============================================================================== --- python/branches/p3yk/Objects/intobject.c (original) +++ python/branches/p3yk/Objects/intobject.c Mon Aug 21 19:06:07 2006 @@ -580,7 +580,7 @@ } static PyObject * -int_div(PyIntObject *x, PyIntObject *y) +int_floor_div(PyIntObject *x, PyIntObject *y) { long xi, yi; long d, m; @@ -872,17 +872,6 @@ return PyInt_FromLong(a | b); } -static int -int_coerce(PyObject **pv, PyObject **pw) -{ - if (PyInt_Check(*pw)) { - Py_INCREF(*pv); - Py_INCREF(*pw); - return 0; - } - return 1; /* Can't do it */ -} - static PyObject * int_int(PyIntObject *v) { @@ -1036,7 +1025,7 @@ (binaryfunc)int_and, /*nb_and*/ (binaryfunc)int_xor, /*nb_xor*/ (binaryfunc)int_or, /*nb_or*/ - int_coerce, /*nb_coerce*/ + 0, /*nb_coerce*/ (unaryfunc)int_int, /*nb_int*/ (unaryfunc)int_long, /*nb_long*/ (unaryfunc)int_float, /*nb_float*/ @@ -1052,7 +1041,7 @@ 0, /*nb_inplace_and*/ 0, /*nb_inplace_xor*/ 0, /*nb_inplace_or*/ - (binaryfunc)int_div, /* nb_floor_divide */ + (binaryfunc)int_floor_div, /* nb_floor_divide */ int_true_divide, /* nb_true_divide */ 0, /* nb_inplace_floor_divide */ 0, /* nb_inplace_true_divide */ Modified: python/branches/p3yk/Objects/object.c ============================================================================== --- python/branches/p3yk/Objects/object.c (original) +++ python/branches/p3yk/Objects/object.c Mon Aug 21 19:06:07 2006 @@ -681,9 +681,7 @@ b) have different types or a type without tp_compare; and c) don't have a user-defined tp_compare. tp_compare implementations in C assume that both arguments - have their type, so we give up if the coercion fails or if - it yields types which are still incompatible (which can - happen with a user-defined nb_coerce). + have their type, so we give up if the coercion fails. */ c = PyNumber_CoerceEx(&v, &w); if (c < 0) @@ -1513,22 +1511,6 @@ return 1; } -/* Coerce two numeric types to the "larger" one. - Increment the reference count on each argument. - Return -1 and raise an exception if no coercion is possible - (and then no reference count is incremented). -*/ -int -PyNumber_Coerce(PyObject **pv, PyObject **pw) -{ - int err = PyNumber_CoerceEx(pv, pw); - if (err <= 0) - return err; - PyErr_SetString(PyExc_TypeError, "number coercion failed"); - return -1; -} - - /* Test whether an object can be called */ int Modified: python/branches/p3yk/Objects/typeobject.c ============================================================================== --- python/branches/p3yk/Objects/typeobject.c (original) +++ python/branches/p3yk/Objects/typeobject.c Mon Aug 21 19:06:07 2006 @@ -3327,34 +3327,6 @@ } static PyObject * -wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped) -{ - coercion func = (coercion)wrapped; - PyObject *other, *res; - int ok; - - if (!check_num_args(args, 1)) - return NULL; - other = PyTuple_GET_ITEM(args, 0); - ok = func(&self, &other); - if (ok < 0) - return NULL; - if (ok > 0) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - res = PyTuple_New(2); - if (res == NULL) { - Py_DECREF(self); - Py_DECREF(other); - return NULL; - } - PyTuple_SET_ITEM(res, 0, self); - PyTuple_SET_ITEM(res, 1, other); - return res; -} - -static PyObject * wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped) { ternaryfunc func = (ternaryfunc)wrapped; @@ -4247,64 +4219,6 @@ SLOT1BIN(slot_nb_xor, nb_xor, "__xor__", "__rxor__") SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__") -static int -slot_nb_coerce(PyObject **a, PyObject **b) -{ - static PyObject *coerce_str; - PyObject *self = *a, *other = *b; - - if (self->ob_type->tp_as_number != NULL && - self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) { - PyObject *r; - r = call_maybe( - self, "__coerce__", &coerce_str, "(O)", other); - if (r == NULL) - return -1; - if (r == Py_NotImplemented) { - Py_DECREF(r); - } - else { - if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) { - PyErr_SetString(PyExc_TypeError, - "__coerce__ didn't return a 2-tuple"); - Py_DECREF(r); - return -1; - } - *a = PyTuple_GET_ITEM(r, 0); - Py_INCREF(*a); - *b = PyTuple_GET_ITEM(r, 1); - Py_INCREF(*b); - Py_DECREF(r); - return 0; - } - } - if (other->ob_type->tp_as_number != NULL && - other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) { - PyObject *r; - r = call_maybe( - other, "__coerce__", &coerce_str, "(O)", self); - if (r == NULL) - return -1; - if (r == Py_NotImplemented) { - Py_DECREF(r); - return 1; - } - if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) { - PyErr_SetString(PyExc_TypeError, - "__coerce__ didn't return a 2-tuple"); - Py_DECREF(r); - return -1; - } - *a = PyTuple_GET_ITEM(r, 1); - Py_INCREF(*a); - *b = PyTuple_GET_ITEM(r, 0); - Py_INCREF(*b); - Py_DECREF(r); - return 0; - } - return 1; -} - SLOT0(slot_nb_int, "__int__") SLOT0(slot_nb_long, "__long__") SLOT0(slot_nb_float, "__float__") @@ -4958,8 +4872,6 @@ RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"), BINSLOT("__or__", nb_or, slot_nb_or, "|"), RBINSLOT("__ror__", nb_or, slot_nb_or, "|"), - NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc, - "x.__coerce__(y) <==> coerce(x, y)"), UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc, "int(x)"), UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc, Modified: python/branches/p3yk/PC/_winreg.c ============================================================================== --- python/branches/p3yk/PC/_winreg.c (original) +++ python/branches/p3yk/PC/_winreg.c Mon Aug 21 19:06:07 2006 @@ -444,7 +444,6 @@ PyHKEY_binaryFailureFunc, /* nb_and */ PyHKEY_binaryFailureFunc, /* nb_xor */ PyHKEY_binaryFailureFunc, /* nb_or */ - 0, /* nb_coerce (allowed to be zero) */ PyHKEY_intFunc, /* nb_int */ PyHKEY_unaryFailureFunc, /* nb_long */ PyHKEY_unaryFailureFunc, /* nb_float */ Modified: python/branches/p3yk/Python/bltinmodule.c ============================================================================== --- python/branches/p3yk/Python/bltinmodule.c (original) +++ python/branches/p3yk/Python/bltinmodule.c Mon Aug 21 19:06:07 2006 @@ -333,30 +333,6 @@ \n\ Return negative if xy."); - -static PyObject * -builtin_coerce(PyObject *self, PyObject *args) -{ - PyObject *v, *w; - PyObject *res; - - if (!PyArg_UnpackTuple(args, "coerce", 2, 2, &v, &w)) - return NULL; - if (PyNumber_Coerce(&v, &w) < 0) - return NULL; - res = PyTuple_Pack(2, v, w); - Py_DECREF(v); - Py_DECREF(w); - return res; -} - -PyDoc_STRVAR(coerce_doc, -"coerce(x, y) -> (x1, y1)\n\ -\n\ -Return a tuple consisting of the two numeric arguments converted to\n\ -a common type, using the same rules as used by arithmetic operations.\n\ -If coercion is not possible, raise TypeError."); - static PyObject * builtin_compile(PyObject *self, PyObject *args) { @@ -2068,7 +2044,6 @@ {"callable", builtin_callable, METH_O, callable_doc}, {"chr", builtin_chr, METH_VARARGS, chr_doc}, {"cmp", builtin_cmp, METH_VARARGS, cmp_doc}, - {"coerce", builtin_coerce, METH_VARARGS, coerce_doc}, {"compile", builtin_compile, METH_VARARGS, compile_doc}, {"delattr", builtin_delattr, METH_VARARGS, delattr_doc}, {"dir", builtin_dir, METH_VARARGS, dir_doc}, From python-3000-checkins at python.org Mon Aug 21 20:27:08 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Mon, 21 Aug 2006 20:27:08 +0200 (CEST) Subject: [Python-3000-checkins] r51435 - in python/branches/p3yk: BROKEN Objects/complexobject.c Message-ID: <20060821182708.A235E1E4009@bag.python.org> Author: guido.van.rossum Date: Mon Aug 21 20:27:07 2006 New Revision: 51435 Modified: python/branches/p3yk/BROKEN python/branches/p3yk/Objects/complexobject.c Log: Fix comparing complex to non-complex numbers. Modified: python/branches/p3yk/BROKEN ============================================================================== --- python/branches/p3yk/BROKEN (original) +++ python/branches/p3yk/BROKEN Mon Aug 21 20:27:07 2006 @@ -110,31 +110,3 @@ File "../Lib/test/test_set.py", line 291, in test_remove self.assert_(self.thetype(self.word) in s) AssertionError - -//////////////////////////////////////////////////////////////////////// -test_compare -//////////////////////////////////////////////////////////////////////// -test test_compare failed -- Traceback (most recent call last): - File "/Users/nnorwitz/build/python/py3k.2/Lib/test/test_compare.py", line 28, in test_comparisons - self.assertEqual(a, b) -AssertionError: 2 != (2+0j) - -//////////////////////////////////////////////////////////////////////// -test_complex -//////////////////////////////////////////////////////////////////////// -====================================================================== -FAIL: test_pow (test.test_complex.ComplexTest) ----------------------------------------------------------------------- -Traceback (most recent call last): - File "/Users/nnorwitz/build/python/py3k.2/Lib/test/test_complex.py", line 130, in test_pow - self.assertEqual(a ** 0j, 1) -AssertionError: (1+0j) != 1 - -====================================================================== -FAIL: test_richcompare (test.test_complex.ComplexTest) ----------------------------------------------------------------------- -Traceback (most recent call last): - File "/Users/nnorwitz/build/python/py3k.2/Lib/test/test_complex.py", line 96, in test_richcompare - self.assertRaises(OverflowError, complex.__eq__, 1+1j, 1L<<10000) -AssertionError: OverflowError not raised - Modified: python/branches/p3yk/Objects/complexobject.c ============================================================================== --- python/branches/p3yk/Objects/complexobject.c (original) +++ python/branches/p3yk/Objects/complexobject.c Mon Aug 21 20:27:07 2006 @@ -576,19 +576,13 @@ static PyObject * complex_richcompare(PyObject *v, PyObject *w, int op) { - Py_complex i, j; PyObject *res; - - /* Make sure both arguments are complex. */ - if (!(PyComplex_Check(v) && PyComplex_Check(w))) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - - i = ((PyComplexObject *)v)->cval; - j = ((PyComplexObject *)w)->cval; + Py_complex i, j; + TO_COMPLEX(v, i); + TO_COMPLEX(w, j); if (op != Py_EQ && op != Py_NE) { + /* XXX Should eventually return NotImplemented */ PyErr_SetString(PyExc_TypeError, "no ordering relation is defined for complex numbers"); return NULL; From python-3000-checkins at python.org Mon Aug 21 21:53:20 2006 From: python-3000-checkins at python.org (alex.martelli) Date: Mon, 21 Aug 2006 21:53:20 +0200 (CEST) Subject: [Python-3000-checkins] r51440 - python/branches/p3yk/Lib/xml/dom/minidom.py Message-ID: <20060821195320.BC25E1E4009@bag.python.org> Author: alex.martelli Date: Mon Aug 21 21:53:20 2006 New Revision: 51440 Modified: python/branches/p3yk/Lib/xml/dom/minidom.py Log: Changed minidom.py to work correctly with new-style classes (since there are no other kinds of classes in Py3K). Modified: python/branches/p3yk/Lib/xml/dom/minidom.py ============================================================================== --- python/branches/p3yk/Lib/xml/dom/minidom.py (original) +++ python/branches/p3yk/Lib/xml/dom/minidom.py Mon Aug 21 21:53:20 2006 @@ -359,6 +359,8 @@ # nodeValue and value are set elsewhere def _get_localName(self): + if 'localName' in self.__dict__: + return self.__dict__['localName'] return self.nodeName.split(":", 1)[-1] def _get_name(self): @@ -662,6 +664,8 @@ # namespaces. def _get_localName(self): + if 'localName' in self.__dict__: + return self.__dict__['localName'] return self.tagName.split(":", 1)[-1] def _get_tagName(self): @@ -1118,7 +1122,7 @@ return None -class Comment(Childless, CharacterData): +class Comment(CharacterData): nodeType = Node.COMMENT_NODE nodeName = "#comment" From python-3000-checkins at python.org Mon Aug 21 21:55:37 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Mon, 21 Aug 2006 21:55:37 +0200 (CEST) Subject: [Python-3000-checkins] r51441 - python/branches/p3yk/BROKEN Message-ID: <20060821195537.031CF1E4017@bag.python.org> Author: guido.van.rossum Date: Mon Aug 21 21:55:37 2006 New Revision: 51441 Modified: python/branches/p3yk/BROKEN Log: minidom is fixed. Modified: python/branches/p3yk/BROKEN ============================================================================== --- python/branches/p3yk/BROKEN (original) +++ python/branches/p3yk/BROKEN Mon Aug 21 21:55:37 2006 @@ -9,14 +9,6 @@ #5922 0x00021124 in PyObject_Call (func=0x5b0c90, arg=0x3384c0, kw=0x134e10) at ../Objects/abstract.c:1791 //////////////////////////////////////////////////////////////////////// -test_minidom -//////////////////////////////////////////////////////////////////////// - -test test_minidom crashed -- : Error when calling the metaclass bases - Cannot create a consistent method resolution -order (MRO) for bases object, GetattrMagic - -//////////////////////////////////////////////////////////////////////// test_xml_etree //////////////////////////////////////////////////////////////////////// From python-3000-checkins at python.org Mon Aug 21 22:54:39 2006 From: python-3000-checkins at python.org (alex.martelli) Date: Mon, 21 Aug 2006 22:54:39 +0200 (CEST) Subject: [Python-3000-checkins] r51445 - python/branches/p3yk/Lib/xml/etree/ElementInclude.py python/branches/p3yk/Lib/xml/etree/ElementTree.py Message-ID: <20060821205439.3D6171E4009@bag.python.org> Author: alex.martelli Date: Mon Aug 21 22:54:38 2006 New Revision: 51445 Modified: python/branches/p3yk/Lib/xml/etree/ElementInclude.py python/branches/p3yk/Lib/xml/etree/ElementTree.py Log: Use proper py3k syntax for relative import (from . import foo) Modified: python/branches/p3yk/Lib/xml/etree/ElementInclude.py ============================================================================== --- python/branches/p3yk/Lib/xml/etree/ElementInclude.py (original) +++ python/branches/p3yk/Lib/xml/etree/ElementInclude.py Mon Aug 21 22:54:38 2006 @@ -49,7 +49,7 @@ ## import copy -import ElementTree +from . import ElementTree XINCLUDE = "{http://www.w3.org/2001/XInclude}" Modified: python/branches/p3yk/Lib/xml/etree/ElementTree.py ============================================================================== --- python/branches/p3yk/Lib/xml/etree/ElementTree.py (original) +++ python/branches/p3yk/Lib/xml/etree/ElementTree.py Mon Aug 21 22:54:38 2006 @@ -133,9 +133,10 @@ return result try: - import ElementPath + from . import ElementPath except ImportError: # FIXME: issue warning in this case? + # TODO: DEFINITELY issue warning here!!! ElementPath = _SimpleElementPath() # TODO: add support for custom namespace resolvers/default namespaces From python-3000-checkins at python.org Mon Aug 21 22:57:17 2006 From: python-3000-checkins at python.org (alex.martelli) Date: Mon, 21 Aug 2006 22:57:17 +0200 (CEST) Subject: [Python-3000-checkins] r51446 - python/branches/p3yk/BROKEN Message-ID: <20060821205717.5A4E71E4009@bag.python.org> Author: alex.martelli Date: Mon Aug 21 22:57:17 2006 New Revision: 51446 Modified: python/branches/p3yk/BROKEN Log: etree unittest not broken any more Modified: python/branches/p3yk/BROKEN ============================================================================== --- python/branches/p3yk/BROKEN (original) +++ python/branches/p3yk/BROKEN Mon Aug 21 22:57:17 2006 @@ -9,17 +9,6 @@ #5922 0x00021124 in PyObject_Call (func=0x5b0c90, arg=0x3384c0, kw=0x134e10) at ../Objects/abstract.c:1791 //////////////////////////////////////////////////////////////////////// -test_xml_etree -//////////////////////////////////////////////////////////////////////// - -3 items had failures: - 18 of 32 in test.test_xml_etree.find - 1 of 3 in test.test_xml_etree.sanity - 8 of 12 in test.test_xml_etree.xinclude -***Test Failed*** 27 failures. -test test_xml_etree failed -- 27 of 91 doctests failed - -//////////////////////////////////////////////////////////////////////// test_xml_etree_c //////////////////////////////////////////////////////////////////////// From python-3000-checkins at python.org Mon Aug 21 22:58:26 2006 From: python-3000-checkins at python.org (alex.martelli) Date: Mon, 21 Aug 2006 22:58:26 +0200 (CEST) Subject: [Python-3000-checkins] r51447 - python/branches/p3yk/BROKEN Message-ID: <20060821205826.E70911E4009@bag.python.org> Author: alex.martelli Date: Mon Aug 21 22:58:26 2006 New Revision: 51447 Modified: python/branches/p3yk/BROKEN Log: etree_c not broken any more. Modified: python/branches/p3yk/BROKEN ============================================================================== --- python/branches/p3yk/BROKEN (original) +++ python/branches/p3yk/BROKEN Mon Aug 21 22:58:26 2006 @@ -9,22 +9,6 @@ #5922 0x00021124 in PyObject_Call (func=0x5b0c90, arg=0x3384c0, kw=0x134e10) at ../Objects/abstract.c:1791 //////////////////////////////////////////////////////////////////////// -test_xml_etree_c -//////////////////////////////////////////////////////////////////////// - -********************************************************************** -File "/Users/guido/projects/python/py3k/Lib/test/test_xml_etree_c.py", line 112, in test.test_xml_etree_c.find -Failed example: - elem.find("section/tag").tag -Exception raised: - Traceback (most recent call last): - File "/Users/guido/projects/python/py3k/Lib/doctest.py", line 1207, in __run - compileflags, 1) in test.globs - File "", line 1, in - elem.find("section/tag").tag - AttributeError: 'NoneType' object has no attribute 'tag' - -//////////////////////////////////////////////////////////////////////// test_descr //////////////////////////////////////////////////////////////////////// From python-3000-checkins at python.org Tue Aug 22 00:15:42 2006 From: python-3000-checkins at python.org (thomas.wouters) Date: Tue, 22 Aug 2006 00:15:42 +0200 (CEST) Subject: [Python-3000-checkins] r51449 - python/branches/p3yk/Modules/gcmodule.c Message-ID: <20060821221542.8E1051E4023@bag.python.org> Author: thomas.wouters Date: Tue Aug 22 00:15:41 2006 New Revision: 51449 Modified: python/branches/p3yk/Modules/gcmodule.c Log: Fix test_gc failure by fixing the bug test_gc found: __del__ methods were no longer preventing classes from being cleaned up by the cycle-gc, after Guido removed references to PyInstance_*. Modified: python/branches/p3yk/Modules/gcmodule.c ============================================================================== --- python/branches/p3yk/Modules/gcmodule.c (original) +++ python/branches/p3yk/Modules/gcmodule.c Tue Aug 22 00:15:41 2006 @@ -411,7 +411,7 @@ if (PyGen_CheckExact(op)) return PyGen_NeedsFinalizing((PyGenObject *)op); else - return 0; + return op->ob_type->tp_del != NULL; } /* Move the objects in unreachable with __del__ methods into `finalizers`. From python-3000-checkins at python.org Tue Aug 22 00:25:22 2006 From: python-3000-checkins at python.org (thomas.wouters) Date: Tue, 22 Aug 2006 00:25:22 +0200 (CEST) Subject: [Python-3000-checkins] r51451 - python/branches/p3yk/BROKEN Message-ID: <20060821222522.5DE3B1E4009@bag.python.org> Author: thomas.wouters Date: Tue Aug 22 00:25:22 2006 New Revision: 51451 Modified: python/branches/p3yk/BROKEN Log: test_gc is no longer broken Modified: python/branches/p3yk/BROKEN ============================================================================== --- python/branches/p3yk/BROKEN (original) +++ python/branches/p3yk/BROKEN Tue Aug 22 00:25:22 2006 @@ -22,23 +22,6 @@ raise TestFailed, "hash() of dict subclass should fail" test.test_support.TestFailed: hash() of dict subclass should fail -//////////////////////////////////////////////////////////////////////// -test_gc -//////////////////////////////////////////////////////////////////////// - -testing finalizers... restoring automatic collection -Traceback (most recent call last): - File "../Lib/test/test_gc.py", line 636, in - test() - File "../Lib/test/test_gc.py", line 623, in test - test_all() - File "../Lib/test/test_gc.py", line 586, in test_all - run_test("finalizers", test_finalizer) - File "../Lib/test/test_gc.py", line 18, in run_test - thunk() - File "../Lib/test/test_gc.py", line 125, in test_finalizer - raise TestFailed, "didn't find obj in garbage (finalizer)" -test.test_support.TestFailed: didn't find obj in garbage (finalizer) //////////////////////////////////////////////////////////////////////// test_set From python-3000-checkins at python.org Tue Aug 22 01:36:27 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Tue, 22 Aug 2006 01:36:27 +0200 (CEST) Subject: [Python-3000-checkins] r51454 - in python/branches/p3yk: BROKEN Include/object.h Lib/test/mapping_tests.py Lib/test/test_dict.py Objects/object.c Objects/typeobject.c Message-ID: <20060821233627.B70731E4009@bag.python.org> Author: guido.van.rossum Date: Tue Aug 22 01:36:26 2006 New Revision: 51454 Modified: python/branches/p3yk/BROKEN python/branches/p3yk/Include/object.h python/branches/p3yk/Lib/test/mapping_tests.py python/branches/p3yk/Lib/test/test_dict.py python/branches/p3yk/Objects/object.c python/branches/p3yk/Objects/typeobject.c Log: Change the way __hash__ is inherited; when __eq__ or __cmp__ is overridden but __hash__ is not, set __hash__ explicitly to None (and tp_hash to NULL). All unit tests pass now! Modified: python/branches/p3yk/BROKEN ============================================================================== --- python/branches/p3yk/BROKEN (original) +++ python/branches/p3yk/BROKEN Tue Aug 22 01:36:26 2006 @@ -1,60 +1 @@ -//////////////////////////////////////////////////////////////////////// -test_class -//////////////////////////////////////////////////////////////////////// - -test test_class failed -- hash(C1()) should raise -Also hash(C2()) -Also stack blowout, recursing between -#5921 0x0003868c in slot_tp_call (self=0x5b0c90, args=0x338030, kwds=0x0) at ../Objects/typeobject.c:4583 -#5922 0x00021124 in PyObject_Call (func=0x5b0c90, arg=0x3384c0, kw=0x134e10) at ../Objects/abstract.c:1791 - -//////////////////////////////////////////////////////////////////////// -test_descr -//////////////////////////////////////////////////////////////////////// - -Testing hash of mutable subclasses... -Traceback (most recent call last): - File "../Lib/test/test_descr.py", line 4096, in - test_main() - File "../Lib/test/test_descr.py", line 4059, in test_main - hashinherit() - File "../Lib/test/test_descr.py", line 3108, in hashinherit - raise TestFailed, "hash() of dict subclass should fail" -test.test_support.TestFailed: hash() of dict subclass should fail - - -//////////////////////////////////////////////////////////////////////// -test_set -//////////////////////////////////////////////////////////////////////// - -====================================================================== -FAIL: test_contains (__main__.TestSetSubclass) ----------------------------------------------------------------------- -Traceback (most recent call last): - File "../Lib/test/test_set.py", line 52, in test_contains - self.assert_(self.thetype(self.letters) in s) -AssertionError - -====================================================================== -FAIL: test_discard (__main__.TestSetSubclass) ----------------------------------------------------------------------- -Traceback (most recent call last): - File "../Lib/test/test_set.py", line 302, in test_discard - self.assert_(self.thetype(self.word) in s) -AssertionError - -====================================================================== -FAIL: test_hash (__main__.TestSetSubclass) ----------------------------------------------------------------------- -Traceback (most recent call last): - File "../Lib/test/test_set.py", line 265, in test_hash - self.assertRaises(TypeError, hash, self.s) -AssertionError: TypeError not raised - -====================================================================== -FAIL: test_remove (__main__.TestSetSubclass) ----------------------------------------------------------------------- -Traceback (most recent call last): - File "../Lib/test/test_set.py", line 291, in test_remove - self.assert_(self.thetype(self.word) in s) -AssertionError +(Nothing is broken at the moment AFAIK.) Modified: python/branches/p3yk/Include/object.h ============================================================================== --- python/branches/p3yk/Include/object.h (original) +++ python/branches/p3yk/Include/object.h Tue Aug 22 01:36:26 2006 @@ -368,6 +368,7 @@ /* Generic operations on objects */ PyAPI_FUNC(int) PyObject_Print(PyObject *, FILE *, int); +PyAPI_FUNC(void) _Py_Break(void); PyAPI_FUNC(void) _PyObject_Dump(PyObject *); PyAPI_FUNC(PyObject *) PyObject_Repr(PyObject *); PyAPI_FUNC(PyObject *) _PyObject_Str(PyObject *); Modified: python/branches/p3yk/Lib/test/mapping_tests.py ============================================================================== --- python/branches/p3yk/Lib/test/mapping_tests.py (original) +++ python/branches/p3yk/Lib/test/mapping_tests.py Tue Aug 22 01:36:26 2006 @@ -545,6 +545,8 @@ class BadEq(object): def __eq__(self, other): raise Exc() + def __hash__(self): + return 24 d = self._empty_mapping() d[BadEq()] = 42 @@ -630,6 +632,8 @@ class BadCmp(object): def __eq__(self, other): raise Exc() + def __hash__(self): + return 42 d1 = self._full_mapping({BadCmp(): 1}) d2 = self._full_mapping({1: 1}) Modified: python/branches/p3yk/Lib/test/test_dict.py ============================================================================== --- python/branches/p3yk/Lib/test/test_dict.py (original) +++ python/branches/p3yk/Lib/test/test_dict.py Tue Aug 22 01:36:26 2006 @@ -76,6 +76,8 @@ class BadEq(object): def __eq__(self, other): raise Exc() + def __hash__(self): + return 24 d = {} d[BadEq()] = 42 @@ -375,6 +377,8 @@ class BadCmp(object): def __eq__(self, other): raise Exc() + def __hash__(self): + return 42 d1 = {BadCmp(): 1} d2 = {1: 1} Modified: python/branches/p3yk/Objects/object.c ============================================================================== --- python/branches/p3yk/Objects/object.c (original) +++ python/branches/p3yk/Objects/object.c Tue Aug 22 01:36:26 2006 @@ -320,9 +320,16 @@ return internal_print(op, fp, flags, 0); } +/* For debugging convenience. Set a breakpoint here and call it from your DLL */ +void +_Py_Break(void) +{ +} + /* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */ -void _PyObject_Dump(PyObject* op) +void +_PyObject_Dump(PyObject* op) { if (op == NULL) fprintf(stderr, "NULL\n"); Modified: python/branches/p3yk/Objects/typeobject.c ============================================================================== --- python/branches/p3yk/Objects/typeobject.c (original) +++ python/branches/p3yk/Objects/typeobject.c Tue Aug 22 01:36:26 2006 @@ -2847,6 +2847,33 @@ COPYVAL(tp_dictoffset); } +/* Map rich comparison operators to their __xx__ namesakes */ +static char *name_op[] = { + "__lt__", + "__le__", + "__eq__", + "__ne__", + "__gt__", + "__ge__", + /* These are only for overrides_cmp_or_hash(): */ + "__cmp__", + "__hash__", +}; + +static int +overrides_cmp_or_hash(PyTypeObject *type) +{ + int i; + PyObject *dict = type->tp_dict; + + assert(dict != NULL); + for (i = 0; i < 8; i++) { + if (PyDict_GetItemString(dict, name_op[i]) != NULL) + return 1; + } + return 0; +} + static void inherit_slots(PyTypeObject *type, PyTypeObject *base) { @@ -2970,9 +2997,12 @@ COPYSLOT(tp_call); COPYSLOT(tp_str); { + /* Copy comparison-related slots only when + not overriding them anywhere */ if (type->tp_compare == NULL && type->tp_richcompare == NULL && - type->tp_hash == NULL) + type->tp_hash == NULL && + !overrides_cmp_or_hash(type)) { type->tp_compare = base->tp_compare; type->tp_richcompare = base->tp_richcompare; @@ -3020,6 +3050,10 @@ PyTypeObject *base; Py_ssize_t i, n; + if (strcmp(type->tp_name, "C") == 0) { + _Py_Break(); + } + if (type->tp_flags & Py_TPFLAGS_READY) { assert(type->tp_dict != NULL); return 0; @@ -3150,6 +3184,18 @@ } } + /* Hack for tp_hash and __hash__. + If after all that, tp_hash is still NULL, and __hash__ is not in + tp_dict, set tp_dict['__hash__'] equal to None. + This signals that __hash__ is not inherited. + */ + if (type->tp_hash == NULL) { + if (PyDict_GetItemString(type->tp_dict, "__hash__") == NULL) { + if (PyDict_SetItemString(type->tp_dict, "__hash__", Py_None) < 0) + goto error; + } + } + /* Some more special stuff */ base = type->tp_base; if (base != NULL) { @@ -4450,16 +4496,6 @@ return 0; } -/* Map rich comparison operators to their __xx__ namesakes */ -static char *name_op[] = { - "__lt__", - "__le__", - "__eq__", - "__ne__", - "__gt__", - "__ge__", -}; - static PyObject * half_richcompare(PyObject *self, PyObject *other, int op) { From python-3000-checkins at python.org Tue Aug 22 01:40:18 2006 From: python-3000-checkins at python.org (thomas.wouters) Date: Tue, 22 Aug 2006 01:40:18 +0200 (CEST) Subject: [Python-3000-checkins] r51455 - python/branches/p3yk/Objects/typeobject.c Message-ID: <20060821234018.3181C1E4009@bag.python.org> Author: thomas.wouters Date: Tue Aug 22 01:40:16 2006 New Revision: 51455 Modified: python/branches/p3yk/Objects/typeobject.c Log: remove debugging turd. Modified: python/branches/p3yk/Objects/typeobject.c ============================================================================== --- python/branches/p3yk/Objects/typeobject.c (original) +++ python/branches/p3yk/Objects/typeobject.c Tue Aug 22 01:40:16 2006 @@ -3050,10 +3050,6 @@ PyTypeObject *base; Py_ssize_t i, n; - if (strcmp(type->tp_name, "C") == 0) { - _Py_Break(); - } - if (type->tp_flags & Py_TPFLAGS_READY) { assert(type->tp_dict != NULL); return 0; From python-3000-checkins at python.org Tue Aug 22 01:45:19 2006 From: python-3000-checkins at python.org (alex.martelli) Date: Tue, 22 Aug 2006 01:45:19 +0200 (CEST) Subject: [Python-3000-checkins] r51457 - python/branches/p3yk/Lib/xml/etree/ElementTree.py Message-ID: <20060821234519.81B5F1E4009@bag.python.org> Author: alex.martelli Date: Tue Aug 22 01:45:19 2006 New Revision: 51457 Modified: python/branches/p3yk/Lib/xml/etree/ElementTree.py Log: Jacques Frechet's and John Reese's simplification of ElementTree: give up attempts at backwards compatibility which can't work anyway on Py3k (and aren't needed for Python 2.5 and later). Modified: python/branches/p3yk/Lib/xml/etree/ElementTree.py ============================================================================== --- python/branches/p3yk/Lib/xml/etree/ElementTree.py (original) +++ python/branches/p3yk/Lib/xml/etree/ElementTree.py Tue Aug 22 01:45:19 2006 @@ -111,33 +111,7 @@ import string, sys, re -class _SimpleElementPath: - # emulate pre-1.2 find/findtext/findall behaviour - def find(self, element, tag): - for elem in element: - if elem.tag == tag: - return elem - return None - def findtext(self, element, tag, default=None): - for elem in element: - if elem.tag == tag: - return elem.text or "" - return default - def findall(self, element, tag): - if tag[:3] == ".//": - return element.getiterator(tag[3:]) - result = [] - for elem in element: - if elem.tag == tag: - result.append(elem) - return result - -try: - from . import ElementPath -except ImportError: - # FIXME: issue warning in this case? - # TODO: DEFINITELY issue warning here!!! - ElementPath = _SimpleElementPath() +from . import ElementPath # TODO: add support for custom namespace resolvers/default namespaces # TODO: add improved support for incremental parsing From python-3000-checkins at python.org Tue Aug 22 02:21:27 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Tue, 22 Aug 2006 02:21:27 +0200 (CEST) Subject: [Python-3000-checkins] r51459 - in python/branches/p3yk: Lib/csv.py Lib/difflib.py Lib/idlelib/AutoCompleteWindow.py Lib/idlelib/MultiCall.py Lib/test/test_builtin.py Lib/test/test_iter.py Lib/test/test_random.py Python/bltinmodule.c Tools/i18n/pygettext.py Tools/pybench/pybench.py Message-ID: <20060822002127.B51051E4009@bag.python.org> Author: guido.van.rossum Date: Tue Aug 22 02:21:25 2006 New Revision: 51459 Modified: python/branches/p3yk/Lib/csv.py python/branches/p3yk/Lib/difflib.py python/branches/p3yk/Lib/idlelib/AutoCompleteWindow.py python/branches/p3yk/Lib/idlelib/MultiCall.py python/branches/p3yk/Lib/test/test_builtin.py python/branches/p3yk/Lib/test/test_iter.py python/branches/p3yk/Lib/test/test_random.py python/branches/p3yk/Python/bltinmodule.c python/branches/p3yk/Tools/i18n/pygettext.py python/branches/p3yk/Tools/pybench/pybench.py Log: Kill reduce(). A coproduction of John Reese, Jacques Frechet, and Alex M. Modified: python/branches/p3yk/Lib/csv.py ============================================================================== --- python/branches/p3yk/Lib/csv.py (original) +++ python/branches/p3yk/Lib/csv.py Tue Aug 22 02:21:25 2006 @@ -221,12 +221,10 @@ if m[n]: spaces += 1 - quotechar = reduce(lambda a, b, quotes = quotes: - (quotes[a] > quotes[b]) and a or b, quotes.keys()) + quotechar = max(quotes, key=quotes.get) if delims: - delim = reduce(lambda a, b, delims = delims: - (delims[a] > delims[b]) and a or b, delims.keys()) + delim = max(delims, key=delims.get) skipinitialspace = delims[delim] == spaces if delim == '\n': # most likely a file with a single column delim = '' @@ -285,14 +283,12 @@ continue # get the mode of the frequencies if len(items) > 1: - modes[char] = reduce(lambda a, b: a[1] > b[1] and a or b, - items) + modes[char] = max(items, key=lambda x: x[1]) # adjust the mode - subtract the sum of all # other frequencies items.remove(modes[char]) modes[char] = (modes[char][0], modes[char][1] - - reduce(lambda a, b: (0, a[1] + b[1]), - items)[1]) + - sum(item[1] for item in items)) else: modes[char] = items[0] Modified: python/branches/p3yk/Lib/difflib.py ============================================================================== --- python/branches/p3yk/Lib/difflib.py (original) +++ python/branches/p3yk/Lib/difflib.py Tue Aug 22 02:21:25 2006 @@ -652,8 +652,7 @@ 1.0 """ - matches = reduce(lambda sum, triple: sum + triple[-1], - self.get_matching_blocks(), 0) + matches = sum(triple[-1] for triple in self.get_matching_blocks()) return _calculate_ratio(matches, len(self.a) + len(self.b)) def quick_ratio(self): Modified: python/branches/p3yk/Lib/idlelib/AutoCompleteWindow.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/AutoCompleteWindow.py (original) +++ python/branches/p3yk/Lib/idlelib/AutoCompleteWindow.py Tue Aug 22 02:21:25 2006 @@ -335,10 +335,8 @@ self.userwantswindow = True return - elif reduce(lambda x, y: x or y, - [keysym.find(s) != -1 for s in ("Shift", "Control", "Alt", - "Meta", "Command", "Option") - ]): + elif any(s in keysym for s in ("Shift", "Control", "Alt", + "Meta", "Command", "Option")): # A modifier key, so ignore return Modified: python/branches/p3yk/Lib/idlelib/MultiCall.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/MultiCall.py (original) +++ python/branches/p3yk/Lib/idlelib/MultiCall.py Tue Aug 22 02:21:25 2006 @@ -106,24 +106,26 @@ # _state_subsets gives for each combination of modifiers, or *state*, # a list of the states which are a subset of it. This list is ordered by the # number of modifiers is the state - the most specific state comes first. +# XXX rewrite without overusing functional primitives :-) _states = range(1 << len(_modifiers)) -_state_names = [reduce(lambda x, y: x + y, - [_modifiers[i][0]+'-' for i in range(len(_modifiers)) - if (1 << i) & s], - "") +_state_names = [''.join(m[0]+'-' + for i, m in enumerate(_modifiers) + if (1 << i) & s) for s in _states] _state_subsets = map(lambda i: filter(lambda j: not (j & (~i)), _states), - _states) + _states) for l in _state_subsets: l.sort(lambda a, b, nummod = lambda x: len(filter(lambda i: (1<ob_refcnt > 1) { - Py_DECREF(args); - if ((args = PyTuple_New(2)) == NULL) - goto Fail; - } - - op2 = PyIter_Next(it); - if (op2 == NULL) { - if (PyErr_Occurred()) - goto Fail; - break; - } - - if (result == NULL) - result = op2; - else { - PyTuple_SetItem(args, 0, result); - PyTuple_SetItem(args, 1, op2); - if ((result = PyEval_CallObject(func, args)) == NULL) - goto Fail; - } - } - - Py_DECREF(args); - - if (result == NULL) - PyErr_SetString(PyExc_TypeError, - "reduce() of empty sequence with no initial value"); - - Py_DECREF(it); - return result; - -Fail: - Py_XDECREF(args); - Py_XDECREF(result); - Py_DECREF(it); - return NULL; -} - -PyDoc_STRVAR(reduce_doc, -"reduce(function, sequence[, initial]) -> value\n\ -\n\ -Apply a function of two arguments cumulatively to the items of a sequence,\n\ -from left to right, so as to reduce the sequence to a single value.\n\ -For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\ -((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\ -of the sequence in the calculation, and serves as a default when the\n\ -sequence is empty."); - - -static PyObject * builtin_reload(PyObject *self, PyObject *v) { return PyImport_ReloadModule(v); @@ -2071,7 +1997,6 @@ {"ord", builtin_ord, METH_O, ord_doc}, {"pow", builtin_pow, METH_VARARGS, pow_doc}, {"range", builtin_range, METH_VARARGS, range_doc}, - {"reduce", builtin_reduce, METH_VARARGS, reduce_doc}, {"reload", builtin_reload, METH_O, reload_doc}, {"repr", builtin_repr, METH_O, repr_doc}, {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc}, Modified: python/branches/p3yk/Tools/i18n/pygettext.py ============================================================================== --- python/branches/p3yk/Tools/i18n/pygettext.py (original) +++ python/branches/p3yk/Tools/i18n/pygettext.py Tue Aug 22 02:21:25 2006 @@ -462,12 +462,10 @@ rentries = reverse[rkey] rentries.sort() for k, v in rentries: - isdocstring = 0 # If the entry was gleaned out of a docstring, then add a # comment stating so. This is to aid translators who may wish # to skip translating some unimportant docstrings. - if reduce(operator.__add__, v.values()): - isdocstring = 1 + isdocstring = any(v.values()) # k is the message string, v is a dictionary-set of (filename, # lineno) tuples. We want to sort the entries in v first by # file name and then by line number. Modified: python/branches/p3yk/Tools/pybench/pybench.py ============================================================================== --- python/branches/p3yk/Tools/pybench/pybench.py (original) +++ python/branches/p3yk/Tools/pybench/pybench.py Tue Aug 22 02:21:25 2006 @@ -370,7 +370,7 @@ if runs == 0: return 0.0, 0.0, 0.0, 0.0 min_time = min(self.times) - total_time = reduce(operator.add, self.times, 0.0) + total_time = sum(self.times) avg_time = total_time / float(runs) operation_avg = total_time / float(runs * self.rounds @@ -570,7 +570,7 @@ if runs == 0: return 0.0, 0.0 min_time = min(self.roundtimes) - total_time = reduce(operator.add, self.roundtimes, 0.0) + total_time = sum(self.roundtimes) avg_time = total_time / float(runs) max_time = max(self.roundtimes) return (min_time, avg_time, max_time) From python-3000-checkins at python.org Tue Aug 22 15:41:17 2006 From: python-3000-checkins at python.org (thomas.wouters) Date: Tue, 22 Aug 2006 15:41:17 +0200 (CEST) Subject: [Python-3000-checkins] r51472 - in python/branches/p3yk: Lib/test/test_bytes.py Objects/bytesobject.c Message-ID: <20060822134117.A87581E400A@bag.python.org> Author: thomas.wouters Date: Tue Aug 22 15:41:17 2006 New Revision: 51472 Modified: python/branches/p3yk/Lib/test/test_bytes.py python/branches/p3yk/Objects/bytesobject.c Log: Make bytesobject raise ValueError instead of TypeError again (thanks, Nick) Modified: python/branches/p3yk/Lib/test/test_bytes.py ============================================================================== --- python/branches/p3yk/Lib/test/test_bytes.py (original) +++ python/branches/p3yk/Lib/test/test_bytes.py Tue Aug 22 15:41:17 2006 @@ -60,13 +60,13 @@ self.assertRaises(ValueError, bytes, [-1]) self.assertRaises(ValueError, bytes, [-sys.maxint]) self.assertRaises(ValueError, bytes, [-sys.maxint-1]) - self.assertRaises(TypeError, bytes, [-sys.maxint-2]) - self.assertRaises(TypeError, bytes, [-10**100]) + self.assertRaises(ValueError, bytes, [-sys.maxint-2]) + self.assertRaises(ValueError, bytes, [-10**100]) self.assertRaises(ValueError, bytes, [256]) self.assertRaises(ValueError, bytes, [257]) self.assertRaises(ValueError, bytes, [sys.maxint]) - self.assertRaises(TypeError, bytes, [sys.maxint+1]) - self.assertRaises(TypeError, bytes, [10**100]) + self.assertRaises(ValueError, bytes, [sys.maxint+1]) + self.assertRaises(ValueError, bytes, [10**100]) def test_repr(self): self.assertEqual(repr(bytes()), "bytes()") Modified: python/branches/p3yk/Objects/bytesobject.c ============================================================================== --- python/branches/p3yk/Objects/bytesobject.c (original) +++ python/branches/p3yk/Objects/bytesobject.c Tue Aug 22 15:41:17 2006 @@ -245,7 +245,7 @@ if (PyBytes_Check(value)) return bytes_substring(self, (PyBytesObject *)value); - ival = PyNumber_AsSsize_t(value, PyExc_TypeError); + ival = PyNumber_AsSsize_t(value, PyExc_ValueError); if (ival == -1 && PyErr_Occurred()) return -1; if (ival < 0 || ival >= 256) { @@ -365,7 +365,7 @@ if (value == NULL) return bytes_setslice(self, i, i+1, NULL); - ival = PyNumber_AsSsize_t(value, PyExc_TypeError); + ival = PyNumber_AsSsize_t(value, PyExc_ValueError); if (ival == -1 && PyErr_Occurred()) return -1; @@ -448,7 +448,7 @@ } /* Is it an int? */ - count = PyNumber_AsSsize_t(arg, PyExc_TypeError); + count = PyNumber_AsSsize_t(arg, PyExc_ValueError); if (count == -1 && PyErr_Occurred()) PyErr_Clear(); else { @@ -500,7 +500,7 @@ } /* Interpret it as an int (__index__) */ - value = PyNumber_AsSsize_t(item, PyExc_TypeError); + value = PyNumber_AsSsize_t(item, PyExc_ValueError); Py_DECREF(item); if (value == -1 && PyErr_Occurred()) goto error; From python-3000-checkins at python.org Tue Aug 22 17:45:48 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Tue, 22 Aug 2006 17:45:48 +0200 (CEST) Subject: [Python-3000-checkins] r51478 - python/branches/p3yk/Lib/idlelib/EditorWindow.py python/branches/p3yk/Lib/idlelib/FileList.py python/branches/p3yk/Lib/idlelib/MultiCall.py python/branches/p3yk/Lib/idlelib/MultiStatusBar.py python/branches/p3yk/Lib/idlelib/ObjectBrowser.py python/branches/p3yk/Lib/idlelib/PathBrowser.py python/branches/p3yk/Lib/idlelib/RemoteDebugger.py python/branches/p3yk/Lib/idlelib/TreeWidget.py python/branches/p3yk/Lib/idlelib/WidgetRedirector.py python/branches/p3yk/Lib/idlelib/configDialog.py python/branches/p3yk/Lib/idlelib/rpc.py Message-ID: <20060822154548.855F81E4011@bag.python.org> Author: guido.van.rossum Date: Tue Aug 22 17:45:46 2006 New Revision: 51478 Modified: python/branches/p3yk/Lib/idlelib/EditorWindow.py python/branches/p3yk/Lib/idlelib/FileList.py python/branches/p3yk/Lib/idlelib/MultiCall.py python/branches/p3yk/Lib/idlelib/MultiStatusBar.py python/branches/p3yk/Lib/idlelib/ObjectBrowser.py python/branches/p3yk/Lib/idlelib/PathBrowser.py python/branches/p3yk/Lib/idlelib/RemoteDebugger.py python/branches/p3yk/Lib/idlelib/TreeWidget.py python/branches/p3yk/Lib/idlelib/WidgetRedirector.py python/branches/p3yk/Lib/idlelib/configDialog.py python/branches/p3yk/Lib/idlelib/rpc.py Log: Remove has_key() references from idlelib. IDLE still doesn't run due to relative import issues. Any volunteers? Modified: python/branches/p3yk/Lib/idlelib/EditorWindow.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/EditorWindow.py (original) +++ python/branches/p3yk/Lib/idlelib/EditorWindow.py Tue Aug 22 17:45:46 2006 @@ -648,8 +648,8 @@ if accel: itemName = menu.entrycget(index, 'label') event = '' - if menuEventDict.has_key(menubarItem): - if menuEventDict[menubarItem].has_key(itemName): + if menubarItem in menuEventDict: + if itemName in menuEventDict[menubarItem]: event = menuEventDict[menubarItem][itemName] if event: accel = get_accelerator(keydefs, event) Modified: python/branches/p3yk/Lib/idlelib/FileList.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/FileList.py (original) +++ python/branches/p3yk/Lib/idlelib/FileList.py Tue Aug 22 17:45:46 2006 @@ -25,7 +25,7 @@ master=self.root) return None key = os.path.normcase(filename) - if self.dict.has_key(key): + if key in self.dict: edit = self.dict[key] edit.top.wakeup() return edit @@ -79,7 +79,7 @@ newkey = os.path.normcase(filename) if newkey == key: return - if self.dict.has_key(newkey): + if newkey in self.dict: conflict = self.dict[newkey] self.inversedict[conflict] = None tkMessageBox.showerror( Modified: python/branches/p3yk/Lib/idlelib/MultiCall.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/MultiCall.py (original) +++ python/branches/p3yk/Lib/idlelib/MultiCall.py Tue Aug 22 17:45:46 2006 @@ -187,7 +187,7 @@ seq, handler))) def bind(self, triplet, func): - if not self.bindedfuncs.has_key(triplet[2]): + if triplet[2] not in self.bindedfuncs: self.bindedfuncs[triplet[2]] = [[] for s in _states] for s in _states: lists = [ self.bindedfuncs[detail][i] Modified: python/branches/p3yk/Lib/idlelib/MultiStatusBar.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/MultiStatusBar.py (original) +++ python/branches/p3yk/Lib/idlelib/MultiStatusBar.py Tue Aug 22 17:45:46 2006 @@ -9,7 +9,7 @@ self.labels = {} def set_label(self, name, text='', side=LEFT): - if not self.labels.has_key(name): + if name not in self.labels: label = Label(self, bd=1, relief=SUNKEN, anchor=W) label.pack(side=side) self.labels[name] = label Modified: python/branches/p3yk/Lib/idlelib/ObjectBrowser.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/ObjectBrowser.py (original) +++ python/branches/p3yk/Lib/idlelib/ObjectBrowser.py Tue Aug 22 17:45:46 2006 @@ -126,7 +126,7 @@ def make_objecttreeitem(labeltext, object, setfunction=None): t = type(object) - if dispatch.has_key(t): + if t in dispatch: c = dispatch[t] else: c = ObjectTreeItem Modified: python/branches/p3yk/Lib/idlelib/PathBrowser.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/PathBrowser.py (original) +++ python/branches/p3yk/Lib/idlelib/PathBrowser.py Tue Aug 22 17:45:46 2006 @@ -78,7 +78,7 @@ normed_name = os.path.normcase(name) if normed_name[i:] == suff: mod_name = name[:i] - if not modules.has_key(mod_name): + if mod_name not in modules: modules[mod_name] = None sorted.append((normed_name, name)) allnames.remove(name) Modified: python/branches/p3yk/Lib/idlelib/RemoteDebugger.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/RemoteDebugger.py (original) +++ python/branches/p3yk/Lib/idlelib/RemoteDebugger.py Tue Aug 22 17:45:46 2006 @@ -231,7 +231,7 @@ return self._get_dict_proxy(did) def _get_dict_proxy(self, did): - if self._dictcache.has_key(did): + if did in self._dictcache: return self._dictcache[did] dp = DictProxy(self._conn, self._oid, did) self._dictcache[did] = dp Modified: python/branches/p3yk/Lib/idlelib/TreeWidget.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/TreeWidget.py (original) +++ python/branches/p3yk/Lib/idlelib/TreeWidget.py Tue Aug 22 17:45:46 2006 @@ -410,7 +410,7 @@ class ScrolledCanvas: def __init__(self, master, **opts): - if not opts.has_key('yscrollincrement'): + if 'yscrollincrement' not in opts: opts['yscrollincrement'] = 17 self.master = master self.frame = Frame(master) Modified: python/branches/p3yk/Lib/idlelib/WidgetRedirector.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/WidgetRedirector.py (original) +++ python/branches/p3yk/Lib/idlelib/WidgetRedirector.py Tue Aug 22 17:45:46 2006 @@ -29,7 +29,7 @@ tk.call("rename", orig, w) def register(self, name, function): - if self.dict.has_key(name): + if name in self.dict: previous = dict[name] else: previous = OriginalCommand(self, name) @@ -38,7 +38,7 @@ return previous def unregister(self, name): - if self.dict.has_key(name): + if name in self.dict: function = self.dict[name] del self.dict[name] if hasattr(self.widget, name): Modified: python/branches/p3yk/Lib/idlelib/configDialog.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/configDialog.py (original) +++ python/branches/p3yk/Lib/idlelib/configDialog.py Tue Aug 22 17:45:46 2006 @@ -550,7 +550,7 @@ def AddChangedItem(self,type,section,item,value): value=str(value) #make sure we use a string - if not self.changedItems[type].has_key(section): + if section not in self.changedItems[type]: self.changedItems[type][section]={} self.changedItems[type][section][item]=value @@ -697,7 +697,7 @@ return #remove key set from config idleConf.userCfg['keys'].remove_section(keySetName) - if self.changedItems['keys'].has_key(keySetName): + if keySetName in self.changedItems['keys']: del(self.changedItems['keys'][keySetName]) #write changes idleConf.userCfg['keys'].Save() @@ -724,7 +724,7 @@ return #remove theme from config idleConf.userCfg['highlight'].remove_section(themeName) - if self.changedItems['highlight'].has_key(themeName): + if themeName in self.changedItems['highlight']: del(self.changedItems['highlight'][themeName]) #write changes idleConf.userCfg['highlight'].Save() @@ -859,9 +859,9 @@ #handle any unsaved changes to this theme if theme in self.changedItems['highlight'].keys(): themeDict=self.changedItems['highlight'][theme] - if themeDict.has_key(element+'-foreground'): + if element+'-foreground' in themeDict: colours['foreground']=themeDict[element+'-foreground'] - if themeDict.has_key(element+'-background'): + if element+'-background' in themeDict: colours['background']=themeDict[element+'-background'] self.textHighlightSample.tag_config(element, **colours) self.SetColourSample() Modified: python/branches/p3yk/Lib/idlelib/rpc.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/rpc.py (original) +++ python/branches/p3yk/Lib/idlelib/rpc.py Tue Aug 22 17:45:46 2006 @@ -169,7 +169,7 @@ how, (oid, methodname, args, kwargs) = request except TypeError: return ("ERROR", "Bad request format") - if not self.objtable.has_key(oid): + if oid not in self.objtable: return ("ERROR", "Unknown object id: %r" % (oid,)) obj = self.objtable[oid] if methodname == "__methods__": @@ -304,7 +304,7 @@ # wait for notification from socket handling thread cvar = self.cvars[myseq] cvar.acquire() - while not self.responses.has_key(myseq): + while myseq not in self.responses: cvar.wait() response = self.responses[myseq] self.debug("_getresponse:%s: thread woke up: response: %s" % @@ -552,7 +552,7 @@ return MethodProxy(self.sockio, self.oid, name) if self.__attributes is None: self.__getattributes() - if self.__attributes.has_key(name): + if name in self.__attributes: value = self.sockio.remotecall(self.oid, '__getattribute__', (name,), {}) return value From python-3000-checkins at python.org Wed Aug 23 20:13:40 2006 From: python-3000-checkins at python.org (jeremy.hylton) Date: Wed, 23 Aug 2006 20:13:40 +0200 (CEST) Subject: [Python-3000-checkins] r51513 - python/branches/p3yk/Python/compile.c Message-ID: <20060823181340.73F721E4005@bag.python.org> Author: jeremy.hylton Date: Wed Aug 23 20:13:39 2006 New Revision: 51513 Modified: python/branches/p3yk/Python/compile.c Log: Check for exceptions set by PyDict_GetItem(). Modified: python/branches/p3yk/Python/compile.c ============================================================================== --- python/branches/p3yk/Python/compile.c (original) +++ python/branches/p3yk/Python/compile.c Wed Aug 23 20:13:39 2006 @@ -959,6 +959,8 @@ v = PyDict_GetItem(dict, t); if (!v) { + if (PyErr_Occurred()) + return -1; arg = PyDict_Size(dict); v = PyInt_FromLong(arg); if (!v) { From python-3000-checkins at python.org Thu Aug 24 01:20:30 2006 From: python-3000-checkins at python.org (thomas.wouters) Date: Thu, 24 Aug 2006 01:20:30 +0200 (CEST) Subject: [Python-3000-checkins] r51531 - in python/branches/p3yk: Lib/test/test_bytes.py Objects/bytesobject.c Message-ID: <20060823232030.B44631E401A@bag.python.org> Author: thomas.wouters Date: Thu Aug 24 01:20:29 2006 New Revision: 51531 Modified: python/branches/p3yk/Lib/test/test_bytes.py python/branches/p3yk/Objects/bytesobject.c Log: Fix buglet in slice assignment of bytesobjects: assigning to b[3:0] ('stop' being before 'start') would actually assign to b[0:0] (or whatever 'stop' was) Modified: python/branches/p3yk/Lib/test/test_bytes.py ============================================================================== --- python/branches/p3yk/Lib/test/test_bytes.py (original) +++ python/branches/p3yk/Lib/test/test_bytes.py Thu Aug 24 01:20:29 2006 @@ -235,6 +235,9 @@ b[3:5] = [3, 4, 5, 6] self.assertEqual(b, bytes(range(10))) + + b[3:0] = [42, 42, 42] + self.assertEqual(b, bytes([0, 1, 2, 42, 42, 42, 3, 4, 5, 6, 7, 8, 9])) def test_setslice_trap(self): # This test verifies that we correctly handle assigning self Modified: python/branches/p3yk/Objects/bytesobject.c ============================================================================== --- python/branches/p3yk/Objects/bytesobject.c (original) +++ python/branches/p3yk/Objects/bytesobject.c Thu Aug 24 01:20:29 2006 @@ -310,6 +310,8 @@ if (lo < 0) lo = 0; + if (hi < lo) + hi = lo; if (hi > self->ob_size) hi = self->ob_size; From python-3000-checkins at python.org Thu Aug 24 02:41:31 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Thu, 24 Aug 2006 02:41:31 +0200 (CEST) Subject: [Python-3000-checkins] r51533 - in python/branches/p3yk: Include/object.h Lib/StringIO.py Lib/UserDict.py Lib/UserString.py Lib/ctypes/test/test_simplesubclasses.py Lib/decimal.py Lib/distutils/version.py Lib/doctest.py Lib/optparse.py Lib/plat-mac/plistlib.py Lib/pprint.py Lib/sqlite3/test/types.py Lib/test/mapping_tests.py Lib/test/output/test_class Lib/test/pickletester.py Lib/test/test_bisect.py Lib/test/test_buffer.py Lib/test/test_builtin.py Lib/test/test_calendar.py Lib/test/test_cgi.py Lib/test/test_class.py Lib/test/test_compare.py Lib/test/test_copy.py Lib/test/test_decimal.py Lib/test/test_descr.py Lib/test/test_descrtut.py Lib/test/test_dict.py Lib/test/test_grammar.py Lib/test/test_heapq.py Lib/test/test_itertools.py Lib/test/test_mutants.py Lib/test/test_operations.py Lib/test/test_set.py Lib/test/test_sets.py Lib/test/test_slice.py Lib/test/test_sort.py Lib/test/test_support.py Lib/test/test_types.py Lib/test/test_userdict.py Lib/test/test_weakref.py Lib/uuid.py Lib/xmlrpclib.py Modules/threadmodule.c Objects/bufferobject.c Objects/cellobject.c Objects/classobject.c Objects/codeobject.c Objects/dictobject.c Objects/intobject.c Objects/listobject.c Objects/longobject.c Objects/methodobject.c Objects/object.c Objects/sliceobject.c Objects/typeobject.c Objects/weakrefobject.c Python/bltinmodule.c Message-ID: <20060824004131.1C0621E4005@bag.python.org> Author: guido.van.rossum Date: Thu Aug 24 02:41:19 2006 New Revision: 51533 Added: python/branches/p3yk/Lib/test/test_buffer.py (contents, props changed) Modified: python/branches/p3yk/Include/object.h python/branches/p3yk/Lib/StringIO.py python/branches/p3yk/Lib/UserDict.py python/branches/p3yk/Lib/UserString.py python/branches/p3yk/Lib/ctypes/test/test_simplesubclasses.py python/branches/p3yk/Lib/decimal.py python/branches/p3yk/Lib/distutils/version.py python/branches/p3yk/Lib/doctest.py python/branches/p3yk/Lib/optparse.py python/branches/p3yk/Lib/plat-mac/plistlib.py python/branches/p3yk/Lib/pprint.py python/branches/p3yk/Lib/sqlite3/test/types.py python/branches/p3yk/Lib/test/mapping_tests.py python/branches/p3yk/Lib/test/output/test_class python/branches/p3yk/Lib/test/pickletester.py python/branches/p3yk/Lib/test/test_bisect.py python/branches/p3yk/Lib/test/test_builtin.py python/branches/p3yk/Lib/test/test_calendar.py python/branches/p3yk/Lib/test/test_cgi.py python/branches/p3yk/Lib/test/test_class.py python/branches/p3yk/Lib/test/test_compare.py python/branches/p3yk/Lib/test/test_copy.py python/branches/p3yk/Lib/test/test_decimal.py python/branches/p3yk/Lib/test/test_descr.py python/branches/p3yk/Lib/test/test_descrtut.py python/branches/p3yk/Lib/test/test_dict.py python/branches/p3yk/Lib/test/test_grammar.py python/branches/p3yk/Lib/test/test_heapq.py python/branches/p3yk/Lib/test/test_itertools.py python/branches/p3yk/Lib/test/test_mutants.py python/branches/p3yk/Lib/test/test_operations.py python/branches/p3yk/Lib/test/test_set.py python/branches/p3yk/Lib/test/test_sets.py python/branches/p3yk/Lib/test/test_slice.py python/branches/p3yk/Lib/test/test_sort.py python/branches/p3yk/Lib/test/test_support.py python/branches/p3yk/Lib/test/test_types.py python/branches/p3yk/Lib/test/test_userdict.py python/branches/p3yk/Lib/test/test_weakref.py python/branches/p3yk/Lib/uuid.py python/branches/p3yk/Lib/xmlrpclib.py python/branches/p3yk/Modules/threadmodule.c python/branches/p3yk/Objects/bufferobject.c python/branches/p3yk/Objects/cellobject.c python/branches/p3yk/Objects/classobject.c python/branches/p3yk/Objects/codeobject.c python/branches/p3yk/Objects/dictobject.c python/branches/p3yk/Objects/intobject.c python/branches/p3yk/Objects/listobject.c python/branches/p3yk/Objects/longobject.c python/branches/p3yk/Objects/methodobject.c python/branches/p3yk/Objects/object.c python/branches/p3yk/Objects/sliceobject.c python/branches/p3yk/Objects/typeobject.c python/branches/p3yk/Objects/weakrefobject.c python/branches/p3yk/Python/bltinmodule.c Log: Restructure comparison dramatically. There is no longer a default *ordering* between objects; there is only a default equality test (defined by an object being equal to itself only). Read the comment in object.c. The current implementation never uses a three-way comparison to compute a rich comparison, but it does use a rich comparison to compute a three-way comparison. I'm not quite done ripping out all the calls to PyObject_Compare/Cmp, or replacing tp_compare implementations with tp_richcompare implementations; but much of that has happened (to make most unit tests pass). The following tests still fail, because I need help deciding or understanding: test_codeop -- depends on comparing code objects test_datetime -- need Tim Peters' opinion test_marshal -- depends on comparing code objects test_mutants -- need help understanding it The problem with test_codeop and test_marshal is this: these tests compare two different code objects and expect them to be equal. Is that still a feature we'd like to support? I've temporarily removed the comparison and hash code from code objects, so they use the default (equality by pointer only) comparison. For the other two tests, run them to see for yourself. (There may be more failing test with "-u all".) A general problem with getting lots of these tests to pass is the reality that for object types that have a natural total ordering, implementing __cmp__ is much more convenient than implementing __eq__, __ne__, __lt__, and so on. Should we go back to allowing __cmp__ to provide a total ordering? Should we provide some other way to implement rich comparison with a single method override? Alex proposed a __key__() method; I've considered a __richcmp__() method. Or perhaps __cmp__() just shouldn't be killed off... Modified: python/branches/p3yk/Include/object.h ============================================================================== --- python/branches/p3yk/Include/object.h (original) +++ python/branches/p3yk/Include/object.h Thu Aug 24 02:41:19 2006 @@ -379,6 +379,7 @@ PyAPI_FUNC(int) PyObject_Compare(PyObject *, PyObject *); PyAPI_FUNC(PyObject *) PyObject_RichCompare(PyObject *, PyObject *, int); PyAPI_FUNC(int) PyObject_RichCompareBool(PyObject *, PyObject *, int); +PyAPI_FUNC(PyObject *) Py_CmpToRich(int op, int cmp); PyAPI_FUNC(PyObject *) PyObject_GetAttrString(PyObject *, const char *); PyAPI_FUNC(int) PyObject_SetAttrString(PyObject *, const char *, PyObject *); PyAPI_FUNC(int) PyObject_HasAttrString(PyObject *, const char *); Modified: python/branches/p3yk/Lib/StringIO.py ============================================================================== --- python/branches/p3yk/Lib/StringIO.py (original) +++ python/branches/p3yk/Lib/StringIO.py Thu Aug 24 02:41:19 2006 @@ -116,7 +116,7 @@ _complain_ifclosed(self.closed) return self.pos - def read(self, n = -1): + def read(self, n=None): """Read at most size bytes from the file (less if the read hits EOF before obtaining size bytes). @@ -128,6 +128,8 @@ if self.buflist: self.buf += ''.join(self.buflist) self.buflist = [] + if n is None: + n = -1 if n < 0: newpos = self.len else: Modified: python/branches/p3yk/Lib/UserDict.py ============================================================================== --- python/branches/p3yk/Lib/UserDict.py (original) +++ python/branches/p3yk/Lib/UserDict.py Thu Aug 24 02:41:19 2006 @@ -8,11 +8,16 @@ if len(kwargs): self.update(kwargs) def __repr__(self): return repr(self.data) - def __cmp__(self, dict): + def __eq__(self, dict): if isinstance(dict, UserDict): - return cmp(self.data, dict.data) + return self.data == dict.data else: - return cmp(self.data, dict) + return self.data == dict + def __ne__(self, dict): + if isinstance(dict, UserDict): + return self.data != dict.data + else: + return self.data != dict def __len__(self): return len(self.data) def __getitem__(self, key): if key in self.data: @@ -162,11 +167,13 @@ return default def __repr__(self): return repr(dict(self.iteritems())) - def __cmp__(self, other): - if other is None: - return 1 + def __eq__(self, other): + if isinstance(other, DictMixin): + other = dict(other.iteritems()) + return dict(self.iteritems()) == other + def __ne__(self, other): if isinstance(other, DictMixin): other = dict(other.iteritems()) - return cmp(dict(self.iteritems()), other) + return dict(self.iteritems()) != other def __len__(self): return len(self.keys()) Modified: python/branches/p3yk/Lib/UserString.py ============================================================================== --- python/branches/p3yk/Lib/UserString.py (original) +++ python/branches/p3yk/Lib/UserString.py Thu Aug 24 02:41:19 2006 @@ -25,11 +25,37 @@ def __complex__(self): return complex(self.data) def __hash__(self): return hash(self.data) - def __cmp__(self, string): + def __eq__(self, string): if isinstance(string, UserString): - return cmp(self.data, string.data) + return self.data == string.data else: - return cmp(self.data, string) + return self.data == string + def __ne__(self, string): + if isinstance(string, UserString): + return self.data != string.data + else: + return self.data != string + def __lt__(self, string): + if isinstance(string, UserString): + return self.data < string.data + else: + return self.data < string + def __le__(self, string): + if isinstance(string, UserString): + return self.data <= string.data + else: + return self.data <= string + def __gt__(self, string): + if isinstance(string, UserString): + return self.data > string.data + else: + return self.data > string + def __ge__(self, string): + if isinstance(string, UserString): + return self.data >= string.data + else: + return self.data >= string + def __contains__(self, char): return char in self.data Modified: python/branches/p3yk/Lib/ctypes/test/test_simplesubclasses.py ============================================================================== --- python/branches/p3yk/Lib/ctypes/test/test_simplesubclasses.py (original) +++ python/branches/p3yk/Lib/ctypes/test/test_simplesubclasses.py Thu Aug 24 02:41:19 2006 @@ -2,10 +2,10 @@ from ctypes import * class MyInt(c_int): - def __cmp__(self, other): + def __eq__(self, other): if type(other) != MyInt: - return -1 - return cmp(self.value, other.value) + return NotImplementedError + return self.value == other.value class Test(unittest.TestCase): Modified: python/branches/p3yk/Lib/decimal.py ============================================================================== --- python/branches/p3yk/Lib/decimal.py (original) +++ python/branches/p3yk/Lib/decimal.py Thu Aug 24 02:41:19 2006 @@ -706,6 +706,26 @@ return NotImplemented return self.__cmp__(other) != 0 + def __lt__(self, other): + if not isinstance(other, (Decimal, int, long)): + return NotImplemented + return self.__cmp__(other) < 0 + + def __le__(self, other): + if not isinstance(other, (Decimal, int, long)): + return NotImplemented + return self.__cmp__(other) <= 0 + + def __gt__(self, other): + if not isinstance(other, (Decimal, int, long)): + return NotImplemented + return self.__cmp__(other) > 0 + + def __ge__(self, other): + if not isinstance(other, (Decimal, int, long)): + return NotImplemented + return self.__cmp__(other) >= 0 + def compare(self, other, context=None): """Compares one to another. @@ -1894,6 +1914,7 @@ ans = self._check_nans(context=context) if ans: return ans + return self if self._exp >= 0: return self if context is None: Modified: python/branches/p3yk/Lib/distutils/version.py ============================================================================== --- python/branches/p3yk/Lib/distutils/version.py (original) +++ python/branches/p3yk/Lib/distutils/version.py Thu Aug 24 02:41:19 2006 @@ -32,7 +32,8 @@ class Version: """Abstract base class for version numbering classes. Just provides constructor (__init__) and reproducer (__repr__), because those - seem to be the same for all version numbering classes. + seem to be the same for all version numbering classes; and route + rich comparisons to __cmp__. """ def __init__ (self, vstring=None): @@ -42,6 +43,42 @@ def __repr__ (self): return "%s ('%s')" % (self.__class__.__name__, str(self)) + def __eq__(self, other): + c = self.__cmp__(other) + if c is NotImplemented: + return c + return c == 0 + + def __ne__(self, other): + c = self.__cmp__(other) + if c is NotImplemented: + return c + return c != 0 + + def __lt__(self, other): + c = self.__cmp__(other) + if c is NotImplemented: + return c + return c < 0 + + def __le__(self, other): + c = self.__cmp__(other) + if c is NotImplemented: + return c + return c <= 0 + + def __gt__(self, other): + c = self.__cmp__(other) + if c is NotImplemented: + return c + return c > 0 + + def __ge__(self, other): + c = self.__cmp__(other) + if c is NotImplemented: + return c + return c >= 0 + # Interface for version-number classes -- must be implemented # by the following classes (the concrete ones -- Version should Modified: python/branches/p3yk/Lib/doctest.py ============================================================================== --- python/branches/p3yk/Lib/doctest.py (original) +++ python/branches/p3yk/Lib/doctest.py Thu Aug 24 02:41:19 2006 @@ -469,11 +469,12 @@ # This lets us sort tests by name: - def __cmp__(self, other): + def __lt__(self, other): if not isinstance(other, DocTest): - return -1 - return cmp((self.name, self.filename, self.lineno, id(self)), - (other.name, other.filename, other.lineno, id(other))) + return NotImplemented + return ((self.name, self.filename, self.lineno, id(self)) + < + (other.name, other.filename, other.lineno, id(other))) ###################################################################### ## 3. DocTestParser Modified: python/branches/p3yk/Lib/optparse.py ============================================================================== --- python/branches/p3yk/Lib/optparse.py (original) +++ python/branches/p3yk/Lib/optparse.py Thu Aug 24 02:41:19 2006 @@ -838,13 +838,13 @@ __repr__ = _repr - def __cmp__(self, other): + def __eq__(self, other): if isinstance(other, Values): - return cmp(self.__dict__, other.__dict__) + return self.__dict__ == other.__dict__ elif isinstance(other, types.DictType): - return cmp(self.__dict__, other) + return self.__dict__ == other else: - return -1 + return NotImplemented def _update_careful(self, dict): """ Modified: python/branches/p3yk/Lib/plat-mac/plistlib.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/plistlib.py (original) +++ python/branches/p3yk/Lib/plat-mac/plistlib.py Thu Aug 24 02:41:19 2006 @@ -374,13 +374,13 @@ def asBase64(self, maxlinelength=76): return _encodeBase64(self.data, maxlinelength) - def __cmp__(self, other): + def __eq__(self, other): if isinstance(other, self.__class__): - return cmp(self.data, other.data) + return self.data == other.data elif isinstance(other, str): - return cmp(self.data, other) + return self.data == other else: - return cmp(id(self), id(other)) + return id(self) == id(other) def __repr__(self): return "%s(%s)" % (self.__class__.__name__, repr(self.data)) Modified: python/branches/p3yk/Lib/pprint.py ============================================================================== --- python/branches/p3yk/Lib/pprint.py (original) +++ python/branches/p3yk/Lib/pprint.py Thu Aug 24 02:41:19 2006 @@ -246,7 +246,12 @@ append = components.append level += 1 saferepr = _safe_repr - for k, v in sorted(object.items()): + items = object.items() + try: + items = sorted(items) + except TypeError: + items = sorted(items, key=lambda (k, v): (str(type(k)), k, v)) + for k, v in items: krepr, kreadable, krecur = saferepr(k, context, maxlevels, level) vrepr, vreadable, vrecur = saferepr(v, context, maxlevels, level) append("%s: %s" % (krepr, vrepr)) Modified: python/branches/p3yk/Lib/sqlite3/test/types.py ============================================================================== --- python/branches/p3yk/Lib/sqlite3/test/types.py (original) +++ python/branches/p3yk/Lib/sqlite3/test/types.py Thu Aug 24 02:41:19 2006 @@ -86,6 +86,12 @@ else: return 1 + def __eq__(self, other): + c = self.__cmp__(other) + if c is NotImplemented: + return c + return c == 0 + def __conform__(self, protocol): if protocol is sqlite.PrepareProtocol: return self.val Modified: python/branches/p3yk/Lib/test/mapping_tests.py ============================================================================== --- python/branches/p3yk/Lib/test/mapping_tests.py (original) +++ python/branches/p3yk/Lib/test/mapping_tests.py Thu Aug 24 02:41:19 2006 @@ -60,10 +60,10 @@ for k in self.other: self.failIf(k in d) #cmp - self.assertEqual(cmp(p,p), 0) - self.assertEqual(cmp(d,d), 0) - self.assertEqual(cmp(p,d), -1) - self.assertEqual(cmp(d,p), 1) + self.assertEqual(p, p) + self.assertEqual(d, d) + self.assertNotEqual(p, d) + self.assertNotEqual(d, p) #__non__zero__ if p: self.fail("Empty mapping must compare to False") if not d: self.fail("Full mapping must compare to True") @@ -623,9 +623,10 @@ d = self._full_mapping({1: BadRepr()}) self.assertRaises(Exc, repr, d) - def test_le(self): - self.assert_(not (self._empty_mapping() < self._empty_mapping())) - self.assert_(not (self._full_mapping({1: 2}) < self._full_mapping({1L: 2L}))) + def test_eq(self): + self.assertEqual(self._empty_mapping(), self._empty_mapping()) + self.assertEqual(self._full_mapping({1: 2}), + self._full_mapping({1L: 2L})) class Exc(Exception): pass @@ -633,16 +634,12 @@ def __eq__(self, other): raise Exc() def __hash__(self): - return 42 + return 1 d1 = self._full_mapping({BadCmp(): 1}) d2 = self._full_mapping({1: 1}) - try: - d1 < d2 - except Exc: - pass - else: - self.fail("< didn't raise Exc") + self.assertRaises(Exc, lambda: BadCmp()==1) + self.assertRaises(Exc, lambda: d1==d2) def test_setdefault(self): TestMappingProtocol.test_setdefault(self) Modified: python/branches/p3yk/Lib/test/output/test_class ============================================================================== --- python/branches/p3yk/Lib/test/output/test_class (original) +++ python/branches/p3yk/Lib/test/output/test_class Thu Aug 24 02:41:19 2006 @@ -51,16 +51,16 @@ __hash__: () __repr__: () __str__: () -__cmp__: (1,) -__cmp__: (1,) -__cmp__: (1,) -__cmp__: (1,) -__cmp__: (1,) -__cmp__: (1,) -__cmp__: (1,) -__cmp__: (1,) -__cmp__: (1,) -__cmp__: (1,) +__eq__: (1,) +__lt__: (1,) +__gt__: (1,) +__ne__: (1,) +__ne__: (1,) +__eq__: (1,) +__gt__: (1,) +__lt__: (1,) +__ne__: (1,) +__ne__: (1,) __del__: () __getattr__: ('spam',) __setattr__: ('eggs', 'spam, spam, spam and ham') Modified: python/branches/p3yk/Lib/test/pickletester.py ============================================================================== --- python/branches/p3yk/Lib/test/pickletester.py (original) +++ python/branches/p3yk/Lib/test/pickletester.py Thu Aug 24 02:41:19 2006 @@ -65,8 +65,8 @@ copy_reg.add_extension(pair[0], pair[1], code) class C: - def __cmp__(self, other): - return cmp(self.__dict__, other.__dict__) + def __eq__(self, other): + return self.__dict__ == other.__dict__ import __main__ __main__.C = C Modified: python/branches/p3yk/Lib/test/test_bisect.py ============================================================================== --- python/branches/p3yk/Lib/test/test_bisect.py (original) +++ python/branches/p3yk/Lib/test/test_bisect.py Thu Aug 24 02:41:19 2006 @@ -174,8 +174,13 @@ class CmpErr: "Dummy element that always raises an error during comparison" - def __cmp__(self, other): + def __lt__(self, other): raise ZeroDivisionError + __gt__ = __lt__ + __le__ = __lt__ + __ge__ = __lt__ + __eq__ = __lt__ + __ne__ = __lt__ class TestErrorHandling(unittest.TestCase): Added: python/branches/p3yk/Lib/test/test_buffer.py ============================================================================== --- (empty file) +++ python/branches/p3yk/Lib/test/test_buffer.py Thu Aug 24 02:41:19 2006 @@ -0,0 +1,44 @@ +"""Unit tests for buffer objects. + +For now, we just test (the brand new) rich comparison. + +""" + +import unittest +from test import test_support + +class BufferTests(unittest.TestCase): + + def test_comparison(self): + a = buffer("a.b.c") + b = buffer("a.b" + ".c") + self.assert_(a == b) + self.assert_(a <= b) + self.assert_(a >= b) + self.assert_(a == "a.b.c") + self.assert_(a <= "a.b.c") + self.assert_(a >= "a.b.c") + b = buffer("a.b.c.d") + self.assert_(a != b) + self.assert_(a <= b) + self.assert_(a < b) + self.assert_(a != "a.b.c.d") + self.assert_(a < "a.b.c.d") + self.assert_(a <= "a.b.c.d") + b = buffer("a.b") + self.assert_(a != b) + self.assert_(a >= b) + self.assert_(a > b) + self.assert_(a != "a.b") + self.assert_(a > "a.b") + self.assert_(a >= "a.b") + b = object() + self.assert_(a != b) + self.failIf(a == b) + self.assertRaises(TypeError, lambda: a < b) + +def test_main(): + test_support.run_unittest(BufferTests) + +if __name__ == "__main__": + test_main() Modified: python/branches/p3yk/Lib/test/test_builtin.py ============================================================================== --- python/branches/p3yk/Lib/test/test_builtin.py (original) +++ python/branches/p3yk/Lib/test/test_builtin.py Thu Aug 24 02:41:19 2006 @@ -179,7 +179,8 @@ self.assertRaises(ValueError, chr, 256) self.assertRaises(TypeError, chr) - def test_cmp(self): + def XXX_test_cmp(self): + # cmp() is no longer supported self.assertEqual(cmp(-1, 1), -1) self.assertEqual(cmp(1, -1), 1) self.assertEqual(cmp(1, 1), 0) @@ -1132,8 +1133,14 @@ map(None, Squares(3), Squares(2)), [(0,0), (1,1), (4,None)] ) + def Max(a, b): + if a is None: + return b + if b is None: + return a + return max(a, b) self.assertEqual( - map(max, Squares(3), Squares(2)), + map(Max, Squares(3), Squares(2)), [0, 1, 4] ) self.assertRaises(TypeError, map) @@ -1201,7 +1208,7 @@ class BadNumber: def __cmp__(self, other): raise ValueError - self.assertRaises(ValueError, min, (42, BadNumber())) + self.assertRaises(TypeError, min, (42, BadNumber())) for stmt in ( "min(key=int)", # no args @@ -1379,8 +1386,11 @@ self.assertRaises(ValueError, range, a, a + 1, long(0)) class badzero(int): - def __cmp__(self, other): + def __eq__(self, other): raise RuntimeError + __ne__ = __lt__ = __gt__ = __le__ = __ge__ = __eq__ + + # XXX This won't (but should!) raise RuntimeError if a is an int... self.assertRaises(RuntimeError, range, a, a + 1, badzero(1)) # Reject floats when it would require PyLongs to represent. @@ -1594,7 +1604,7 @@ data.reverse() random.shuffle(copy) - self.assertEqual(data, sorted(copy, cmp=lambda x, y: cmp(y,x))) + self.assertEqual(data, sorted(copy, cmp=lambda x, y: (x < y) - (x > y))) self.assertNotEqual(data, copy) random.shuffle(copy) self.assertEqual(data, sorted(copy, key=lambda x: -x)) Modified: python/branches/p3yk/Lib/test/test_calendar.py ============================================================================== --- python/branches/p3yk/Lib/test/test_calendar.py (original) +++ python/branches/p3yk/Lib/test/test_calendar.py Thu Aug 24 02:41:19 2006 @@ -212,7 +212,7 @@ self.assertEqual(calendar.isleap(2003), 0) def test_setfirstweekday(self): - self.assertRaises(ValueError, calendar.setfirstweekday, 'flabber') + self.assertRaises(TypeError, calendar.setfirstweekday, 'flabber') self.assertRaises(ValueError, calendar.setfirstweekday, -1) self.assertRaises(ValueError, calendar.setfirstweekday, 200) orig = calendar.firstweekday() Modified: python/branches/p3yk/Lib/test/test_cgi.py ============================================================================== --- python/branches/p3yk/Lib/test/test_cgi.py (original) +++ python/branches/p3yk/Lib/test/test_cgi.py Thu Aug 24 02:41:19 2006 @@ -25,13 +25,11 @@ def __str__(self): return str(self.err) - def __cmp__(self, anExc): + def __eq__(self, anExc): if not isinstance(anExc, Exception): - return -1 - x = cmp(self.err.__class__, anExc.__class__) - if x != 0: - return x - return cmp(self.err.args, anExc.args) + return NotImplemented + return (self.err.__class__ == anExc.__class__ and + self.err.args == anExc.args) def __getattr__(self, attr): return getattr(self.err, attr) @@ -118,10 +116,10 @@ }) ] -def norm(list): - if type(list) == type([]): - list.sort() - return list +def norm(seq): + if isinstance(seq, list): + seq.sort(key=repr) + return seq def first_elts(list): return map(lambda x:x[0], list) Modified: python/branches/p3yk/Lib/test/test_class.py ============================================================================== --- python/branches/p3yk/Lib/test/test_class.py (original) +++ python/branches/p3yk/Lib/test/test_class.py Thu Aug 24 02:41:19 2006 @@ -100,6 +100,30 @@ print "__cmp__:", args return 0 + def __eq__(self, *args): + print "__eq__:", args + return True + + def __ne__(self, *args): + print "__ne__:", args + return False + + def __lt__(self, *args): + print "__lt__:", args + return False + + def __le__(self, *args): + print "__le__:", args + return True + + def __gt__(self, *args): + print "__gt__:", args + return False + + def __ge__(self, *args): + print "__ge__:", args + return True + def __del__(self, *args): print "__del__:", args Modified: python/branches/p3yk/Lib/test/test_compare.py ============================================================================== --- python/branches/p3yk/Lib/test/test_compare.py (original) +++ python/branches/p3yk/Lib/test/test_compare.py Thu Aug 24 02:41:19 2006 @@ -13,8 +13,8 @@ def __repr__(self): return '' % self.arg - def __cmp__(self, other): - return cmp(self.arg, other) + def __eq__(self, other): + return self.arg == other class ComparisonTest(unittest.TestCase): set1 = [2, 2.0, 2L, 2+0j, Cmp(2.0)] @@ -36,7 +36,7 @@ L.insert(len(L)//2, Empty()) for a in L: for b in L: - self.assertEqual(cmp(a, b), cmp(id(a), id(b)), + self.assertEqual(a == b, id(a) == id(b), 'a=%r, b=%r' % (a, b)) def test_main(): Modified: python/branches/p3yk/Lib/test/test_copy.py ============================================================================== --- python/branches/p3yk/Lib/test/test_copy.py (original) +++ python/branches/p3yk/Lib/test/test_copy.py Thu Aug 24 02:41:19 2006 @@ -104,8 +104,8 @@ class C: def __init__(self, foo): self.foo = foo - def __cmp__(self, other): - return cmp(self.foo, other.foo) + def __eq__(self, other): + return self.foo == other.foo x = C(42) self.assertEqual(copy.copy(x), x) @@ -115,8 +115,8 @@ self.foo = foo def __copy__(self): return C(self.foo) - def __cmp__(self, other): - return cmp(self.foo, other.foo) + def __eq__(self, other): + return self.foo == other.foo x = C(42) self.assertEqual(copy.copy(x), x) @@ -126,8 +126,8 @@ self.foo = foo def __getinitargs__(self): return (self.foo,) - def __cmp__(self, other): - return cmp(self.foo, other.foo) + def __eq__(self, other): + return self.foo == other.foo x = C(42) self.assertEqual(copy.copy(x), x) @@ -137,8 +137,8 @@ self.foo = foo def __getstate__(self): return {"foo": self.foo} - def __cmp__(self, other): - return cmp(self.foo, other.foo) + def __eq__(self, other): + return self.foo == other.foo x = C(42) self.assertEqual(copy.copy(x), x) @@ -148,8 +148,8 @@ self.foo = foo def __setstate__(self, state): self.foo = state["foo"] - def __cmp__(self, other): - return cmp(self.foo, other.foo) + def __eq__(self, other): + return self.foo == other.foo x = C(42) self.assertEqual(copy.copy(x), x) @@ -161,8 +161,8 @@ return self.foo def __setstate__(self, state): self.foo = state - def __cmp__(self, other): - return cmp(self.foo, other.foo) + def __eq__(self, other): + return self.foo == other.foo x = C(42) self.assertEqual(copy.copy(x), x) @@ -304,7 +304,7 @@ x = {} x['foo'] = x y = copy.deepcopy(x) - self.assertRaises(RuntimeError, cmp, y, x) + self.assertRaises(TypeError, cmp, y, x) self.assert_(y is not x) self.assert_(y['foo'] is y) self.assertEqual(len(y), 1) @@ -319,8 +319,8 @@ class C: def __init__(self, foo): self.foo = foo - def __cmp__(self, other): - return cmp(self.foo, other.foo) + def __eq__(self, other): + return self.foo == other.foo x = C([42]) y = copy.deepcopy(x) self.assertEqual(y, x) @@ -332,8 +332,8 @@ self.foo = foo def __deepcopy__(self, memo): return C(copy.deepcopy(self.foo, memo)) - def __cmp__(self, other): - return cmp(self.foo, other.foo) + def __eq__(self, other): + return self.foo == other.foo x = C([42]) y = copy.deepcopy(x) self.assertEqual(y, x) @@ -346,8 +346,8 @@ self.foo = foo def __getinitargs__(self): return (self.foo,) - def __cmp__(self, other): - return cmp(self.foo, other.foo) + def __eq__(self, other): + return self.foo == other.foo x = C([42]) y = copy.deepcopy(x) self.assertEqual(y, x) @@ -360,8 +360,8 @@ self.foo = foo def __getstate__(self): return {"foo": self.foo} - def __cmp__(self, other): - return cmp(self.foo, other.foo) + def __eq__(self, other): + return self.foo == other.foo x = C([42]) y = copy.deepcopy(x) self.assertEqual(y, x) @@ -374,8 +374,8 @@ self.foo = foo def __setstate__(self, state): self.foo = state["foo"] - def __cmp__(self, other): - return cmp(self.foo, other.foo) + def __eq__(self, other): + return self.foo == other.foo x = C([42]) y = copy.deepcopy(x) self.assertEqual(y, x) @@ -390,8 +390,8 @@ return self.foo def __setstate__(self, state): self.foo = state - def __cmp__(self, other): - return cmp(self.foo, other.foo) + def __eq__(self, other): + return self.foo == other.foo x = C([42]) y = copy.deepcopy(x) self.assertEqual(y, x) @@ -434,8 +434,8 @@ class C(object): def __reduce__(self): return (C, (), self.__dict__) - def __cmp__(self, other): - return cmp(self.__dict__, other.__dict__) + def __eq__(self, other): + return self.__dict__ == other.__dict__ x = C() x.foo = [42] y = copy.copy(x) @@ -450,8 +450,8 @@ return (C, (), self.__dict__) def __setstate__(self, state): self.__dict__.update(state) - def __cmp__(self, other): - return cmp(self.__dict__, other.__dict__) + def __eq__(self, other): + return self.__dict__ == other.__dict__ x = C() x.foo = [42] y = copy.copy(x) @@ -475,9 +475,9 @@ class C(list): def __reduce__(self): return (C, (), self.__dict__, iter(self)) - def __cmp__(self, other): - return (cmp(list(self), list(other)) or - cmp(self.__dict__, other.__dict__)) + def __eq__(self, other): + return (list(self) == list(other) and + self.__dict__ == other.__dict__) x = C([[1, 2], 3]) y = copy.copy(x) self.assertEqual(x, y) @@ -492,9 +492,9 @@ class C(dict): def __reduce__(self): return (C, (), self.__dict__, None, self.iteritems()) - def __cmp__(self, other): - return (cmp(dict(self), list(dict)) or - cmp(self.__dict__, other.__dict__)) + def __eq__(self, other): + return (dict(self) == dict(other) and + self.__dict__ == other.__dict__) x = C([("foo", [1, 2]), ("bar", 3)]) y = copy.copy(x) self.assertEqual(x, y) Modified: python/branches/p3yk/Lib/test/test_decimal.py ============================================================================== --- python/branches/p3yk/Lib/test/test_decimal.py (original) +++ python/branches/p3yk/Lib/test/test_decimal.py Thu Aug 24 02:41:19 2006 @@ -276,8 +276,8 @@ myexceptions = self.getexceptions() self.context.clear_flags() - myexceptions.sort() - theirexceptions.sort() + myexceptions.sort(key=repr) + theirexceptions.sort(key=repr) self.assertEqual(result, ans, 'Incorrect answer for ' + s + ' -- got ' + result) Modified: python/branches/p3yk/Lib/test/test_descr.py ============================================================================== --- python/branches/p3yk/Lib/test/test_descr.py (original) +++ python/branches/p3yk/Lib/test/test_descr.py Thu Aug 24 02:41:19 2006 @@ -151,7 +151,7 @@ def dicts(): if verbose: print "Testing dict operations..." - testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__") + ##testbinop({1:2}, {2:1}, -1, "cmp(a,b)", "__cmp__") testbinop({1:2,3:4}, 1, 1, "b in a", "__contains__") testbinop({1:2,3:4}, 2, 0, "b in a", "__contains__") testbinop({1:2,3:4}, 1, 2, "a[b]", "__getitem__") @@ -523,7 +523,7 @@ # This is an ugly hack: copy._deepcopy_dispatch[spam.spamdict] = spamdict - testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__") + ##testbinop(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)", "__cmp__") testbinop(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__") testbinop(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__") testbinop(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__") @@ -1641,7 +1641,7 @@ verify(id(c1) != id(c2)) hash(c1) hash(c2) - vereq(cmp(c1, c2), cmp(id(c1), id(c2))) + ##vereq(cmp(c1, c2), cmp(id(c1), id(c2))) vereq(c1, c1) verify(c1 != c2) verify(not c1 != c1) @@ -1665,7 +1665,7 @@ verify(id(d1) != id(d2)) hash(d1) hash(d2) - vereq(cmp(d1, d2), cmp(id(d1), id(d2))) + ##vereq(cmp(d1, d2), cmp(id(d1), id(d2))) vereq(d1, d1) verify(d1 != d2) verify(not d1 != d1) @@ -1758,21 +1758,21 @@ for i in range(10): verify(i in p10) verify(10 not in p10) - # Safety test for __cmp__ - def unsafecmp(a, b): - try: - a.__class__.__cmp__(a, b) - except TypeError: - pass - else: - raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % ( - a.__class__, a, b) - unsafecmp(u"123", "123") - unsafecmp("123", u"123") - unsafecmp(1, 1.0) - unsafecmp(1.0, 1) - unsafecmp(1, 1L) - unsafecmp(1L, 1) +## # Safety test for __cmp__ +## def unsafecmp(a, b): +## try: +## a.__class__.__cmp__(a, b) +## except TypeError: +## pass +## else: +## raise TestFailed, "shouldn't allow %s.__cmp__(%r, %r)" % ( +## a.__class__, a, b) +## unsafecmp(u"123", "123") +## unsafecmp("123", u"123") +## unsafecmp(1, 1.0) +## unsafecmp(1.0, 1) +## unsafecmp(1, 1L) +## unsafecmp(1L, 1) class Letter(str): def __new__(cls, letter): @@ -2469,12 +2469,43 @@ class C(base): def __init__(self, value): self.value = int(value) - def __cmp__(self, other): + def __eq__(self, other): + if isinstance(other, C): + return self.value == other.value + if isinstance(other, int) or isinstance(other, long): + return self.value == other + return NotImplemented + def __ne__(self, other): + if isinstance(other, C): + return self.value != other.value + if isinstance(other, int) or isinstance(other, long): + return self.value != other + return NotImplemented + def __lt__(self, other): + if isinstance(other, C): + return self.value < other.value + if isinstance(other, int) or isinstance(other, long): + return self.value < other + return NotImplemented + def __le__(self, other): + if isinstance(other, C): + return self.value <= other.value + if isinstance(other, int) or isinstance(other, long): + return self.value <= other + return NotImplemented + def __gt__(self, other): if isinstance(other, C): - return cmp(self.value, other.value) + return self.value > other.value + if isinstance(other, int) or isinstance(other, long): + return self.value > other + return NotImplemented + def __ge__(self, other): + if isinstance(other, C): + return self.value >= other.value if isinstance(other, int) or isinstance(other, long): - return cmp(self.value, other) + return self.value >= other return NotImplemented + c1 = C(1) c2 = C(2) c3 = C(3) @@ -2482,12 +2513,12 @@ c = {1: c1, 2: c2, 3: c3} for x in 1, 2, 3: for y in 1, 2, 3: - verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y)) + ##verify(cmp(c[x], c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y)) for op in "<", "<=", "==", "!=", ">", ">=": verify(eval("c[x] %s c[y]" % op) == eval("x %s y" % op), "x=%d, y=%d" % (x, y)) - verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y)) - verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y)) + ##verify(cmp(c[x], y) == cmp(x, y), "x=%d, y=%d" % (x, y)) + ##verify(cmp(x, c[y]) == cmp(x, y), "x=%d, y=%d" % (x, y)) def rich_comparisons(): if verbose: @@ -3875,6 +3906,8 @@ if verbose: print "Testing method-wrapper objects..." + return # XXX should methods really support __eq__? + l = [] vereq(l.__add__, l.__add__) vereq(l.__add__, [].__add__) Modified: python/branches/p3yk/Lib/test/test_descrtut.py ============================================================================== --- python/branches/p3yk/Lib/test/test_descrtut.py (original) +++ python/branches/p3yk/Lib/test/test_descrtut.py Thu Aug 24 02:41:19 2006 @@ -65,14 +65,11 @@ dictionaries, such as the locals/globals dictionaries for the exec statement or the built-in function eval(): - >>> def sorted(seq): - ... seq.sort() - ... return seq >>> print sorted(a.keys()) [1, 2] >>> exec "x = 3; print x" in a 3 - >>> print sorted(a.keys()) + >>> print sorted(a.keys(), key=lambda x: (str(type(x)), x)) [1, 2, '__builtins__', 'x'] >>> print a['x'] 3 Modified: python/branches/p3yk/Lib/test/test_dict.py ============================================================================== --- python/branches/p3yk/Lib/test/test_dict.py (original) +++ python/branches/p3yk/Lib/test/test_dict.py Thu Aug 24 02:41:19 2006 @@ -5,6 +5,7 @@ class DictTest(unittest.TestCase): + def test_constructor(self): # calling built-in types without argument must return empty self.assertEqual(dict(), {}) @@ -368,9 +369,9 @@ d = {1: BadRepr()} self.assertRaises(Exc, repr, d) - def test_le(self): - self.assert_(not ({} < {})) - self.assert_(not ({1: 2} < {1L: 2L})) + def test_eq(self): + self.assertEqual({}, {}) + self.assertEqual({1: 2}, {1L: 2L}) class Exc(Exception): pass @@ -378,12 +379,12 @@ def __eq__(self, other): raise Exc() def __hash__(self): - return 42 + return 1 d1 = {BadCmp(): 1} d2 = {1: 1} try: - d1 < d2 + d1 == d2 except Exc: pass else: Modified: python/branches/p3yk/Lib/test/test_grammar.py ============================================================================== --- python/branches/p3yk/Lib/test/test_grammar.py (original) +++ python/branches/p3yk/Lib/test/test_grammar.py Thu Aug 24 02:41:19 2006 @@ -681,7 +681,7 @@ d[1,2] = 3 d[1,2,3] = 4 L = list(d) -L.sort() +L.sort(key=lambda x: x if isinstance(x, tuple) else ()) print L @@ -741,7 +741,7 @@ print [(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)] def test_in_func(l): - return [None < x < 3 for x in l if x > 2] + return [0 < x < 3 for x in l if x > 2] print test_in_func(nums) Modified: python/branches/p3yk/Lib/test/test_heapq.py ============================================================================== --- python/branches/p3yk/Lib/test/test_heapq.py (original) +++ python/branches/p3yk/Lib/test/test_heapq.py Thu Aug 24 02:41:19 2006 @@ -136,6 +136,7 @@ "Dummy element that always raises an error during comparison" def __cmp__(self, other): raise ZeroDivisionError + __eq__ = __ne__ = __lt__ = __le__ = __gt__ = __ge__ = __cmp__ def R(seqn): 'Regular generator' @@ -253,7 +254,7 @@ def test_iterable_args(self): for f in (nlargest, nsmallest): - for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)): + for s in ("123", "", range(1000), (1, 1.2), xrange(2000,2200,5)): for g in (G, I, Ig, L, R): self.assertEqual(f(2, g(s)), f(2,s)) self.assertEqual(f(2, S(s)), []) Modified: python/branches/p3yk/Lib/test/test_itertools.py ============================================================================== --- python/branches/p3yk/Lib/test/test_itertools.py (original) +++ python/branches/p3yk/Lib/test/test_itertools.py Thu Aug 24 02:41:19 2006 @@ -132,13 +132,13 @@ # __cmp__ failure class DummyCmp: - def __cmp__(self, dst): + def __eq__(self, dst): raise ExpectedError s = [DummyCmp(), DummyCmp(), None] - # __cmp__ failure on outer object + # __eq__ failure on outer object self.assertRaises(ExpectedError, gulp, s, func=id) - # __cmp__ failure on inner object + # __eq__ failure on inner object self.assertRaises(ExpectedError, gulp, s) # keyfunc failure Modified: python/branches/p3yk/Lib/test/test_mutants.py ============================================================================== --- python/branches/p3yk/Lib/test/test_mutants.py (original) +++ python/branches/p3yk/Lib/test/test_mutants.py Thu Aug 24 02:41:19 2006 @@ -27,7 +27,7 @@ # ran it. Indeed, at the start, the driver never got beyond 6 iterations # before the test died. -# The dicts are global to make it easy to mutate tham from within functions. +# The dicts are global to make it easy to mutate them from within functions. dict1 = {} dict2 = {} @@ -93,9 +93,9 @@ def __hash__(self): return self.hashcode - def __cmp__(self, other): + def __eq__(self, other): maybe_mutate() # The point of the test. - return cmp(self.i, other.i) + return self.i == other.i def __repr__(self): return "Horrid(%d)" % self.i @@ -132,7 +132,8 @@ while dict1 and len(dict1) == len(dict2): if verbose: print ".", - c = cmp(dict1, dict2) + c = dict1 == dict2 + XXX # Can't figure out how to make this work if verbose: print Modified: python/branches/p3yk/Lib/test/test_operations.py ============================================================================== --- python/branches/p3yk/Lib/test/test_operations.py (original) +++ python/branches/p3yk/Lib/test/test_operations.py Thu Aug 24 02:41:19 2006 @@ -12,7 +12,7 @@ def __hash__(self): return hash(self.__class__) - def __cmp__(self, other): + def __eq__(self, other): if isinstance(other, self.__class__): print "raising error" raise RuntimeError, "gotcha" @@ -34,7 +34,7 @@ except RuntimeError: print "%s: caught the RuntimeError outside" % (stmt,) else: - print "%s: No exception passed through!" # old CPython behavior + print "%s: No exception passed through!" % (stmt,) # old CPython behavior # Dict resizing bug, found by Jack Jansen in 2.2 CVS development. Modified: python/branches/p3yk/Lib/test/test_set.py ============================================================================== --- python/branches/p3yk/Lib/test/test_set.py (original) +++ python/branches/p3yk/Lib/test/test_set.py Thu Aug 24 02:41:19 2006 @@ -18,7 +18,7 @@ class BadCmp: def __hash__(self): return 1 - def __cmp__(self, other): + def __eq__(self, other): raise RuntimeError class TestJointOps(unittest.TestCase): @@ -781,11 +781,8 @@ a, b = set('a'), set('b') self.assertRaises(TypeError, cmp, a, b) - # You can view this as a buglet: cmp(a, a) does not raise TypeError, - # because __eq__ is tried before __cmp__, and a.__eq__(a) returns True, - # which Python thinks is good enough to synthesize a cmp() result - # without calling __cmp__. - self.assertEqual(cmp(a, a), 0) + # In py3k, this works! + self.assertRaises(TypeError, cmp, a, a) self.assertRaises(TypeError, cmp, a, 12) self.assertRaises(TypeError, cmp, "abc", a) @@ -1201,8 +1198,8 @@ def test_copy(self): dup = self.set.copy() - dup_list = list(dup); dup_list.sort() - set_list = list(self.set); set_list.sort() + dup_list = sorted(dup, key=repr) + set_list = sorted(self.set, key=repr) self.assertEqual(len(dup_list), len(set_list)) for i in range(len(dup_list)): self.failUnless(dup_list[i] is set_list[i]) @@ -1210,8 +1207,8 @@ def test_deep_copy(self): dup = copy.deepcopy(self.set) ##print type(dup), repr(dup) - dup_list = list(dup); dup_list.sort() - set_list = list(self.set); set_list.sort() + dup_list = sorted(dup, key=repr) + set_list = sorted(self.set, key=repr) self.assertEqual(len(dup_list), len(set_list)) for i in range(len(dup_list)): self.assertEqual(dup_list[i], set_list[i]) @@ -1374,7 +1371,7 @@ for cons in (set, frozenset): for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)): for g in (G, I, Ig, S, L, R): - self.assertEqual(sorted(cons(g(s))), sorted(g(s))) + self.assertEqual(sorted(cons(g(s)), key=repr), sorted(g(s), key=repr)) self.assertRaises(TypeError, cons , X(s)) self.assertRaises(TypeError, cons , N(s)) self.assertRaises(ZeroDivisionError, cons , E(s)) @@ -1386,7 +1383,7 @@ for g in (G, I, Ig, L, R): expected = meth(data) actual = meth(G(data)) - self.assertEqual(sorted(actual), sorted(expected)) + self.assertEqual(sorted(actual, key=repr), sorted(expected, key=repr)) self.assertRaises(TypeError, meth, X(s)) self.assertRaises(TypeError, meth, N(s)) self.assertRaises(ZeroDivisionError, meth, E(s)) @@ -1400,7 +1397,7 @@ t = s.copy() getattr(s, methname)(list(g(data))) getattr(t, methname)(g(data)) - self.assertEqual(sorted(s), sorted(t)) + self.assertEqual(sorted(s, key=repr), sorted(t, key=repr)) self.assertRaises(TypeError, getattr(set('january'), methname), X(data)) self.assertRaises(TypeError, getattr(set('january'), methname), N(data)) Modified: python/branches/p3yk/Lib/test/test_sets.py ============================================================================== --- python/branches/p3yk/Lib/test/test_sets.py (original) +++ python/branches/p3yk/Lib/test/test_sets.py Thu Aug 24 02:41:19 2006 @@ -234,11 +234,8 @@ a, b = Set('a'), Set('b') self.assertRaises(TypeError, cmp, a, b) - # You can view this as a buglet: cmp(a, a) does not raise TypeError, - # because __eq__ is tried before __cmp__, and a.__eq__(a) returns True, - # which Python thinks is good enough to synthesize a cmp() result - # without calling __cmp__. - self.assertEqual(cmp(a, a), 0) + # In py3k, this works! + self.assertRaises(TypeError, cmp, a, a) self.assertRaises(TypeError, cmp, a, 12) self.assertRaises(TypeError, cmp, "abc", a) @@ -675,8 +672,8 @@ def test_copy(self): dup = self.set.copy() - dup_list = list(dup); dup_list.sort() - set_list = list(self.set); set_list.sort() + dup_list = sorted(dup, key=repr) + set_list = sorted(self.set, key=repr) self.assertEqual(len(dup_list), len(set_list)) for i in range(len(dup_list)): self.failUnless(dup_list[i] is set_list[i]) @@ -684,8 +681,8 @@ def test_deep_copy(self): dup = copy.deepcopy(self.set) ##print type(dup), repr(dup) - dup_list = list(dup); dup_list.sort() - set_list = list(self.set); set_list.sort() + dup_list = sorted(dup, key=repr) + set_list = sorted(self.set, key=repr) self.assertEqual(len(dup_list), len(set_list)) for i in range(len(dup_list)): self.assertEqual(dup_list[i], set_list[i]) Modified: python/branches/p3yk/Lib/test/test_slice.py ============================================================================== --- python/branches/p3yk/Lib/test/test_slice.py (original) +++ python/branches/p3yk/Lib/test/test_slice.py Thu Aug 24 02:41:19 2006 @@ -35,18 +35,18 @@ s1 = slice(BadCmp()) s2 = slice(BadCmp()) - self.assertRaises(Exc, cmp, s1, s2) self.assertEqual(s1, s1) + self.assertRaises(Exc, lambda: s1 == s2) s1 = slice(1, BadCmp()) s2 = slice(1, BadCmp()) self.assertEqual(s1, s1) - self.assertRaises(Exc, cmp, s1, s2) + self.assertRaises(Exc, lambda: s1 == s2) s1 = slice(1, 2, BadCmp()) s2 = slice(1, 2, BadCmp()) self.assertEqual(s1, s1) - self.assertRaises(Exc, cmp, s1, s2) + self.assertRaises(Exc, lambda: s1 == s2) def test_members(self): s = slice(1) Modified: python/branches/p3yk/Lib/test/test_sort.py ============================================================================== --- python/branches/p3yk/Lib/test/test_sort.py (original) +++ python/branches/p3yk/Lib/test/test_sort.py Thu Aug 24 02:41:19 2006 @@ -68,8 +68,8 @@ self.key = key self.index = i - def __cmp__(self, other): - return cmp(self.key, other.key) + def __lt__(self, other): + return self.key < other.key def __repr__(self): return "Stable(%d, %d)" % (self.key, self.index) @@ -225,6 +225,8 @@ def __del__(self): del data[:] data[:] = range(20) + def __lt__(self, other): + return id(self) < id(other) self.assertRaises(ValueError, data.sort, key=SortKiller) def test_key_with_mutating_del_and_exception(self): Modified: python/branches/p3yk/Lib/test/test_support.py ============================================================================== --- python/branches/p3yk/Lib/test/test_support.py (original) +++ python/branches/p3yk/Lib/test/test_support.py Thu Aug 24 02:41:19 2006 @@ -122,8 +122,8 @@ outcome = fcmp(x[i], y[i]) if outcome != 0: return outcome - return cmp(len(x), len(y)) - return cmp(x, y) + return (len(x) > len(y)) - (len(x) < len(y)) + return (x > y) - (x < y) try: unicode Modified: python/branches/p3yk/Lib/test/test_types.py ============================================================================== --- python/branches/p3yk/Lib/test/test_types.py (original) +++ python/branches/p3yk/Lib/test/test_types.py Thu Aug 24 02:41:19 2006 @@ -233,7 +233,6 @@ try: buffer('asdf', -1) except ValueError: pass else: raise TestFailed, "buffer('asdf', -1) should raise ValueError" -cmp(buffer("abc"), buffer("def")) # used to raise a warning: tp_compare didn't return -1, 0, or 1 try: buffer(None) except TypeError: pass Modified: python/branches/p3yk/Lib/test/test_userdict.py ============================================================================== --- python/branches/p3yk/Lib/test/test_userdict.py (original) +++ python/branches/p3yk/Lib/test/test_userdict.py Thu Aug 24 02:41:19 2006 @@ -52,7 +52,7 @@ all = [d0, d1, d2, u, u0, u1, u2, uu, uu0, uu1, uu2] for a in all: for b in all: - self.assertEqual(cmp(a, b), cmp(len(a), len(b))) + self.assertEqual(a == b, len(a) == len(b)) # Test __getitem__ self.assertEqual(u2["one"], 1) Modified: python/branches/p3yk/Lib/test/test_weakref.py ============================================================================== --- python/branches/p3yk/Lib/test/test_weakref.py (original) +++ python/branches/p3yk/Lib/test/test_weakref.py Thu Aug 24 02:41:19 2006 @@ -701,6 +701,12 @@ self.arg = arg def __repr__(self): return "" % self.arg + def __lt__(self, other): + if isinstance(other, Object): + return self.arg < other.arg + return NotImplemented + def __hash__(self): + return hash(self.arg) class MappingTestCase(TestBase): Modified: python/branches/p3yk/Lib/uuid.py ============================================================================== --- python/branches/p3yk/Lib/uuid.py (original) +++ python/branches/p3yk/Lib/uuid.py Thu Aug 24 02:41:19 2006 @@ -177,9 +177,36 @@ int |= version << 76L self.__dict__['int'] = int - def __cmp__(self, other): + def __eq__(self, other): if isinstance(other, UUID): - return cmp(self.int, other.int) + return self.int == other.int + return NotImplemented + + def __ne__(self, other): + if isinstance(other, UUID): + return self.int != other.int + return NotImplemented + + # XXX What's the value of being able to sort UUIDs? + + def __lt__(self, other): + if isinstance(other, UUID): + return self.int < other.int + return NotImplemented + + def __gt__(self, other): + if isinstance(other, UUID): + return self.int > other.int + return NotImplemented + + def __le__(self, other): + if isinstance(other, UUID): + return self.int <= other.int + return NotImplemented + + def __ge__(self, other): + if isinstance(other, UUID): + return self.int >= other.int return NotImplemented def __hash__(self): @@ -488,7 +515,7 @@ # 0x01b21dd213814000 is the number of 100-ns intervals between the # UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00. timestamp = int(nanoseconds/100) + 0x01b21dd213814000L - if timestamp <= _last_timestamp: + if _last_timestamp is not None and timestamp <= _last_timestamp: timestamp = _last_timestamp + 1 _last_timestamp = timestamp if clock_seq is None: Modified: python/branches/p3yk/Lib/xmlrpclib.py ============================================================================== --- python/branches/p3yk/Lib/xmlrpclib.py (original) +++ python/branches/p3yk/Lib/xmlrpclib.py Thu Aug 24 02:41:19 2006 @@ -282,56 +282,9 @@ # @param value A boolean value. Any true value is interpreted as True, # all other values are interpreted as False. -if _bool_is_builtin: - boolean = Boolean = bool - # to avoid breaking code which references xmlrpclib.{True,False} - True, False = True, False -else: - class Boolean: - """Boolean-value wrapper. - - Use True or False to generate a "boolean" XML-RPC value. - """ - - def __init__(self, value = 0): - self.value = operator.truth(value) - - def encode(self, out): - out.write("%d\n" % self.value) - - def __cmp__(self, other): - if isinstance(other, Boolean): - other = other.value - return cmp(self.value, other) - - def __repr__(self): - if self.value: - return "" % id(self) - else: - return "" % id(self) - - def __int__(self): - return self.value - - def __nonzero__(self): - return self.value - - True, False = Boolean(1), Boolean(0) - - ## - # Map true or false value to XML-RPC boolean values. - # - # @def boolean(value) - # @param value A boolean value. Any true value is mapped to True, - # all other values are mapped to False. - # @return xmlrpclib.True or xmlrpclib.False. - # @see Boolean - # @see True - # @see False - - def boolean(value, _truefalse=(False, True)): - """Convert any Python value to XML-RPC 'boolean'.""" - return _truefalse[operator.truth(value)] +boolean = Boolean = bool +# to avoid breaking code which references xmlrpclib.{True,False} +True, False = True, False ## # Wrapper for XML-RPC DateTime values. This converts a time value to @@ -371,10 +324,15 @@ value = time.strftime("%Y%m%dT%H:%M:%S", value) self.value = value - def __cmp__(self, other): + def __eq__(self, other): + if isinstance(other, DateTime): + other = other.value + return self.value == other + + def __ne__(self, other): if isinstance(other, DateTime): other = other.value - return cmp(self.value, other) + return self.value != other ## # Get date/time value. @@ -432,10 +390,15 @@ def __str__(self): return self.data or "" - def __cmp__(self, other): + def __eq__(self, other): + if isinstance(other, Binary): + other = other.data + return self.data == other + + def __ne__(self, other): if isinstance(other, Binary): other = other.data - return cmp(self.data, other) + return self.data != other def decode(self, data): self.data = base64.decodestring(data) Modified: python/branches/p3yk/Modules/threadmodule.c ============================================================================== --- python/branches/p3yk/Modules/threadmodule.c (original) +++ python/branches/p3yk/Modules/threadmodule.c Thu Aug 24 02:41:19 2006 @@ -696,6 +696,8 @@ /* Initialize types: */ if (PyType_Ready(&localtype) < 0) return; + if (PyType_Ready(&Locktype) < 0) + return; /* Create the module and add the functions */ m = Py_InitModule3("thread", thread_methods, thread_doc); Modified: python/branches/p3yk/Objects/bufferobject.c ============================================================================== --- python/branches/p3yk/Objects/bufferobject.c (original) +++ python/branches/p3yk/Objects/bufferobject.c Thu Aug 24 02:41:19 2006 @@ -252,23 +252,65 @@ } static int -buffer_compare(PyBufferObject *self, PyBufferObject *other) +get_bufx(PyObject *obj, void **ptr, Py_ssize_t *size) { - void *p1, *p2; - Py_ssize_t len_self, len_other, min_len; - int cmp; + PyBufferProcs *bp; - if (!get_buf(self, &p1, &len_self, ANY_BUFFER)) - return -1; - if (!get_buf(other, &p2, &len_other, ANY_BUFFER)) - return -1; - min_len = (len_self < len_other) ? len_self : len_other; - if (min_len > 0) { - cmp = memcmp(p1, p2, min_len); - if (cmp != 0) - return cmp < 0 ? -1 : 1; + if (PyBuffer_Check(obj)) { + if (!get_buf((PyBufferObject *)obj, ptr, size, ANY_BUFFER)) { + PyErr_Clear(); + return 0; + } + else + return 1; + } + bp = obj->ob_type->tp_as_buffer; + if (bp == NULL || + bp->bf_getreadbuffer == NULL || + bp->bf_getsegcount == NULL) + return 0; + if ((*bp->bf_getsegcount)(obj, NULL) != 1) + return 0; + *size = (*bp->bf_getreadbuffer)(obj, 0, ptr); + if (*size < 0) { + PyErr_Clear(); + return 0; } - return (len_self < len_other) ? -1 : (len_self > len_other) ? 1 : 0; + return 1; +} + +static PyObject * +buffer_richcompare(PyObject *self, PyObject *other, int op) +{ + void *p1, *p2; + Py_ssize_t len1, len2, min_len; + int cmp, ok; + + ok = 1; + if (!get_bufx(self, &p1, &len1)) + ok = 0; + if (!get_bufx(other, &p2, &len2)) + ok = 0; + if (!ok) { + /* If we can't get the buffers, + == and != are still defined + (and the objects are unequal) */ + PyObject *result; + if (op == Py_EQ) + result = Py_False; + else if (op == Py_NE) + result = Py_True; + else + result = Py_NotImplemented; + Py_INCREF(result); + return result; + } + min_len = (len1 < len2) ? len1 : len2; + cmp = memcmp(p1, p2, min_len); + if (cmp == 0) + cmp = (len1 < len2) ? -1 : + (len1 > len2) ? 1 : 0; + return Py_CmpToRich(op, cmp); } static PyObject * @@ -667,7 +709,7 @@ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ - (cmpfunc)buffer_compare, /* tp_compare */ + 0, /* tp_compare */ (reprfunc)buffer_repr, /* tp_repr */ 0, /* tp_as_number */ &buffer_as_sequence, /* tp_as_sequence */ @@ -682,7 +724,7 @@ buffer_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ - 0, /* tp_richcompare */ + buffer_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ Modified: python/branches/p3yk/Objects/cellobject.c ============================================================================== --- python/branches/p3yk/Objects/cellobject.c (original) +++ python/branches/p3yk/Objects/cellobject.c Thu Aug 24 02:41:19 2006 @@ -49,18 +49,6 @@ PyObject_GC_Del(op); } -static int -cell_compare(PyCellObject *a, PyCellObject *b) -{ - if (a->ob_ref == NULL) { - if (b->ob_ref == NULL) - return 0; - return -1; - } else if (b->ob_ref == NULL) - return 1; - return PyObject_Compare(a->ob_ref, b->ob_ref); -} - static PyObject * cell_repr(PyCellObject *op) { @@ -108,7 +96,7 @@ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ - (cmpfunc)cell_compare, /* tp_compare */ + 0, /* tp_compare */ (reprfunc)cell_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ Modified: python/branches/p3yk/Objects/classobject.c ============================================================================== --- python/branches/p3yk/Objects/classobject.c (original) +++ python/branches/p3yk/Objects/classobject.c Thu Aug 24 02:41:19 2006 @@ -80,7 +80,7 @@ #define OFF(x) offsetof(PyMethodObject, x) -static PyMemberDef instancemethod_memberlist[] = { +static PyMemberDef method_memberlist[] = { {"im_class", T_OBJECT, OFF(im_class), READONLY|RESTRICTED, "the class associated with a method"}, {"im_func", T_OBJECT, OFF(im_func), READONLY|RESTRICTED, @@ -96,7 +96,7 @@ should only be used for the class, not for instances */ static PyObject * -instancemethod_get_doc(PyMethodObject *im, void *context) +method_get_doc(PyMethodObject *im, void *context) { static PyObject *docstr; if (docstr == NULL) { @@ -107,13 +107,13 @@ return PyObject_GetAttr(im->im_func, docstr); } -static PyGetSetDef instancemethod_getset[] = { - {"__doc__", (getter)instancemethod_get_doc, NULL, NULL}, +static PyGetSetDef method_getset[] = { + {"__doc__", (getter)method_get_doc, NULL, NULL}, {0} }; static PyObject * -instancemethod_getattro(PyObject *obj, PyObject *name) +method_getattro(PyObject *obj, PyObject *name) { PyMethodObject *im = (PyMethodObject *)obj; PyTypeObject *tp = obj->ob_type; @@ -140,19 +140,19 @@ return PyObject_GetAttr(im->im_func, name); } -PyDoc_STRVAR(instancemethod_doc, -"instancemethod(function, instance, class)\n\ +PyDoc_STRVAR(method_doc, +"method(function, instance, class)\n\ \n\ Create an instance method object."); static PyObject * -instancemethod_new(PyTypeObject* type, PyObject* args, PyObject *kw) +method_new(PyTypeObject* type, PyObject* args, PyObject *kw) { PyObject *func; PyObject *self; PyObject *classObj = NULL; - if (!PyArg_UnpackTuple(args, "instancemethod", 2, 3, + if (!PyArg_UnpackTuple(args, "method", 2, 3, &func, &self, &classObj)) return NULL; if (!PyCallable_Check(func)) { @@ -172,7 +172,7 @@ } static void -instancemethod_dealloc(register PyMethodObject *im) +method_dealloc(register PyMethodObject *im) { _PyObject_GC_UNTRACK(im); if (im->im_weakreflist != NULL) @@ -184,24 +184,42 @@ free_list = im; } -static int -instancemethod_compare(PyMethodObject *a, PyMethodObject *b) +static PyObject * +method_richcompare(PyObject *self, PyObject *other, int op) { - int cmp; - cmp = PyObject_Compare(a->im_func, b->im_func); - if (cmp) - return cmp; - - if (a->im_self == b->im_self) - return 0; - if (a->im_self == NULL || b->im_self == NULL) - return (a->im_self < b->im_self) ? -1 : 1; + PyMethodObject *a, *b; + PyObject *res; + int eq; + + if ((op != Py_EQ && op != Py_NE) || + !PyMethod_Check(self) || + !PyMethod_Check(other)) + { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + a = (PyMethodObject *)self; + b = (PyMethodObject *)other; + eq = PyObject_RichCompareBool(a->im_func, b->im_func, Py_EQ); + if (eq == 1) { + if (a->im_self == NULL || b->im_self == NULL) + eq = a->im_self == b->im_self; + else + eq = PyObject_RichCompareBool(a->im_self, b->im_self, + Py_EQ); + } + if (eq < 0) + return NULL; + if (op == Py_EQ) + res = eq ? Py_True : Py_False; else - return PyObject_Compare(a->im_self, b->im_self); + res = eq ? Py_False : Py_True; + Py_INCREF(res); + return res; } static PyObject * -instancemethod_repr(PyMethodObject *a) +method_repr(PyMethodObject *a) { PyObject *self = a->im_self; PyObject *func = a->im_func; @@ -261,7 +279,7 @@ } static long -instancemethod_hash(PyMethodObject *a) +method_hash(PyMethodObject *a) { long x, y; if (a->im_self == NULL) @@ -280,7 +298,7 @@ } static int -instancemethod_traverse(PyMethodObject *im, visitproc visit, void *arg) +method_traverse(PyMethodObject *im, visitproc visit, void *arg) { Py_VISIT(im->im_func); Py_VISIT(im->im_self); @@ -333,7 +351,7 @@ } static PyObject * -instancemethod_call(PyObject *func, PyObject *arg, PyObject *kw) +method_call(PyObject *func, PyObject *arg, PyObject *kw) { PyObject *self = PyMethod_GET_SELF(func); PyObject *klass = PyMethod_GET_CLASS(func); @@ -392,7 +410,7 @@ } static PyObject * -instancemethod_descr_get(PyObject *meth, PyObject *obj, PyObject *cls) +method_descr_get(PyObject *meth, PyObject *obj, PyObject *cls) { /* Don't rebind an already bound method, or an unbound method of a class that's not a base class of cls. */ @@ -420,43 +438,43 @@ PyTypeObject PyMethod_Type = { PyObject_HEAD_INIT(&PyType_Type) 0, - "instancemethod", + "method", sizeof(PyMethodObject), 0, - (destructor)instancemethod_dealloc, /* tp_dealloc */ + (destructor)method_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ - (cmpfunc)instancemethod_compare, /* tp_compare */ - (reprfunc)instancemethod_repr, /* tp_repr */ + 0, /* tp_compare */ + (reprfunc)method_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ - (hashfunc)instancemethod_hash, /* tp_hash */ - instancemethod_call, /* tp_call */ + (hashfunc)method_hash, /* tp_hash */ + method_call, /* tp_call */ 0, /* tp_str */ - instancemethod_getattro, /* tp_getattro */ + method_getattro, /* tp_getattro */ PyObject_GenericSetAttr, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */ - instancemethod_doc, /* tp_doc */ - (traverseproc)instancemethod_traverse, /* tp_traverse */ + method_doc, /* tp_doc */ + (traverseproc)method_traverse, /* tp_traverse */ 0, /* tp_clear */ - 0, /* tp_richcompare */ + method_richcompare, /* tp_richcompare */ offsetof(PyMethodObject, im_weakreflist), /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ - instancemethod_memberlist, /* tp_members */ - instancemethod_getset, /* tp_getset */ + method_memberlist, /* tp_members */ + method_getset, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ - instancemethod_descr_get, /* tp_descr_get */ + method_descr_get, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ - instancemethod_new, /* tp_new */ + method_new, /* tp_new */ }; /* Clear out the free list */ Modified: python/branches/p3yk/Objects/codeobject.c ============================================================================== --- python/branches/p3yk/Objects/codeobject.c (original) +++ python/branches/p3yk/Objects/codeobject.c Thu Aug 24 02:41:19 2006 @@ -291,9 +291,15 @@ return PyString_FromString(buf); } -static int -code_compare(PyCodeObject *co, PyCodeObject *cp) +static PyObject * +code_richcompare(PyObject *self, PyObject *other, int op) { + /* Temporarily make this unsupported */ + _Py_Break(); + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + +#if 0 int cmp; cmp = PyObject_Compare(co->co_name, cp->co_name); if (cmp) return cmp; @@ -325,6 +331,7 @@ return -1; else return 0; +#endif } static long @@ -363,12 +370,12 @@ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ - (cmpfunc)code_compare, /* tp_compare */ + 0, /* tp_compare */ (reprfunc)code_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ - (hashfunc)code_hash, /* tp_hash */ + 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ Modified: python/branches/p3yk/Objects/dictobject.c ============================================================================== --- python/branches/p3yk/Objects/dictobject.c (original) +++ python/branches/p3yk/Objects/dictobject.c Thu Aug 24 02:41:19 2006 @@ -582,6 +582,36 @@ return ep->me_value; } +/* Variant of PyDict_GetItem() that doesn't suppress exceptions. + This returns NULL *with* an exception set if an exception occurred. + It returns NULL *without* an exception set if the key wasn't present. +*/ +PyObject * +PyDict_GetItemWithError(PyObject *op, PyObject *key) +{ + long hash; + dictobject *mp = (dictobject *)op; + dictentry *ep; + + if (!PyDict_Check(op)) { + PyErr_BadInternalCall(); + return NULL; + } + if (!PyString_CheckExact(key) || + (hash = ((PyStringObject *) key)->ob_shash) == -1) + { + hash = PyObject_Hash(key); + if (hash == -1) { + return NULL; + } + } + + ep = (mp->ma_lookup)(mp, key, hash); + if (ep == NULL) + return NULL; + return ep->me_value; +} + /* CAUTION: PyDict_SetItem() must guarantee that it won't resize the * dictionary if it's merely replacing the value for an existing key. * This means that it's safe to loop over a dictionary with PyDict_Next() @@ -1432,136 +1462,6 @@ return dict_items((dictobject *)mp); } -/* Subroutine which returns the smallest key in a for which b's value - is different or absent. The value is returned too, through the - pval argument. Both are NULL if no key in a is found for which b's status - differs. The refcounts on (and only on) non-NULL *pval and function return - values must be decremented by the caller (characterize() increments them - to ensure that mutating comparison and PyDict_GetItem calls can't delete - them before the caller is done looking at them). */ - -static PyObject * -characterize(dictobject *a, dictobject *b, PyObject **pval) -{ - PyObject *akey = NULL; /* smallest key in a s.t. a[akey] != b[akey] */ - PyObject *aval = NULL; /* a[akey] */ - Py_ssize_t i; - int cmp; - - for (i = 0; i <= a->ma_mask; i++) { - PyObject *thiskey, *thisaval, *thisbval; - if (a->ma_table[i].me_value == NULL) - continue; - thiskey = a->ma_table[i].me_key; - Py_INCREF(thiskey); /* keep alive across compares */ - if (akey != NULL) { - cmp = PyObject_RichCompareBool(akey, thiskey, Py_LT); - if (cmp < 0) { - Py_DECREF(thiskey); - goto Fail; - } - if (cmp > 0 || - i > a->ma_mask || - a->ma_table[i].me_value == NULL) - { - /* Not the *smallest* a key; or maybe it is - * but the compare shrunk the dict so we can't - * find its associated value anymore; or - * maybe it is but the compare deleted the - * a[thiskey] entry. - */ - Py_DECREF(thiskey); - continue; - } - } - - /* Compare a[thiskey] to b[thiskey]; cmp <- true iff equal. */ - thisaval = a->ma_table[i].me_value; - assert(thisaval); - Py_INCREF(thisaval); /* keep alive */ - thisbval = PyDict_GetItem((PyObject *)b, thiskey); - if (thisbval == NULL) - cmp = 0; - else { - /* both dicts have thiskey: same values? */ - cmp = PyObject_RichCompareBool( - thisaval, thisbval, Py_EQ); - if (cmp < 0) { - Py_DECREF(thiskey); - Py_DECREF(thisaval); - goto Fail; - } - } - if (cmp == 0) { - /* New winner. */ - Py_XDECREF(akey); - Py_XDECREF(aval); - akey = thiskey; - aval = thisaval; - } - else { - Py_DECREF(thiskey); - Py_DECREF(thisaval); - } - } - *pval = aval; - return akey; - -Fail: - Py_XDECREF(akey); - Py_XDECREF(aval); - *pval = NULL; - return NULL; -} - -static int -dict_compare(dictobject *a, dictobject *b) -{ - PyObject *adiff, *bdiff, *aval, *bval; - int res; - - /* Compare lengths first */ - if (a->ma_used < b->ma_used) - return -1; /* a is shorter */ - else if (a->ma_used > b->ma_used) - return 1; /* b is shorter */ - - /* Same length -- check all keys */ - bdiff = bval = NULL; - adiff = characterize(a, b, &aval); - if (adiff == NULL) { - assert(!aval); - /* Either an error, or a is a subset with the same length so - * must be equal. - */ - res = PyErr_Occurred() ? -1 : 0; - goto Finished; - } - bdiff = characterize(b, a, &bval); - if (bdiff == NULL && PyErr_Occurred()) { - assert(!bval); - res = -1; - goto Finished; - } - res = 0; - if (bdiff) { - /* bdiff == NULL "should be" impossible now, but perhaps - * the last comparison done by the characterize() on a had - * the side effect of making the dicts equal! - */ - res = PyObject_Compare(adiff, bdiff); - } - if (res == 0 && bval != NULL) - res = PyObject_Compare(aval, bval); - -Finished: - Py_XDECREF(adiff); - Py_XDECREF(bdiff); - Py_XDECREF(aval); - Py_XDECREF(bval); - return res; -} - /* Return 1 if dicts equal, 0 if not, -1 if error. * Gets out as soon as any difference is detected. * Uses only Py_EQ comparison. @@ -1585,9 +1485,11 @@ /* temporarily bump aval's refcount to ensure it stays alive until we're done with it */ Py_INCREF(aval); - bval = PyDict_GetItem((PyObject *)b, key); + bval = PyDict_GetItemWithError((PyObject *)b, key); if (bval == NULL) { Py_DECREF(aval); + if (PyErr_Occurred()) + return -1; return 0; } cmp = PyObject_RichCompareBool(aval, bval, Py_EQ); @@ -2028,7 +1930,7 @@ (printfunc)dict_print, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ - (cmpfunc)dict_compare, /* tp_compare */ + 0, /* tp_compare */ (reprfunc)dict_repr, /* tp_repr */ 0, /* tp_as_number */ &dict_as_sequence, /* tp_as_sequence */ Modified: python/branches/p3yk/Objects/intobject.c ============================================================================== --- python/branches/p3yk/Objects/intobject.c (original) +++ python/branches/p3yk/Objects/intobject.c Thu Aug 24 02:41:19 2006 @@ -446,6 +446,17 @@ return (i < j) ? -1 : (i > j) ? 1 : 0; } +static PyObject * +int_richcompare(PyObject *self, PyObject *other, int op) +{ + if (!PyInt_Check(self) || !PyInt_Check(other)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + return Py_CmpToRich(op, int_compare((PyIntObject *)self, + (PyIntObject *)other)); +} + static long int_hash(PyIntObject *v) { @@ -1063,7 +1074,7 @@ (printfunc)int_print, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ - (cmpfunc)int_compare, /* tp_compare */ + 0, /* tp_compare */ (reprfunc)int_repr, /* tp_repr */ &int_as_number, /* tp_as_number */ 0, /* tp_as_sequence */ @@ -1078,7 +1089,7 @@ int_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ - 0, /* tp_richcompare */ + int_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ Modified: python/branches/p3yk/Objects/listobject.c ============================================================================== --- python/branches/p3yk/Objects/listobject.c (original) +++ python/branches/p3yk/Objects/listobject.c Thu Aug 24 02:41:19 2006 @@ -1971,6 +1971,26 @@ return (PyObject *)co; } +static int +is_default_cmp(PyObject *cmpfunc) +{ + PyCFunctionObject *f; + if (cmpfunc == NULL || cmpfunc == Py_None) + return 1; + if (!PyCFunction_Check(cmpfunc)) + return 0; + f = (PyCFunction *)cmpfunc; + if (f->m_self != NULL) + return 0; + if (!PyString_Check(f->m_module)) + return 0; + if (strcmp(PyString_AS_STRING(f->m_module), "__builtin__") != 0) + return 0; + if (strcmp(f->m_ml->ml_name, "cmp") != 0) + return 0; + return 1; +} + /* An adaptive, stable, natural mergesort. See listsort.txt. * Returns Py_None on success, NULL on error. Even in case of error, the * list will be some permutation of its input state (nothing is lost or @@ -2001,7 +2021,7 @@ kwlist, &compare, &keyfunc, &reverse)) return NULL; } - if (compare == Py_None) + if (is_default_cmp(compare)) compare = NULL; if (keyfunc == Py_None) keyfunc = NULL; Modified: python/branches/p3yk/Objects/longobject.c ============================================================================== --- python/branches/p3yk/Objects/longobject.c (original) +++ python/branches/p3yk/Objects/longobject.c Thu Aug 24 02:41:19 2006 @@ -1,5 +1,3 @@ - - /* Long (arbitrary precision) integer object implementation */ /* XXX The functional organization of this file is terrible */ @@ -1882,6 +1880,14 @@ return sign < 0 ? -1 : sign > 0 ? 1 : 0; } +static PyObject * +long_richcompare(PyObject *self, PyObject *other, int op) +{ + PyLongObject *a, *b; + CONVERT_BINOP((PyObject *)self, (PyObject *)other, &a, &b); + return Py_CmpToRich(op, long_compare(a, b)); +} + static long long_hash(PyLongObject *v) { @@ -3357,7 +3363,7 @@ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ - (cmpfunc)long_compare, /* tp_compare */ + 0, /* tp_compare */ long_repr, /* tp_repr */ &long_as_number, /* tp_as_number */ 0, /* tp_as_sequence */ @@ -3372,7 +3378,7 @@ long_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ - 0, /* tp_richcompare */ + long_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ Modified: python/branches/p3yk/Objects/methodobject.c ============================================================================== --- python/branches/p3yk/Objects/methodobject.c (original) +++ python/branches/p3yk/Objects/methodobject.c Thu Aug 24 02:41:19 2006 @@ -196,17 +196,31 @@ m->m_self); } -static int -meth_compare(PyCFunctionObject *a, PyCFunctionObject *b) +static PyObject * +meth_richcompare(PyObject *self, PyObject *other, int op) { - if (a->m_self != b->m_self) - return (a->m_self < b->m_self) ? -1 : 1; - if (a->m_ml->ml_meth == b->m_ml->ml_meth) - return 0; - if (strcmp(a->m_ml->ml_name, b->m_ml->ml_name) < 0) - return -1; + PyCFunctionObject *a, *b; + PyObject *res; + int eq; + + if ((op != Py_EQ && op != Py_NE) || + !PyCFunction_Check(self) || + !PyCFunction_Check(other)) + { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + a = (PyCFunctionObject *)self; + b = (PyCFunctionObject *)other; + eq = a->m_self == b->m_self; + if (eq) + eq = a->m_ml->ml_meth == b->m_ml->ml_meth; + if (op == Py_EQ) + res = eq ? Py_True : Py_False; else - return 1; + res = eq ? Py_False : Py_True; + Py_INCREF(res); + return res; } static long @@ -240,7 +254,7 @@ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ - (cmpfunc)meth_compare, /* tp_compare */ + 0, /* tp_compare */ (reprfunc)meth_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ @@ -255,7 +269,7 @@ 0, /* tp_doc */ (traverseproc)meth_traverse, /* tp_traverse */ 0, /* tp_clear */ - 0, /* tp_richcompare */ + meth_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ Modified: python/branches/p3yk/Objects/object.c ============================================================================== --- python/branches/p3yk/Objects/object.c (original) +++ python/branches/p3yk/Objects/object.c Thu Aug 24 02:41:19 2006 @@ -252,14 +252,6 @@ return PyObject_INIT_VAR(op, tp, nitems); } -/* for binary compatibility with 2.2 */ -#undef _PyObject_Del -void -_PyObject_Del(PyObject *op) -{ - PyObject_FREE(op); -} - /* Implementation of PyObject_Print with recursion checking */ static int internal_print(PyObject *op, FILE *fp, int flags, int nesting) @@ -513,431 +505,200 @@ #endif -/* Helper to warn about deprecated tp_compare return values. Return: - -2 for an exception; - -1 if v < w; - 0 if v == w; - 1 if v > w. - (This function cannot return 2.) -*/ -static int -adjust_tp_compare(int c) -{ - if (PyErr_Occurred()) { - if (c != -1 && c != -2) { - PyObject *t, *v, *tb; - PyErr_Fetch(&t, &v, &tb); - if (PyErr_Warn(PyExc_RuntimeWarning, - "tp_compare didn't return -1 or -2 " - "for exception") < 0) { - Py_XDECREF(t); - Py_XDECREF(v); - Py_XDECREF(tb); - } - else - PyErr_Restore(t, v, tb); - } - return -2; - } - else if (c < -1 || c > 1) { - if (PyErr_Warn(PyExc_RuntimeWarning, - "tp_compare didn't return -1, 0 or 1") < 0) - return -2; - else - return c < -1 ? -1 : 1; - } - else { - assert(c >= -1 && c <= 1); - return c; - } -} +/* The new comparison philosophy is: we completely separate three-way + comparison from rich comparison. That is, PyObject_Compare() and + PyObject_Cmp() *just* use the tp_compare slot. And PyObject_RichCompare() + and PyObject_RichCompareBool() *just* use the tp_richcompare slot. + + See (*) below for practical amendments. + IOW, only cmp() uses tp_compare; the comparison operators (==, !=, <=, <, + >=, >) only use tp_richcompare. Note that list.sort() only uses <. -/* Macro to get the tp_richcompare field of a type if defined */ -#define RICHCOMPARE(t) ((t)->tp_richcompare) + (And yes, eventually we'll rip out cmp() and tp_compare.) -/* Map rich comparison operators to their swapped version, e.g. LT --> GT */ -int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE}; + The calling conventions are different: tp_compare only gets called with two + objects of the appropriate type; tp_richcompare gets called with a first + argument of the appropriate type and a second object of an arbitrary type. + We never do any kind of coercion. -/* Try a genuine rich comparison, returning an object. Return: - NULL for exception; - NotImplemented if this particular rich comparison is not implemented or - undefined; - some object not equal to NotImplemented if it is implemented - (this latter object may not be a Boolean). -*/ -static PyObject * -try_rich_compare(PyObject *v, PyObject *w, int op) -{ - richcmpfunc f; - PyObject *res; + The return conventions are also different. - if (v->ob_type != w->ob_type && - PyType_IsSubtype(w->ob_type, v->ob_type) && - (f = RICHCOMPARE(w->ob_type)) != NULL) { - res = (*f)(w, v, _Py_SwappedOp[op]); - if (res != Py_NotImplemented) - return res; - Py_DECREF(res); - } - if ((f = RICHCOMPARE(v->ob_type)) != NULL) { - res = (*f)(v, w, op); - if (res != Py_NotImplemented) - return res; - Py_DECREF(res); - } - if ((f = RICHCOMPARE(w->ob_type)) != NULL) { - return (*f)(w, v, _Py_SwappedOp[op]); - } - res = Py_NotImplemented; - Py_INCREF(res); - return res; -} + The tp_compare slot should return a C int, as follows: -/* Try a genuine rich comparison, returning an int. Return: - -1 for exception (including the case where try_rich_compare() returns an - object that's not a Boolean); - 0 if the outcome is false; - 1 if the outcome is true; - 2 if this particular rich comparison is not implemented or undefined. -*/ -static int -try_rich_compare_bool(PyObject *v, PyObject *w, int op) -{ - PyObject *res; - int ok; + -1 if a < b or if an exception occurred + 0 if a == b + +1 if a > b - if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL) - return 2; /* Shortcut, avoid INCREF+DECREF */ - res = try_rich_compare(v, w, op); - if (res == NULL) - return -1; - if (res == Py_NotImplemented) { - Py_DECREF(res); - return 2; - } - ok = PyObject_IsTrue(res); - Py_DECREF(res); - return ok; -} + No other return values are allowed. PyObject_Compare() has the same + calling convention. -/* Try rich comparisons to determine a 3-way comparison. Return: - -2 for an exception; - -1 if v < w; - 0 if v == w; - 1 if v > w; - 2 if this particular rich comparison is not implemented or undefined. -*/ -static int -try_rich_to_3way_compare(PyObject *v, PyObject *w) -{ - static struct { int op; int outcome; } tries[3] = { - /* Try this operator, and if it is true, use this outcome: */ - {Py_EQ, 0}, - {Py_LT, -1}, - {Py_GT, 1}, - }; - int i; + The tp_richcompare slot should return an object, as follows: - if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL) - return 2; /* Shortcut */ + NULL if an exception occurred + NotImplemented if the requested comparison is not implemented + any other false value if the requested comparison is false + any other true value if the requested comparison is true - for (i = 0; i < 3; i++) { - switch (try_rich_compare_bool(v, w, tries[i].op)) { - case -1: - return -2; - case 1: - return tries[i].outcome; - } - } - - return 2; -} + The PyObject_RichCompare[Bool]() wrappers raise TypeError when they get + NotImplemented. -/* Try a 3-way comparison, returning an int. Return: - -2 for an exception; - -1 if v < w; - 0 if v == w; - 1 if v > w; - 2 if this particular 3-way comparison is not implemented or undefined. -*/ -static int -try_3way_compare(PyObject *v, PyObject *w) -{ - int c; - cmpfunc f; + (*) Practical amendments: - /* Comparisons involving instances are given to instance_compare, - which has the same return conventions as this function. */ + - If rich comparison returns NotImplemented, == and != are decided by + comparing the object pointer (i.e. falling back to the base object + implementation). - f = v->ob_type->tp_compare; + - If three-way comparison is not implemented, it falls back on rich + comparison (but not the other way around!). - /* If both have the same (non-NULL) tp_compare, use it. */ - if (f != NULL && f == w->ob_type->tp_compare) { - c = (*f)(v, w); - return adjust_tp_compare(c); - } - - /* If either tp_compare is _PyObject_SlotCompare, that's safe. */ - if (f == _PyObject_SlotCompare || - w->ob_type->tp_compare == _PyObject_SlotCompare) - return _PyObject_SlotCompare(v, w); - - /* If we're here, v and w, - a) are not instances; - b) have different types or a type without tp_compare; and - c) don't have a user-defined tp_compare. - tp_compare implementations in C assume that both arguments - have their type, so we give up if the coercion fails. - */ - c = PyNumber_CoerceEx(&v, &w); - if (c < 0) - return -2; - if (c > 0) - return 2; - f = v->ob_type->tp_compare; - if (f != NULL && f == w->ob_type->tp_compare) { - c = (*f)(v, w); - Py_DECREF(v); - Py_DECREF(w); - return adjust_tp_compare(c); - } - - /* No comparison defined */ - Py_DECREF(v); - Py_DECREF(w); - return 2; -} - -/* Final fallback 3-way comparison, returning an int. Return: - -2 if an error occurred; - -1 if v < w; - 0 if v == w; - 1 if v > w. */ -static int -default_3way_compare(PyObject *v, PyObject *w) -{ - int c; - const char *vname, *wname; - if (v->ob_type == w->ob_type) { - /* When comparing these pointers, they must be cast to - * integer types (i.e. Py_uintptr_t, our spelling of C9X's - * uintptr_t). ANSI specifies that pointer compares other - * than == and != to non-related structures are undefined. - */ - Py_uintptr_t vv = (Py_uintptr_t)v; - Py_uintptr_t ww = (Py_uintptr_t)w; - return (vv < ww) ? -1 : (vv > ww) ? 1 : 0; - } +/* Forward */ +static PyObject *do_richcompare(PyObject *v, PyObject *w, int op); - /* None is smaller than anything */ - if (v == Py_None) - return -1; - if (w == Py_None) - return 1; - - /* different type: compare type names; numbers are smaller */ - if (PyNumber_Check(v)) - vname = ""; - else - vname = v->ob_type->tp_name; - if (PyNumber_Check(w)) - wname = ""; - else - wname = w->ob_type->tp_name; - c = strcmp(vname, wname); - if (c < 0) - return -1; - if (c > 0) - return 1; - /* Same type name, or (more likely) incomparable numeric types */ - return ((Py_uintptr_t)(v->ob_type) < ( - Py_uintptr_t)(w->ob_type)) ? -1 : 1; -} - -/* Do a 3-way comparison, by hook or by crook. Return: - -2 for an exception (but see below); - -1 if v < w; - 0 if v == w; - 1 if v > w; - BUT: if the object implements a tp_compare function, it returns - whatever this function returns (whether with an exception or not). -*/ +/* Perform a three-way comparison, raising TypeError if three-way comparison + is not supported. */ static int -do_cmp(PyObject *v, PyObject *w) +do_compare(PyObject *v, PyObject *w) { - int c; cmpfunc f; + int ok; - if (v->ob_type == w->ob_type - && (f = v->ob_type->tp_compare) != NULL) { - c = (*f)(v, w); - return adjust_tp_compare(c); - } - /* We only get here if one of the following is true: - a) v and w have different types - b) v and w have the same type, which doesn't have tp_compare - c) v and w are instances, and either __cmp__ is not defined or - __cmp__ returns NotImplemented - */ - c = try_rich_to_3way_compare(v, w); - if (c < 2) - return c; - c = try_3way_compare(v, w); - if (c < 2) - return c; - return default_3way_compare(v, w); -} - -/* Compare v to w. Return - -1 if v < w or exception (PyErr_Occurred() true in latter case). - 0 if v == w. - 1 if v > w. - XXX The docs (C API manual) say the return value is undefined in case - XXX of error. -*/ + if (v->ob_type == w->ob_type && + (f = v->ob_type->tp_compare) != NULL) { + return (*f)(v, w); + } + + /* Now try three-way compare before giving up. This is intentionally + elaborate; if you have a it will raise TypeError if it detects two + objects that aren't ordered with respect to each other. */ + ok = PyObject_RichCompareBool(v, w, Py_LT); + if (ok < 0) + return -1; /* Error */ + if (ok) + return -1; /* Less than */ + ok = PyObject_RichCompareBool(v, w, Py_GT); + if (ok < 0) + return -1; /* Error */ + if (ok) + return 1; /* Greater than */ + ok = PyObject_RichCompareBool(v, w, Py_EQ); + if (ok < 0) + return -1; /* Error */ + if (ok) + return 0; /* Equal */ + + /* Give up */ + PyErr_Format(PyExc_TypeError, + "unorderable types: '%.100s' <> '%.100s'", + v->ob_type->tp_name, + w->ob_type->tp_name); + return -1; +} + +/* Perform a three-way comparison. This wraps do_compare() with a check for + NULL arguments and a recursion check. */ int PyObject_Compare(PyObject *v, PyObject *w) { - int result; + int res; if (v == NULL || w == NULL) { - PyErr_BadInternalCall(); + if (!PyErr_Occurred()) + PyErr_BadInternalCall(); return -1; } - if (v == w) - return 0; if (Py_EnterRecursiveCall(" in cmp")) return -1; - result = do_cmp(v, w); + res = do_compare(v, w); Py_LeaveRecursiveCall(); - return result < 0 ? -1 : result; + return res < 0 ? -1 : res; } -/* Return (new reference to) Py_True or Py_False. */ -static PyObject * -convert_3way_to_object(int op, int c) -{ - PyObject *result; - switch (op) { - case Py_LT: c = c < 0; break; - case Py_LE: c = c <= 0; break; - case Py_EQ: c = c == 0; break; - case Py_NE: c = c != 0; break; - case Py_GT: c = c > 0; break; - case Py_GE: c = c >= 0; break; - } - result = c ? Py_True : Py_False; - Py_INCREF(result); - return result; -} - -/* We want a rich comparison but don't have one. Try a 3-way cmp instead. - Return - NULL if error - Py_True if v op w - Py_False if not (v op w) -*/ -static PyObject * -try_3way_to_rich_compare(PyObject *v, PyObject *w, int op) -{ - int c; +/* Map rich comparison operators to their swapped version, e.g. LT <--> GT */ +int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE}; - c = try_3way_compare(v, w); - if (c >= 2) - c = default_3way_compare(v, w); - if (c <= -2) - return NULL; - return convert_3way_to_object(op, c); -} +static char *opstrings[] = {">", ">=", "==", "!=", "<", "<="}; -/* Do rich comparison on v and w. Return - NULL if error - Else a new reference to an object other than Py_NotImplemented, usually(?): - Py_True if v op w - Py_False if not (v op w) -*/ +/* Perform a rich comparison, raising TypeError when the requested comparison + operator is not supported. */ static PyObject * -do_richcmp(PyObject *v, PyObject *w, int op) +do_richcompare(PyObject *v, PyObject *w, int op) { + richcmpfunc f; PyObject *res; - res = try_rich_compare(v, w, op); - if (res != Py_NotImplemented) - return res; - Py_DECREF(res); - - return try_3way_to_rich_compare(v, w, op); + if (v->ob_type != w->ob_type && + PyType_IsSubtype(w->ob_type, v->ob_type) && + (f = w->ob_type->tp_richcompare) != NULL) { + res = (*f)(w, v, _Py_SwappedOp[op]); + if (res != Py_NotImplemented) + return res; + Py_DECREF(res); + } + if ((f = v->ob_type->tp_richcompare) != NULL) { + res = (*f)(v, w, op); + if (res != Py_NotImplemented) + return res; + Py_DECREF(res); + } + if ((f = w->ob_type->tp_richcompare) != NULL) { + res = (*f)(w, v, _Py_SwappedOp[op]); + if (res != Py_NotImplemented) + return res; + Py_DECREF(res); + } + /* If neither object implements it, provide a sensible default + for == and !=, but raise an exception for ordering. */ + switch (op) { + case Py_EQ: + res = (v == w) ? Py_True : Py_False; + break; + case Py_NE: + res = (v != w) ? Py_True : Py_False; + break; + default: + PyErr_Format(PyExc_TypeError, + "unorderable types: %.100s() %s %.100s()", + v->ob_type->tp_name, + opstrings[op], + w->ob_type->tp_name); + return NULL; + } + Py_INCREF(res); + return res; } -/* Return: - NULL for exception; - some object not equal to NotImplemented if it is implemented - (this latter object may not be a Boolean). -*/ +/* Perform a rich comparison with object result. This wraps do_richcompare() + with a check for NULL arguments and a recursion check. */ + PyObject * PyObject_RichCompare(PyObject *v, PyObject *w, int op) { PyObject *res; assert(Py_LT <= op && op <= Py_GE); - if (Py_EnterRecursiveCall(" in cmp")) + if (v == NULL || w == NULL) { + if (!PyErr_Occurred()) + PyErr_BadInternalCall(); return NULL; - - /* If the types are equal, and not old-style instances, try to - get out cheap (don't bother with coercions etc.). */ - if (v->ob_type == w->ob_type) { - cmpfunc fcmp; - richcmpfunc frich = RICHCOMPARE(v->ob_type); - /* If the type has richcmp, try it first. try_rich_compare - tries it two-sided, which is not needed since we've a - single type only. */ - if (frich != NULL) { - res = (*frich)(v, w, op); - if (res != Py_NotImplemented) - goto Done; - Py_DECREF(res); - } - /* No richcmp, or this particular richmp not implemented. - Try 3-way cmp. */ - fcmp = v->ob_type->tp_compare; - if (fcmp != NULL) { - int c = (*fcmp)(v, w); - c = adjust_tp_compare(c); - if (c == -2) { - res = NULL; - goto Done; - } - res = convert_3way_to_object(op, c); - goto Done; - } } - - /* Fast path not taken, or couldn't deliver a useful result. */ - res = do_richcmp(v, w, op); -Done: + if (Py_EnterRecursiveCall(" in cmp")) + return NULL; + res = do_richcompare(v, w, op); Py_LeaveRecursiveCall(); return res; } -/* Return -1 if error; 1 if v op w; 0 if not (v op w). */ +/* Perform a rich comparison with integer result. This wraps + PyObject_RichCompare(), returning -1 for error, 0 for false, 1 for true. */ int PyObject_RichCompareBool(PyObject *v, PyObject *w, int op) { PyObject *res; int ok; - /* Quick result when objects are the same. - Guarantees that identity implies equality. */ - if (v == w) { - if (op == Py_EQ) - return 1; - else if (op == Py_NE) - return 0; - } - res = PyObject_RichCompare(v, w, op); if (res == NULL) return -1; @@ -949,6 +710,44 @@ return ok; } +/* Turn the result of a three-way comparison into the result expected by a + rich comparison. */ +PyObject * +Py_CmpToRich(int op, int cmp) +{ + PyObject *res; + int ok; + + if (PyErr_Occurred()) + return NULL; + switch (op) { + case Py_LT: + ok = cmp < 0; + break; + case Py_LE: + ok = cmp <= 0; + break; + case Py_EQ: + ok = cmp == 0; + break; + case Py_NE: + ok = cmp != 0; + break; + case Py_GT: + ok = cmp > 0; + break; + case Py_GE: + ok = cmp >= 0; + break; + default: + PyErr_BadArgument(); + return NULL; + } + res = ok ? Py_True : Py_False; + Py_INCREF(res); + return res; +} + /* Set of hash utility functions to help maintaining the invariant that if a==b then hash(a)==hash(b) @@ -1832,6 +1631,9 @@ if (PyType_Ready(&PyNotImplemented_Type) < 0) Py_FatalError("Can't initialize type(NotImplemented)"); + + if (PyType_Ready(&PyCode_Type) < 0) + Py_FatalError("Can't initialize 'code'"); } Modified: python/branches/p3yk/Objects/sliceobject.c ============================================================================== --- python/branches/p3yk/Objects/sliceobject.c (original) +++ python/branches/p3yk/Objects/sliceobject.c Thu Aug 24 02:41:19 2006 @@ -280,25 +280,55 @@ {NULL, NULL} }; -static int -slice_compare(PySliceObject *v, PySliceObject *w) +static PyObject * +slice_richcompare(PyObject *v, PyObject *w, int op) { - int result = 0; + PyObject *t1; + PyObject *t2; + PyObject *res; - if (v == w) - return 0; + if (v == w) { + /* XXX Do we really need this shortcut? + There's a unit test for it, but is that fair? */ + switch (op) { + case Py_EQ: + case Py_LE: + case Py_GE: + res = Py_True; + break; + default: + res = Py_False; + break; + } + Py_INCREF(res); + return res; + } - if (PyObject_Cmp(v->start, w->start, &result) < 0) - return -2; - if (result != 0) - return result; - if (PyObject_Cmp(v->stop, w->stop, &result) < 0) - return -2; - if (result != 0) - return result; - if (PyObject_Cmp(v->step, w->step, &result) < 0) - return -2; - return result; + t1 = PyTuple_New(3); + t2 = PyTuple_New(3); + if (t1 == NULL || t2 == NULL) + return NULL; + + PyTuple_SET_ITEM(t1, 0, ((PySliceObject *)v)->start); + PyTuple_SET_ITEM(t1, 1, ((PySliceObject *)v)->stop); + PyTuple_SET_ITEM(t1, 2, ((PySliceObject *)v)->step); + PyTuple_SET_ITEM(t2, 0, ((PySliceObject *)w)->start); + PyTuple_SET_ITEM(t2, 1, ((PySliceObject *)w)->stop); + PyTuple_SET_ITEM(t2, 2, ((PySliceObject *)w)->step); + + res = PyObject_RichCompare(t1, t2, op); + + PyTuple_SET_ITEM(t1, 0, NULL); + PyTuple_SET_ITEM(t1, 1, NULL); + PyTuple_SET_ITEM(t1, 2, NULL); + PyTuple_SET_ITEM(t2, 0, NULL); + PyTuple_SET_ITEM(t2, 1, NULL); + PyTuple_SET_ITEM(t2, 2, NULL); + + Py_DECREF(t1); + Py_DECREF(t2); + + return res; } static long @@ -318,7 +348,7 @@ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ - (cmpfunc)slice_compare, /* tp_compare */ + 0, /* tp_compare */ (reprfunc)slice_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ @@ -333,7 +363,7 @@ slice_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ - 0, /* tp_richcompare */ + slice_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ Modified: python/branches/p3yk/Objects/typeobject.c ============================================================================== --- python/branches/p3yk/Objects/typeobject.c (original) +++ python/branches/p3yk/Objects/typeobject.c Thu Aug 24 02:41:19 2006 @@ -361,16 +361,6 @@ {0} }; -static int -type_compare(PyObject *v, PyObject *w) -{ - /* This is called with type objects only. So we - can just compare the addresses. */ - Py_uintptr_t vv = (Py_uintptr_t)v; - Py_uintptr_t ww = (Py_uintptr_t)w; - return (vv < ww) ? -1 : (vv > ww) ? 1 : 0; -} - static PyObject * type_repr(PyTypeObject *type) { @@ -2192,12 +2182,12 @@ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ - type_compare, /* tp_compare */ + 0, /* tp_compare */ (reprfunc)type_repr, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ - (hashfunc)_Py_HashPointer, /* tp_hash */ + 0, /* tp_hash */ (ternaryfunc)type_call, /* tp_call */ 0, /* tp_str */ (getattrofunc)type_getattro, /* tp_getattro */ @@ -2302,6 +2292,30 @@ } static PyObject * +object_richcompare(PyObject *self, PyObject *other, int op) +{ + PyObject *res; + + switch (op) { + + case Py_EQ: + res = (self == other) ? Py_True : Py_False; + break; + + case Py_NE: + res = (self != other) ? Py_True : Py_False; + break; + + default: + res = Py_NotImplemented; + break; + } + + Py_INCREF(res); + return res; +} + +static PyObject * object_get_class(PyObject *self, void *closure) { Py_INCREF(self->ob_type); @@ -2703,7 +2717,7 @@ PyDoc_STR("The most base type"), /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ - 0, /* tp_richcompare */ + object_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ Modified: python/branches/p3yk/Objects/weakrefobject.c ============================================================================== --- python/branches/p3yk/Objects/weakrefobject.c (original) +++ python/branches/p3yk/Objects/weakrefobject.c Thu Aug 24 02:41:19 2006 @@ -184,7 +184,9 @@ static PyObject * weakref_richcompare(PyWeakReference* self, PyWeakReference* other, int op) { - if (op != Py_EQ || self->ob_type != other->ob_type) { + if ((op != Py_EQ && op != Py_NE) || + !PyWeakref_Check(self) || + !PyWeakref_Check(other)) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } @@ -458,12 +460,12 @@ return PyObject_SetAttr(PyWeakref_GET_OBJECT(proxy), name, value); } -static int -proxy_compare(PyObject *proxy, PyObject *v) +static PyObject * +proxy_richcompare(PyObject *proxy, PyObject *v, int op) { - UNWRAP_I(proxy); - UNWRAP_I(v); - return PyObject_Compare(proxy, v); + UNWRAP(proxy); + UNWRAP(v); + return PyObject_RichCompare(proxy, v, op); } /* number slots */ @@ -649,7 +651,7 @@ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ - proxy_compare, /* tp_compare */ + 0, /* tp_compare */ (reprfunc)proxy_repr, /* tp_repr */ &proxy_as_number, /* tp_as_number */ &proxy_as_sequence, /* tp_as_sequence */ @@ -664,7 +666,7 @@ 0, /* tp_doc */ (traverseproc)gc_traverse, /* tp_traverse */ (inquiry)gc_clear, /* tp_clear */ - 0, /* tp_richcompare */ + proxy_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ (getiterfunc)proxy_iter, /* tp_iter */ (iternextfunc)proxy_iternext, /* tp_iternext */ @@ -683,7 +685,7 @@ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ - proxy_compare, /* tp_compare */ + 0, /* tp_compare */ (unaryfunc)proxy_repr, /* tp_repr */ &proxy_as_number, /* tp_as_number */ &proxy_as_sequence, /* tp_as_sequence */ @@ -698,7 +700,7 @@ 0, /* tp_doc */ (traverseproc)gc_traverse, /* tp_traverse */ (inquiry)gc_clear, /* tp_clear */ - 0, /* tp_richcompare */ + proxy_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ (getiterfunc)proxy_iter, /* tp_iter */ (iternextfunc)proxy_iternext, /* tp_iternext */ Modified: python/branches/p3yk/Python/bltinmodule.c ============================================================================== --- python/branches/p3yk/Python/bltinmodule.c (original) +++ python/branches/p3yk/Python/bltinmodule.c Thu Aug 24 02:41:19 2006 @@ -1324,9 +1324,10 @@ PyObject *tmp1 = NULL, *tmp2 = NULL, *tmp3 = NULL; /* holds sub-expression evaluations */ - /* if (lo >= hi), return length of 0. */ - if (PyObject_Compare(lo, hi) >= 0) - return 0; + /* If (lo >= hi), return length of 0 (or error). */ + n = PyObject_RichCompareBool(lo, hi, Py_LT); + if (n <= 0) + return n; if ((one = PyLong_FromLong(1L)) == NULL) goto Fail; @@ -1378,7 +1379,7 @@ PyObject *v = NULL; long bign; int i, n; - int cmp_result; + int step_pos; PyObject *zero = PyLong_FromLong(0); @@ -1439,17 +1440,20 @@ goto Fail; } - if (PyObject_Cmp(istep, zero, &cmp_result) == -1) + step_pos = PyObject_RichCompareBool(istep, zero, Py_GT); + if (step_pos < 0) goto Fail; - if (cmp_result == 0) { - PyErr_SetString(PyExc_ValueError, - "range() step argument must not be zero"); - goto Fail; - } - - if (cmp_result > 0) + if (step_pos) bign = get_len_of_range_longs(ilow, ihigh, istep); else { + int step_zero = PyObject_RichCompareBool(istep, zero, Py_EQ); + if (step_zero < 0) + goto Fail; + if (step_zero) { + PyErr_SetString(PyExc_ValueError, + "range() step argument must not be zero"); + goto Fail; + } PyObject *neg_istep = PyNumber_Negative(istep); if (neg_istep == NULL) goto Fail; From python-3000-checkins at python.org Thu Aug 24 04:10:21 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Thu, 24 Aug 2006 04:10:21 +0200 (CEST) Subject: [Python-3000-checkins] r51535 - python/branches/p3yk/Python/bltinmodule.c Message-ID: <20060824021021.C3AEF1E4004@bag.python.org> Author: guido.van.rossum Date: Thu Aug 24 04:10:21 2006 New Revision: 51535 Modified: python/branches/p3yk/Python/bltinmodule.c Log: Make it compile with C89. Modified: python/branches/p3yk/Python/bltinmodule.c ============================================================================== --- python/branches/p3yk/Python/bltinmodule.c (original) +++ python/branches/p3yk/Python/bltinmodule.c Thu Aug 24 04:10:21 2006 @@ -1447,6 +1447,7 @@ bign = get_len_of_range_longs(ilow, ihigh, istep); else { int step_zero = PyObject_RichCompareBool(istep, zero, Py_EQ); + PyObject *neg_istep; if (step_zero < 0) goto Fail; if (step_zero) { @@ -1454,7 +1455,7 @@ "range() step argument must not be zero"); goto Fail; } - PyObject *neg_istep = PyNumber_Negative(istep); + neg_istep = PyNumber_Negative(istep); if (neg_istep == NULL) goto Fail; bign = get_len_of_range_longs(ihigh, ilow, neg_istep); From python-3000-checkins at python.org Thu Aug 24 04:27:45 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Thu, 24 Aug 2006 04:27:45 +0200 (CEST) Subject: [Python-3000-checkins] r51536 - python/branches/p3yk/Lib/subprocess.py Message-ID: <20060824022745.AF6851E4004@bag.python.org> Author: guido.van.rossum Date: Thu Aug 24 04:27:45 2006 New Revision: 51536 Modified: python/branches/p3yk/Lib/subprocess.py Log: Fix another comparison between None and 0. Modified: python/branches/p3yk/Lib/subprocess.py ============================================================================== --- python/branches/p3yk/Lib/subprocess.py (original) +++ python/branches/p3yk/Lib/subprocess.py Thu Aug 24 04:27:45 2006 @@ -420,7 +420,8 @@ def _cleanup(): for inst in _active[:]: - if inst.poll(_deadstate=sys.maxint) >= 0: + res = inst.poll(_deadstate=sys.maxint) + if res is not None and res >= 0: try: _active.remove(inst) except ValueError: From python-3000-checkins at python.org Thu Aug 24 04:58:14 2006 From: python-3000-checkins at python.org (alex.martelli) Date: Thu, 24 Aug 2006 04:58:14 +0200 (CEST) Subject: [Python-3000-checkins] r51537 - in python/branches/p3yk/Lib: distutils/sysconfig.py idlelib/ColorDelegator.py pstats.py site.py tarfile.py test/test_bool.py test/test_bz2.py test/test_descr.py test/test_inspect.py test/test_iter.py test/test_marshal.py test/test_os.py test/test_tarfile.py test/test_unicode_file.py test/test_urllib.py test/test_urllibnet.py webbrowser.py Message-ID: <20060824025814.BC5741E4004@bag.python.org> Author: alex.martelli Date: Thu Aug 24 04:58:11 2006 New Revision: 51537 Modified: python/branches/p3yk/Lib/distutils/sysconfig.py python/branches/p3yk/Lib/idlelib/ColorDelegator.py python/branches/p3yk/Lib/pstats.py python/branches/p3yk/Lib/site.py python/branches/p3yk/Lib/tarfile.py python/branches/p3yk/Lib/test/test_bool.py python/branches/p3yk/Lib/test/test_bz2.py python/branches/p3yk/Lib/test/test_descr.py python/branches/p3yk/Lib/test/test_inspect.py python/branches/p3yk/Lib/test/test_iter.py python/branches/p3yk/Lib/test/test_marshal.py python/branches/p3yk/Lib/test/test_os.py python/branches/p3yk/Lib/test/test_tarfile.py python/branches/p3yk/Lib/test/test_unicode_file.py python/branches/p3yk/Lib/test/test_urllib.py python/branches/p3yk/Lib/test/test_urllibnet.py python/branches/p3yk/Lib/webbrowser.py Log: Anna Ravenscroft identified many occurrences of "file" used to open a file in the stdlib and changed each of them to use "open" instead. At this time there are no other known occurrences that can be safely changed (in Lib and all subdirectories thereof). Modified: python/branches/p3yk/Lib/distutils/sysconfig.py ============================================================================== --- python/branches/p3yk/Lib/distutils/sysconfig.py (original) +++ python/branches/p3yk/Lib/distutils/sysconfig.py Thu Aug 24 04:58:11 2006 @@ -354,7 +354,7 @@ # load the installed pyconfig.h: try: filename = get_config_h_filename() - parse_config_h(file(filename), g) + parse_config_h(open(filename), g) except IOError, msg: my_msg = "invalid Python installation: unable to open %s" % filename if hasattr(msg, "strerror"): Modified: python/branches/p3yk/Lib/idlelib/ColorDelegator.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/ColorDelegator.py (original) +++ python/branches/p3yk/Lib/idlelib/ColorDelegator.py Thu Aug 24 04:58:11 2006 @@ -16,7 +16,7 @@ kw = r"\b" + any("KEYWORD", keyword.kwlist) + r"\b" builtinlist = [str(name) for name in dir(__builtin__) if not name.startswith('_')] - # self.file = file("file") : + # self.file = open("file") : # 1st 'file' colorized normal, 2nd as builtin, 3rd as string builtin = r"([^.'\"\\#]\b|^)" + any("BUILTIN", builtinlist) + r"\b" comment = any("COMMENT", [r"#[^\n]*"]) Modified: python/branches/p3yk/Lib/pstats.py ============================================================================== --- python/branches/p3yk/Lib/pstats.py (original) +++ python/branches/p3yk/Lib/pstats.py Thu Aug 24 04:58:11 2006 @@ -173,7 +173,7 @@ def dump_stats(self, filename): """Write the profile data to a file we know how to load back.""" - f = file(filename, 'wb') + f = open(filename, 'wb') try: marshal.dump(self.stats, f) finally: Modified: python/branches/p3yk/Lib/site.py ============================================================================== --- python/branches/p3yk/Lib/site.py (original) +++ python/branches/p3yk/Lib/site.py Thu Aug 24 04:58:11 2006 @@ -274,7 +274,7 @@ for filename in self.__files: filename = os.path.join(dir, filename) try: - fp = file(filename, "rU") + fp = open(filename, "rU") data = fp.read() fp.close() break Modified: python/branches/p3yk/Lib/tarfile.py ============================================================================== --- python/branches/p3yk/Lib/tarfile.py (original) +++ python/branches/p3yk/Lib/tarfile.py Thu Aug 24 04:58:11 2006 @@ -934,7 +934,7 @@ self.mode = {"r": "rb", "a": "r+b", "w": "wb"}[mode] if not fileobj: - fileobj = file(self.name, self.mode) + fileobj = open(self.name, self.mode) self._extfileobj = False else: if self.name is None and hasattr(fileobj, "name"): @@ -1083,7 +1083,7 @@ tarname = pre + ext if fileobj is None: - fileobj = file(name, mode + "b") + fileobj = open(name, mode + "b") if mode != "r": name = tarname @@ -1355,7 +1355,7 @@ # Append the tar header and data to the archive. if tarinfo.isreg(): - f = file(name, "rb") + f = open(name, "rb") self.addfile(tarinfo, f) f.close() @@ -1617,7 +1617,7 @@ """Make a file called targetpath. """ source = self.extractfile(tarinfo) - target = file(targetpath, "wb") + target = open(targetpath, "wb") copyfileobj(source, target) source.close() target.close() Modified: python/branches/p3yk/Lib/test/test_bool.py ============================================================================== --- python/branches/p3yk/Lib/test/test_bool.py (original) +++ python/branches/p3yk/Lib/test/test_bool.py Thu Aug 24 04:58:11 2006 @@ -246,7 +246,7 @@ def test_fileclosed(self): try: - f = file(test_support.TESTFN, "w") + f = open(test_support.TESTFN, "w") self.assertIs(f.closed, False) f.close() self.assertIs(f.closed, True) Modified: python/branches/p3yk/Lib/test/test_bz2.py ============================================================================== --- python/branches/p3yk/Lib/test/test_bz2.py (original) +++ python/branches/p3yk/Lib/test/test_bz2.py Thu Aug 24 04:58:11 2006 @@ -243,7 +243,7 @@ self.createTempFile() bz2f = BZ2File(self.filename, "U") bz2f.close() - f = file(self.filename) + f = open(self.filename) f.seek(0, 2) self.assertEqual(f.tell(), len(self.DATA)) f.close() Modified: python/branches/p3yk/Lib/test/test_descr.py ============================================================================== --- python/branches/p3yk/Lib/test/test_descr.py (original) +++ python/branches/p3yk/Lib/test/test_descr.py Thu Aug 24 04:58:11 2006 @@ -2338,7 +2338,7 @@ self.ateof = 1 return s - f = file(name=TESTFN, mode='w') + f = open(name=TESTFN, mode='w') lines = ['a\n', 'b\n', 'c\n'] try: f.writelines(lines) @@ -2394,7 +2394,7 @@ sandbox = rexec.RExec() code1 = """f = open(%r, 'w')""" % TESTFN - code2 = """f = file(%r, 'w')""" % TESTFN + code2 = """f = open(%r, 'w')""" % TESTFN code3 = """\ f = open(%r) t = type(f) # a sneaky way to get the file() constructor Modified: python/branches/p3yk/Lib/test/test_inspect.py ============================================================================== --- python/branches/p3yk/Lib/test/test_inspect.py (original) +++ python/branches/p3yk/Lib/test/test_inspect.py Thu Aug 24 04:58:11 2006 @@ -130,7 +130,7 @@ def __init__(self, *args, **kwargs): unittest.TestCase.__init__(self, *args, **kwargs) - self.source = file(inspect.getsourcefile(self.fodderFile)).read() + self.source = open(inspect.getsourcefile(self.fodderFile)).read() def sourcerange(self, top, bottom): lines = self.source.split("\n") Modified: python/branches/p3yk/Lib/test/test_iter.py ============================================================================== --- python/branches/p3yk/Lib/test/test_iter.py (original) +++ python/branches/p3yk/Lib/test/test_iter.py Thu Aug 24 04:58:11 2006 @@ -661,7 +661,7 @@ # Test iterators with file.writelines(). def test_writelines(self): - f = file(TESTFN, "w") + f = open(TESTFN, "w") try: self.assertRaises(TypeError, f.writelines, None) @@ -700,7 +700,7 @@ f.writelines(Whatever(6, 6+2000)) f.close() - f = file(TESTFN) + f = open(TESTFN) expected = [str(i) + "\n" for i in range(1, 2006)] self.assertEqual(list(f), expected) Modified: python/branches/p3yk/Lib/test/test_marshal.py ============================================================================== --- python/branches/p3yk/Lib/test/test_marshal.py (original) +++ python/branches/p3yk/Lib/test/test_marshal.py Thu Aug 24 04:58:11 2006 @@ -16,8 +16,8 @@ s = marshal.dumps(expected) got = marshal.loads(s) self.assertEqual(expected, got) - marshal.dump(expected, file(test_support.TESTFN, "wb")) - got = marshal.load(file(test_support.TESTFN, "rb")) + marshal.dump(expected, open(test_support.TESTFN, "wb")) + got = marshal.load( open(test_support.TESTFN, "rb")) self.assertEqual(expected, got) n = n >> 1 os.unlink(test_support.TESTFN) @@ -51,8 +51,8 @@ new = marshal.loads(marshal.dumps(b)) self.assertEqual(b, new) self.assertEqual(type(b), type(new)) - marshal.dump(b, file(test_support.TESTFN, "wb")) - new = marshal.load(file(test_support.TESTFN, "rb")) + marshal.dump(b, open(test_support.TESTFN, "wb")) + new = marshal.load(open(test_support.TESTFN, "rb")) self.assertEqual(b, new) self.assertEqual(type(b), type(new)) @@ -67,8 +67,8 @@ s = marshal.dumps(f) got = marshal.loads(s) self.assertEqual(f, got) - marshal.dump(f, file(test_support.TESTFN, "wb")) - got = marshal.load(file(test_support.TESTFN, "rb")) + marshal.dump(f, open(test_support.TESTFN, "wb")) + got = marshal.load(open(test_support.TESTFN, "rb")) self.assertEqual(f, got) n /= 123.4567 @@ -94,12 +94,12 @@ got = marshal.loads(s) self.assertEqual(f, got) - marshal.dump(f, file(test_support.TESTFN, "wb")) - got = marshal.load(file(test_support.TESTFN, "rb")) + marshal.dump(f, open(test_support.TESTFN, "wb")) + got = marshal.load(open(test_support.TESTFN, "rb")) self.assertEqual(f, got) - marshal.dump(f, file(test_support.TESTFN, "wb"), 1) - got = marshal.load(file(test_support.TESTFN, "rb")) + marshal.dump(f, open(test_support.TESTFN, "wb"), 1) + got = marshal.load(open(test_support.TESTFN, "rb")) self.assertEqual(f, got) n *= 123.4567 os.unlink(test_support.TESTFN) @@ -110,8 +110,8 @@ new = marshal.loads(marshal.dumps(s)) self.assertEqual(s, new) self.assertEqual(type(s), type(new)) - marshal.dump(s, file(test_support.TESTFN, "wb")) - new = marshal.load(file(test_support.TESTFN, "rb")) + marshal.dump(s, open(test_support.TESTFN, "wb")) + new = marshal.load(open(test_support.TESTFN, "rb")) self.assertEqual(s, new) self.assertEqual(type(s), type(new)) os.unlink(test_support.TESTFN) @@ -121,8 +121,8 @@ new = marshal.loads(marshal.dumps(s)) self.assertEqual(s, new) self.assertEqual(type(s), type(new)) - marshal.dump(s, file(test_support.TESTFN, "wb")) - new = marshal.load(file(test_support.TESTFN, "rb")) + marshal.dump(s, open(test_support.TESTFN, "wb")) + new = marshal.load(open(test_support.TESTFN, "rb")) self.assertEqual(s, new) self.assertEqual(type(s), type(new)) os.unlink(test_support.TESTFN) @@ -132,8 +132,8 @@ b = buffer(s) new = marshal.loads(marshal.dumps(b)) self.assertEqual(s, new) - marshal.dump(b, file(test_support.TESTFN, "wb")) - new = marshal.load(file(test_support.TESTFN, "rb")) + marshal.dump(b, open(test_support.TESTFN, "wb")) + new = marshal.load(open(test_support.TESTFN, "rb")) self.assertEqual(s, new) os.unlink(test_support.TESTFN) @@ -161,8 +161,8 @@ def test_dict(self): new = marshal.loads(marshal.dumps(self.d)) self.assertEqual(self.d, new) - marshal.dump(self.d, file(test_support.TESTFN, "wb")) - new = marshal.load(file(test_support.TESTFN, "rb")) + marshal.dump(self.d, open(test_support.TESTFN, "wb")) + new = marshal.load(open(test_support.TESTFN, "rb")) self.assertEqual(self.d, new) os.unlink(test_support.TESTFN) @@ -170,8 +170,8 @@ lst = self.d.items() new = marshal.loads(marshal.dumps(lst)) self.assertEqual(lst, new) - marshal.dump(lst, file(test_support.TESTFN, "wb")) - new = marshal.load(file(test_support.TESTFN, "rb")) + marshal.dump(lst, open(test_support.TESTFN, "wb")) + new = marshal.load(open(test_support.TESTFN, "rb")) self.assertEqual(lst, new) os.unlink(test_support.TESTFN) @@ -179,8 +179,8 @@ t = tuple(self.d.keys()) new = marshal.loads(marshal.dumps(t)) self.assertEqual(t, new) - marshal.dump(t, file(test_support.TESTFN, "wb")) - new = marshal.load(file(test_support.TESTFN, "rb")) + marshal.dump(t, open(test_support.TESTFN, "wb")) + new = marshal.load(open(test_support.TESTFN, "rb")) self.assertEqual(t, new) os.unlink(test_support.TESTFN) @@ -191,8 +191,8 @@ self.assertEqual(t, new) self.assert_(isinstance(new, constructor)) self.assertNotEqual(id(t), id(new)) - marshal.dump(t, file(test_support.TESTFN, "wb")) - new = marshal.load(file(test_support.TESTFN, "rb")) + marshal.dump(t, open(test_support.TESTFN, "wb")) + new = marshal.load(open(test_support.TESTFN, "rb")) self.assertEqual(t, new) os.unlink(test_support.TESTFN) Modified: python/branches/p3yk/Lib/test/test_os.py ============================================================================== --- python/branches/p3yk/Lib/test/test_os.py (original) +++ python/branches/p3yk/Lib/test/test_os.py Thu Aug 24 04:58:11 2006 @@ -273,7 +273,7 @@ os.makedirs(sub11_path) os.makedirs(sub2_path) for path in tmp1_path, tmp2_path, tmp3_path: - f = file(path, "w") + f = open(path, "w") f.write("I'm " + path + " and proud of it. Blame test_os.\n") f.close() @@ -361,10 +361,10 @@ class DevNullTests (unittest.TestCase): def test_devnull(self): - f = file(os.devnull, 'w') + f = open(os.devnull, 'w') f.write('hello') f.close() - f = file(os.devnull, 'r') + f = open(os.devnull, 'r') self.assertEqual(f.read(), '') f.close() Modified: python/branches/p3yk/Lib/test/test_tarfile.py ============================================================================== --- python/branches/p3yk/Lib/test/test_tarfile.py (original) +++ python/branches/p3yk/Lib/test/test_tarfile.py Thu Aug 24 04:58:11 2006 @@ -333,11 +333,11 @@ f.close() elif self.comp == "bz2": f = bz2.BZ2Decompressor() - s = file(self.dstname).read() + s = open(self.dstname).read() s = f.decompress(s) self.assertEqual(len(f.unused_data), 0, "trailing data") else: - f = file(self.dstname) + f = open(self.dstname) s = f.read() f.close() Modified: python/branches/p3yk/Lib/test/test_unicode_file.py ============================================================================== --- python/branches/p3yk/Lib/test/test_unicode_file.py (original) +++ python/branches/p3yk/Lib/test/test_unicode_file.py Thu Aug 24 04:58:11 2006 @@ -152,7 +152,7 @@ # top-level 'test' functions would be if they could take params def _test_single(self, filename): remove_if_exists(filename) - f = file(filename, "w") + f = open(filename, "w") f.close() try: self._do_single(filename) @@ -170,7 +170,7 @@ def _test_equivalent(self, filename1, filename2): remove_if_exists(filename1) self.failUnless(not os.path.exists(filename2)) - f = file(filename1, "w") + f = open(filename1, "w") f.close() try: self._do_equivilent(filename1, filename2) Modified: python/branches/p3yk/Lib/test/test_urllib.py ============================================================================== --- python/branches/p3yk/Lib/test/test_urllib.py (original) +++ python/branches/p3yk/Lib/test/test_urllib.py Thu Aug 24 04:58:11 2006 @@ -27,7 +27,7 @@ def setUp(self): """Setup of a temp file to use for testing""" self.text = "test_urllib: %s\n" % self.__class__.__name__ - FILE = file(test_support.TESTFN, 'wb') + FILE = open(test_support.TESTFN, 'wb') try: FILE.write(self.text) finally: @@ -139,7 +139,7 @@ self.registerFileForCleanUp(test_support.TESTFN) self.text = 'testing urllib.urlretrieve' try: - FILE = file(test_support.TESTFN, 'wb') + FILE = open(test_support.TESTFN, 'wb') FILE.write(self.text) FILE.close() finally: @@ -192,7 +192,7 @@ self.assertEqual(second_temp, result[0]) self.assert_(os.path.exists(second_temp), "copy of the file was not " "made") - FILE = file(second_temp, 'rb') + FILE = open(second_temp, 'rb') try: text = FILE.read() FILE.close() Modified: python/branches/p3yk/Lib/test/test_urllibnet.py ============================================================================== --- python/branches/p3yk/Lib/test/test_urllibnet.py (original) +++ python/branches/p3yk/Lib/test/test_urllibnet.py Thu Aug 24 04:58:11 2006 @@ -120,7 +120,7 @@ file_location,info = urllib.urlretrieve("http://www.python.org/") self.assert_(os.path.exists(file_location), "file location returned by" " urlretrieve is not a valid path") - FILE = file(file_location) + FILE = open(file_location) try: self.assert_(FILE.read(), "reading from the file location returned" " by urlretrieve failed") @@ -134,7 +134,7 @@ test_support.TESTFN) self.assertEqual(file_location, test_support.TESTFN) self.assert_(os.path.exists(file_location)) - FILE = file(file_location) + FILE = open(file_location) try: self.assert_(FILE.read(), "reading from temporary file failed") finally: Modified: python/branches/p3yk/Lib/webbrowser.py ============================================================================== --- python/branches/p3yk/Lib/webbrowser.py (original) +++ python/branches/p3yk/Lib/webbrowser.py Thu Aug 24 04:58:11 2006 @@ -210,7 +210,7 @@ cmdline = [self.name] + raise_opt + args if remote or self.background: - inout = file(os.devnull, "r+") + inout = open(os.devnull, "r+") else: # for TTY browsers, we need stdin/out inout = None @@ -334,7 +334,7 @@ else: action = "openURL" - devnull = file(os.devnull, "r+") + devnull = open(os.devnull, "r+") # if possible, put browser in separate process group, so # keyboard interrupts don't affect browser as well as Python setsid = getattr(os, 'setsid', None) From python-3000-checkins at python.org Thu Aug 24 05:53:28 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Thu, 24 Aug 2006 05:53:28 +0200 (CEST) Subject: [Python-3000-checkins] r51538 - in python/branches/p3yk: Grammar/Grammar Lib/bsddb/dbtables.py Lib/bsddb/test/test_compat.py Lib/bsddb/test/test_recno.py Lib/bsddb/test/test_thread.py Lib/compiler/transformer.py Lib/email/base64mime.py Lib/email/charset.py Lib/email/generator.py Lib/email/header.py Lib/email/message.py Lib/email/quoprimime.py Lib/email/test/test_email.py Lib/email/test/test_email_renamed.py Lib/logging/__init__.py Lib/plat-mac/FrameWork.py Lib/plat-mac/buildtools.py Lib/plat-mac/cfmfile.py Lib/plat-mac/gensuitemodule.py Lib/plat-mac/macerrors.py Lib/test/output/test_class Lib/test/output/test_tokenize Lib/test/test_bsddb3.py Lib/test/test_class.py Lib/test/test_funcattrs.py Lib/test/test_grammar.py Lib/test/test_socket.py Lib/test/test_wsgiref.py Lib/test/tokenize_tests.txt Lib/tokenize.py Lib/webbrowser.py Lib/wsgiref/headers.py Lib/wsgiref/util.py Parser/tokenizer.c Python/ast.c Python/graminit.c Message-ID: <20060824035328.A0C2D1E4004@bag.python.org> Author: guido.van.rossum Date: Thu Aug 24 05:53:23 2006 New Revision: 51538 Modified: python/branches/p3yk/Grammar/Grammar python/branches/p3yk/Lib/bsddb/dbtables.py python/branches/p3yk/Lib/bsddb/test/test_compat.py python/branches/p3yk/Lib/bsddb/test/test_recno.py python/branches/p3yk/Lib/bsddb/test/test_thread.py python/branches/p3yk/Lib/compiler/transformer.py python/branches/p3yk/Lib/email/base64mime.py python/branches/p3yk/Lib/email/charset.py python/branches/p3yk/Lib/email/generator.py python/branches/p3yk/Lib/email/header.py python/branches/p3yk/Lib/email/message.py python/branches/p3yk/Lib/email/quoprimime.py python/branches/p3yk/Lib/email/test/test_email.py python/branches/p3yk/Lib/email/test/test_email_renamed.py python/branches/p3yk/Lib/logging/__init__.py python/branches/p3yk/Lib/plat-mac/FrameWork.py python/branches/p3yk/Lib/plat-mac/buildtools.py python/branches/p3yk/Lib/plat-mac/cfmfile.py python/branches/p3yk/Lib/plat-mac/gensuitemodule.py python/branches/p3yk/Lib/plat-mac/macerrors.py python/branches/p3yk/Lib/test/output/test_class python/branches/p3yk/Lib/test/output/test_tokenize python/branches/p3yk/Lib/test/test_bsddb3.py python/branches/p3yk/Lib/test/test_class.py python/branches/p3yk/Lib/test/test_funcattrs.py python/branches/p3yk/Lib/test/test_grammar.py python/branches/p3yk/Lib/test/test_socket.py python/branches/p3yk/Lib/test/test_wsgiref.py python/branches/p3yk/Lib/test/tokenize_tests.txt python/branches/p3yk/Lib/tokenize.py python/branches/p3yk/Lib/webbrowser.py python/branches/p3yk/Lib/wsgiref/headers.py python/branches/p3yk/Lib/wsgiref/util.py python/branches/p3yk/Parser/tokenizer.c python/branches/p3yk/Python/ast.c python/branches/p3yk/Python/graminit.c Log: Killed the <> operator. You must now use !=. Opportunistically also fixed one or two places where '<> None' should be 'is not None' and where 'type(x) <> y' should be 'not isinstance(x, y)'. Modified: python/branches/p3yk/Grammar/Grammar ============================================================================== --- python/branches/p3yk/Grammar/Grammar (original) +++ python/branches/p3yk/Grammar/Grammar Thu Aug 24 05:53:23 2006 @@ -90,7 +90,7 @@ and_test: not_test ('and' not_test)* not_test: 'not' not_test | comparison comparison: expr (comp_op expr)* -comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not' +comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not' expr: xor_expr ('|' xor_expr)* xor_expr: and_expr ('^' and_expr)* and_expr: shift_expr ('&' shift_expr)* Modified: python/branches/p3yk/Lib/bsddb/dbtables.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/dbtables.py (original) +++ python/branches/p3yk/Lib/bsddb/dbtables.py Thu Aug 24 05:53:23 2006 @@ -453,7 +453,7 @@ # error dataitem = None dataitem = mappings[column](dataitem) - if dataitem <> None: + if dataitem != None: self.db.put( _data_key(table, column, rowid), dataitem, txn=txn) Modified: python/branches/p3yk/Lib/bsddb/test/test_compat.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_compat.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_compat.py Thu Aug 24 05:53:23 2006 @@ -120,7 +120,7 @@ try: rec = f.next() except KeyError: - assert rec == f.last(), 'Error, last <> last!' + assert rec == f.last(), 'Error, last != last!' f.previous() break if verbose: Modified: python/branches/p3yk/Lib/bsddb/test/test_recno.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_recno.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_recno.py Thu Aug 24 05:53:23 2006 @@ -30,7 +30,7 @@ try: os.remove(self.filename) except OSError, e: - if e.errno <> errno.EEXIST: raise + if e.errno != errno.EEXIST: raise def test01_basic(self): d = db.DB() Modified: python/branches/p3yk/Lib/bsddb/test/test_thread.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_thread.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_thread.py Thu Aug 24 05:53:23 2006 @@ -58,7 +58,7 @@ try: os.mkdir(homeDir) except OSError, e: - if e.errno <> errno.EEXIST: raise + if e.errno != errno.EEXIST: raise self.env = db.DBEnv() self.setEnvOpts() self.env.open(homeDir, self.envflags | db.DB_CREATE) Modified: python/branches/p3yk/Lib/compiler/transformer.py ============================================================================== --- python/branches/p3yk/Lib/compiler/transformer.py (original) +++ python/branches/p3yk/Lib/compiler/transformer.py Thu Aug 24 05:53:23 2006 @@ -618,7 +618,7 @@ for i in range(2, len(nodelist), 2): nl = nodelist[i-1] - # comp_op: '<' | '>' | '=' | '>=' | '<=' | '<>' | '!=' | '==' + # comp_op: '<' | '>' | '=' | '>=' | '<=' | '!=' | '==' # | 'in' | 'not' 'in' | 'is' | 'is' 'not' n = nl[1] if n[0] == token.NAME: @@ -1396,7 +1396,7 @@ symbol.power, ] -# comp_op: '<' | '>' | '=' | '>=' | '<=' | '<>' | '!=' | '==' +# comp_op: '<' | '>' | '=' | '>=' | '<=' | '!=' | '==' # | 'in' | 'not' 'in' | 'is' | 'is' 'not' _cmp_types = { token.LESS : '<', Modified: python/branches/p3yk/Lib/email/base64mime.py ============================================================================== --- python/branches/p3yk/Lib/email/base64mime.py (original) +++ python/branches/p3yk/Lib/email/base64mime.py Thu Aug 24 05:53:23 2006 @@ -146,7 +146,7 @@ # BAW: should encode() inherit b2a_base64()'s dubious behavior in # adding a newline to the encoded string? enc = b2a_base64(s[i:i + max_unencoded]) - if enc.endswith(NL) and eol <> NL: + if enc.endswith(NL) and eol != NL: enc = enc[:-1] + eol encvec.append(enc) return EMPTYSTRING.join(encvec) Modified: python/branches/p3yk/Lib/email/charset.py ============================================================================== --- python/branches/p3yk/Lib/email/charset.py (original) +++ python/branches/p3yk/Lib/email/charset.py Thu Aug 24 05:53:23 2006 @@ -250,7 +250,7 @@ Returns "base64" if self.body_encoding is BASE64. Returns "7bit" otherwise. """ - assert self.body_encoding <> SHORTEST + assert self.body_encoding != SHORTEST if self.body_encoding == QP: return 'quoted-printable' elif self.body_encoding == BASE64: @@ -260,7 +260,7 @@ def convert(self, s): """Convert a string from the input_codec to the output_codec.""" - if self.input_codec <> self.output_codec: + if self.input_codec != self.output_codec: return unicode(s, self.input_codec).encode(self.output_codec) else: return s Modified: python/branches/p3yk/Lib/email/generator.py ============================================================================== --- python/branches/p3yk/Lib/email/generator.py (original) +++ python/branches/p3yk/Lib/email/generator.py Thu Aug 24 05:53:23 2006 @@ -211,7 +211,7 @@ # doesn't preserve newlines/continuations in headers. This is no big # deal in practice, but turns out to be inconvenient for the unittest # suite. - if msg.get_boundary() <> boundary: + if msg.get_boundary() != boundary: msg.set_boundary(boundary) # If there's a preamble, write it out, with a trailing CRLF if msg.preamble is not None: Modified: python/branches/p3yk/Lib/email/header.py ============================================================================== --- python/branches/p3yk/Lib/email/header.py (original) +++ python/branches/p3yk/Lib/email/header.py Thu Aug 24 05:53:23 2006 @@ -248,7 +248,7 @@ elif not isinstance(charset, Charset): charset = Charset(charset) # If the charset is our faux 8bit charset, leave the string unchanged - if charset <> '8bit': + if charset != '8bit': # We need to test that the string can be converted to unicode and # back to a byte string, given the input and output codecs of the # charset. @@ -454,7 +454,7 @@ # If this part is longer than maxlen and we aren't already # splitting on whitespace, try to recursively split this line # on whitespace. - if partlen > maxlen and ch <> ' ': + if partlen > maxlen and ch != ' ': subl = _split_ascii(part, maxlen, restlen, continuation_ws, ' ') lines.extend(subl[:-1]) Modified: python/branches/p3yk/Lib/email/message.py ============================================================================== --- python/branches/p3yk/Lib/email/message.py (original) +++ python/branches/p3yk/Lib/email/message.py Thu Aug 24 05:53:23 2006 @@ -252,7 +252,7 @@ charset=charset.get_output_charset()) else: self.set_param('charset', charset.get_output_charset()) - if str(charset) <> charset.get_output_charset(): + if str(charset) != charset.get_output_charset(): self._payload = charset.body_encode(self._payload) if 'Content-Transfer-Encoding' not in self: cte = charset.get_body_encoding() @@ -301,7 +301,7 @@ name = name.lower() newheaders = [] for k, v in self._headers: - if k.lower() <> name: + if k.lower() != name: newheaders.append((k, v)) self._headers = newheaders @@ -438,7 +438,7 @@ return self.get_default_type() ctype = paramre.split(value)[0].lower().strip() # RFC 2045, section 5.2 says if its invalid, use text/plain - if ctype.count('/') <> 1: + if ctype.count('/') != 1: return 'text/plain' return ctype @@ -601,7 +601,7 @@ ctype = append_param else: ctype = SEMISPACE.join([ctype, append_param]) - if ctype <> self.get(header): + if ctype != self.get(header): del self[header] self[header] = ctype @@ -617,13 +617,13 @@ return new_ctype = '' for p, v in self.get_params(header=header, unquote=requote): - if p.lower() <> param.lower(): + if p.lower() != param.lower(): if not new_ctype: new_ctype = _formatparam(p, v, requote) else: new_ctype = SEMISPACE.join([new_ctype, _formatparam(p, v, requote)]) - if new_ctype <> self.get(header): + if new_ctype != self.get(header): del self[header] self[header] = new_ctype Modified: python/branches/p3yk/Lib/email/quoprimime.py ============================================================================== --- python/branches/p3yk/Lib/email/quoprimime.py (original) +++ python/branches/p3yk/Lib/email/quoprimime.py Thu Aug 24 05:53:23 2006 @@ -287,7 +287,7 @@ n = len(line) while i < n: c = line[i] - if c <> '=': + if c != '=': decoded += c i += 1 # Otherwise, c == "=". Are we at the end of the line? If so, add Modified: python/branches/p3yk/Lib/email/test/test_email.py ============================================================================== --- python/branches/p3yk/Lib/email/test/test_email.py (original) +++ python/branches/p3yk/Lib/email/test/test_email.py Thu Aug 24 05:53:23 2006 @@ -51,7 +51,7 @@ class TestEmailBase(unittest.TestCase): def ndiffAssertEqual(self, first, second): """Like failUnlessEqual except use ndiff for readable output.""" - if first <> second: + if first != second: sfirst = str(first) ssecond = str(second) diff = difflib.ndiff(sfirst.splitlines(), ssecond.splitlines()) @@ -2726,7 +2726,7 @@ # Try a charset with None body encoding c = Charset('us-ascii') eq('hello world', c.body_encode('hello world')) - # Try the convert argument, where input codec <> output codec + # Try the convert argument, where input codec != output codec c = Charset('euc-jp') # With apologies to Tokio Kikuchi ;) try: Modified: python/branches/p3yk/Lib/email/test/test_email_renamed.py ============================================================================== --- python/branches/p3yk/Lib/email/test/test_email_renamed.py (original) +++ python/branches/p3yk/Lib/email/test/test_email_renamed.py Thu Aug 24 05:53:23 2006 @@ -52,7 +52,7 @@ class TestEmailBase(unittest.TestCase): def ndiffAssertEqual(self, first, second): """Like failUnlessEqual except use ndiff for readable output.""" - if first <> second: + if first != second: sfirst = str(first) ssecond = str(second) diff = difflib.ndiff(sfirst.splitlines(), ssecond.splitlines()) @@ -2732,7 +2732,7 @@ # Try a charset with None body encoding c = Charset('us-ascii') eq('hello world', c.body_encode('hello world')) - # Try the convert argument, where input codec <> output codec + # Try the convert argument, where input codec != output codec c = Charset('euc-jp') # With apologies to Tokio Kikuchi ;) try: Modified: python/branches/p3yk/Lib/logging/__init__.py ============================================================================== --- python/branches/p3yk/Lib/logging/__init__.py (original) +++ python/branches/p3yk/Lib/logging/__init__.py Thu Aug 24 05:53:23 2006 @@ -912,7 +912,8 @@ """ #for c in ph.loggers: for c in ph.loggerMap.keys(): - if string.find(c.parent.name, alogger.name) <> 0: + # XXX Is the following correct? Shouldn't it be >= 0? + if string.find(c.parent.name, alogger.name) != 0: alogger.parent = c.parent c.parent = alogger Modified: python/branches/p3yk/Lib/plat-mac/FrameWork.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/FrameWork.py (original) +++ python/branches/p3yk/Lib/plat-mac/FrameWork.py Thu Aug 24 05:53:23 2006 @@ -602,7 +602,7 @@ def dispatch(self, id, item, window, event): title, shortcut, callback, mtype = self.items[item-1] if callback: - if not self.bar.parent or type(callback) <> types.StringType: + if not self.bar.parent or not isinstance(callback, str): menuhandler = callback else: # callback is string @@ -748,7 +748,7 @@ self.parent = parent def open(self, bounds=(40, 40, 400, 400), resid=None): - if resid <> None: + if resid is not None: self.wid = GetNewWindow(resid, -1) else: self.wid = NewWindow(bounds, self.__class__.__name__, 1, @@ -826,7 +826,7 @@ # If we're not frontmost, select ourselves and wait for # the activate event. # - if MyFrontWindow() <> window: + if MyFrontWindow() != window: window.SelectWindow() return # We are. Handle the event. @@ -875,7 +875,7 @@ if DEBUG: print "control hit in", window, "on", control, "; pcode =", pcode def do_inContent(self, partcode, window, event): - if MyFrontWindow() <> window: + if MyFrontWindow() != window: window.SelectWindow() return (what, message, when, where, modifiers) = event Modified: python/branches/p3yk/Lib/plat-mac/buildtools.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/buildtools.py (original) +++ python/branches/p3yk/Lib/plat-mac/buildtools.py Thu Aug 24 05:53:23 2006 @@ -192,7 +192,7 @@ 'icl8', 'ics4', 'ics8', 'ICN#', 'ics#'] if not copy_codefragment: skiptypes.append('cfrg') -## skipowner = (ownertype <> None) +## skipowner = (ownertype != None) # Copy the resources from the template Modified: python/branches/p3yk/Lib/plat-mac/cfmfile.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/cfmfile.py (original) +++ python/branches/p3yk/Lib/plat-mac/cfmfile.py Thu Aug 24 05:53:23 2006 @@ -73,7 +73,7 @@ Res.CloseResFile(resref) Res.UseResFile(currentresref) self.parse(data) - if self.version <> 1: + if self.version != 1: raise error, "unknown 'cfrg' resource format" def parse(self, data): @@ -143,7 +143,7 @@ return data def getfragment(self): - if self.where <> 1: + if self.where != 1: raise error, "can't read fragment, unsupported location" f = open(self.path, "rb") f.seek(self.offset) @@ -155,7 +155,7 @@ return frag def copydata(self, outfile): - if self.where <> 1: + if self.where != 1: raise error, "can't read fragment, unsupported location" infile = open(self.path, "rb") if self.length == 0: Modified: python/branches/p3yk/Lib/plat-mac/gensuitemodule.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/gensuitemodule.py (original) +++ python/branches/p3yk/Lib/plat-mac/gensuitemodule.py Thu Aug 24 05:53:23 2006 @@ -169,7 +169,7 @@ aete = decode(data, verbose) aetelist.append((aete, res.GetResInfo())) finally: - if rf <> cur: + if rf != cur: CloseResFile(rf) UseResFile(cur) # switch back (needed for dialogs in Python) @@ -332,7 +332,7 @@ def getalign(f): if f.tell() & 1: c = f.read(1) - ##if c <> '\0': + ##if c != '\0': ## print align:', repr(c) def getlist(f, description, getitem): @@ -779,7 +779,7 @@ if is_enum(a[2]): kname = a[1] ename = a[2][0] - if ename <> '****': + if ename != '****': fp.write(" aetools.enumsubst(_arguments, %r, _Enum_%s)\n" % (kname, identify(ename))) self.enumsneeded[ename] = 1 @@ -810,7 +810,7 @@ for a in arguments: if is_enum(a[2]): ename = a[2][0] - if ename <> '****': + if ename != '****': self.enumsneeded[ename] = 1 # Modified: python/branches/p3yk/Lib/plat-mac/macerrors.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/macerrors.py (original) +++ python/branches/p3yk/Lib/plat-mac/macerrors.py Thu Aug 24 05:53:23 2006 @@ -1574,7 +1574,7 @@ smFHBlockRdErr = -310 #Error occurred during _sGetFHeader. smBLFieldBad = -309 #ByteLanes field was bad. smUnExBusErr = -308 #Unexpected BusError -smResrvErr = -307 #Fatal reserved error. Resreved field <> 0. +smResrvErr = -307 #Fatal reserved error. Resreved field != 0. smNosInfoArray = -306 #No sInfoArray. Memory Mgr error. smDisabledSlot = -305 #This slot is disabled (-305 use to be smLWTstBad) smNoDir = -304 #Directory offset is Nil Modified: python/branches/p3yk/Lib/test/output/test_class ============================================================================== --- python/branches/p3yk/Lib/test/output/test_class (original) +++ python/branches/p3yk/Lib/test/output/test_class Thu Aug 24 05:53:23 2006 @@ -55,12 +55,10 @@ __lt__: (1,) __gt__: (1,) __ne__: (1,) -__ne__: (1,) __eq__: (1,) __gt__: (1,) __lt__: (1,) __ne__: (1,) -__ne__: (1,) __del__: () __getattr__: ('spam',) __setattr__: ('eggs', 'spam, spam, spam and ham') Modified: python/branches/p3yk/Lib/test/output/test_tokenize ============================================================================== --- python/branches/p3yk/Lib/test/output/test_tokenize (original) +++ python/branches/p3yk/Lib/test/output/test_tokenize Thu Aug 24 05:53:23 2006 @@ -108,11 +108,11 @@ 37,0-37,1: NL '\n' 38,0-38,20: COMMENT '# Ordinary integers\n' 39,0-39,4: NUMBER '0xff' -39,5-39,7: OP '<>' +39,5-39,7: OP '!=' 39,8-39,11: NUMBER '255' 39,11-39,12: NEWLINE '\n' 40,0-40,4: NUMBER '0377' -40,5-40,7: OP '<>' +40,5-40,7: OP '!=' 40,8-40,11: NUMBER '255' 40,11-40,12: NEWLINE '\n' 41,0-41,10: NUMBER '2147483647' @@ -484,7 +484,7 @@ 149,2-149,3: OP ',' 149,4-149,5: NAME 'y' 149,5-149,6: OP ')' -149,7-149,9: OP '<>' +149,7-149,9: OP '!=' 149,10-149,11: OP '(' 149,11-149,12: OP '{' 149,12-149,15: STRING "'a'" @@ -513,7 +513,7 @@ 152,21-152,22: NUMBER '1' 152,23-152,25: OP '<=' 152,26-152,27: NUMBER '1' -152,28-152,30: OP '<>' +152,28-152,30: OP '!=' 152,31-152,32: NUMBER '1' 152,33-152,35: OP '!=' 152,36-152,37: NUMBER '1' Modified: python/branches/p3yk/Lib/test/test_bsddb3.py ============================================================================== --- python/branches/p3yk/Lib/test/test_bsddb3.py (original) +++ python/branches/p3yk/Lib/test/test_bsddb3.py Thu Aug 24 05:53:23 2006 @@ -8,7 +8,7 @@ # When running as a script instead of within the regrtest framework, skip the # requires test, since it's obvious we want to run them. -if __name__ <> '__main__': +if __name__ != '__main__': requires('bsddb') verbose = False Modified: python/branches/p3yk/Lib/test/test_class.py ============================================================================== --- python/branches/p3yk/Lib/test/test_class.py (original) +++ python/branches/p3yk/Lib/test/test_class.py Thu Aug 24 05:53:23 2006 @@ -244,12 +244,10 @@ testme == 1 testme < 1 testme > 1 -testme <> 1 testme != 1 1 == testme 1 < testme 1 > testme -1 <> testme 1 != testme # This test has to be last (duh.) Modified: python/branches/p3yk/Lib/test/test_funcattrs.py ============================================================================== --- python/branches/p3yk/Lib/test/test_funcattrs.py (original) +++ python/branches/p3yk/Lib/test/test_funcattrs.py Thu Aug 24 05:53:23 2006 @@ -19,16 +19,16 @@ except AttributeError: pass else: raise TestFailed, 'expected AttributeError' -if b.__dict__ <> {}: +if b.__dict__ != {}: raise TestFailed, 'expected unassigned func.__dict__ to be {}' b.publish = 1 -if b.publish <> 1: +if b.publish != 1: raise TestFailed, 'function attribute not set to expected value' docstring = 'its docstring' b.__doc__ = docstring -if b.__doc__ <> docstring: +if b.__doc__ != docstring: raise TestFailed, 'problem with setting __doc__ attribute' if 'publish' not in dir(b): @@ -49,7 +49,7 @@ b.__dict__ = d if b.func_dict is not d: raise TestFailed, 'func.__dict__ assignment to dictionary failed' -if b.hello <> 'world': +if b.hello != 'world': raise TestFailed, 'attribute after func.__dict__ assignment failed' f1 = F() @@ -75,13 +75,13 @@ # But setting it explicitly on the underlying function object is okay. F.a.im_func.publish = 1 -if F.a.publish <> 1: +if F.a.publish != 1: raise TestFailed, 'unbound method attribute not set to expected value' -if f1.a.publish <> 1: +if f1.a.publish != 1: raise TestFailed, 'bound method attribute access did not work' -if f2.a.publish <> 1: +if f2.a.publish != 1: raise TestFailed, 'bound method attribute access did not work' if 'publish' not in dir(F.a): @@ -117,7 +117,7 @@ F.a.im_func.__dict__ = {'one': 11, 'two': 22, 'three': 33} -if f1.a.two <> 22: +if f1.a.two != 22: raise TestFailed, 'setting __dict__' from UserDict import UserDict @@ -128,7 +128,7 @@ except (AttributeError, TypeError): pass else: raise TestFailed -if f2.a.one <> f1.a.one <> F.a.one <> 11: +if f2.a.one != f1.a.one != F.a.one != 11: raise TestFailed # im_func may not be a Python method! @@ -136,7 +136,7 @@ F.id = new.instancemethod(id, None, F) eff = F() -if eff.id() <> id(eff): +if eff.id() != id(eff): raise TestFailed try: Modified: python/branches/p3yk/Lib/test/test_grammar.py ============================================================================== --- python/branches/p3yk/Lib/test/test_grammar.py (original) +++ python/branches/p3yk/Lib/test/test_grammar.py Thu Aug 24 05:53:23 2006 @@ -412,7 +412,7 @@ continue except: raise - if count > 2 or big_hippo <> 1: + if count > 2 or big_hippo != 1: print "continue then break in try/except in loop broken!" test_break_continue_loop() @@ -586,12 +586,11 @@ print 'comparison' ### comparison: expr (comp_op expr)* -### comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not' +### comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not' if 1: pass x = (1 == 1) if 1 == 1: pass if 1 != 1: pass -if 1 <> 1: pass if 1 < 1: pass if 1 > 1: pass if 1 <= 1: pass @@ -600,7 +599,7 @@ if 1 is not 1: pass if 1 in (): pass if 1 not in (): pass -if 1 < 1 > 1 == 1 >= 1 <= 1 <> 1 != 1 in 1 not in 1 is 1 is not 1: pass +if 1 < 1 > 1 == 1 >= 1 <= 1 != 1 in 1 not in 1 is 1 is not 1: pass print 'binary mask ops' x = 1 & 1 Modified: python/branches/p3yk/Lib/test/test_socket.py ============================================================================== --- python/branches/p3yk/Lib/test/test_socket.py (original) +++ python/branches/p3yk/Lib/test/test_socket.py Thu Aug 24 05:53:23 2006 @@ -285,7 +285,7 @@ orig = sys.getrefcount(__name__) socket.getnameinfo(__name__,0) except SystemError: - if sys.getrefcount(__name__) <> orig: + if sys.getrefcount(__name__) != orig: self.fail("socket.getnameinfo loses a reference") def testInterpreterCrash(self): Modified: python/branches/p3yk/Lib/test/test_wsgiref.py ============================================================================== --- python/branches/p3yk/Lib/test/test_wsgiref.py (original) +++ python/branches/p3yk/Lib/test/test_wsgiref.py Thu Aug 24 05:53:23 2006 @@ -515,7 +515,7 @@ "Content-Length: %d\r\n" "\r\n%s" % (h.error_status,len(h.error_body),h.error_body)) - self.failUnless(h.stderr.getvalue().find("AssertionError")<>-1) + self.failUnless("AssertionError" in h.stderr.getvalue()) def testErrorAfterOutput(self): MSG = "Some output has been sent" @@ -528,7 +528,7 @@ self.assertEqual(h.stdout.getvalue(), "Status: 200 OK\r\n" "\r\n"+MSG) - self.failUnless(h.stderr.getvalue().find("AssertionError")<>-1) + self.failUnless("AssertionError" in h.stderr.getvalue()) def testHeaderFormats(self): Modified: python/branches/p3yk/Lib/test/tokenize_tests.txt ============================================================================== --- python/branches/p3yk/Lib/test/tokenize_tests.txt (original) +++ python/branches/p3yk/Lib/test/tokenize_tests.txt Thu Aug 24 05:53:23 2006 @@ -36,8 +36,8 @@ x = 0 # Ordinary integers -0xff <> 255 -0377 <> 255 +0xff != 255 +0377 != 255 2147483647 != 017777777777 -2147483647-1 != 020000000000 037777777777 != -1 @@ -146,10 +146,10 @@ def d22(a, b, c=1, d=2): pass def d01v(a=1, *restt, **restd): pass -(x, y) <> ({'a':1}, {'b':2}) +(x, y) != ({'a':1}, {'b':2}) # comparison -if 1 < 1 > 1 == 1 >= 1 <= 1 <> 1 != 1 in 1 not in 1 is 1 is not 1: pass +if 1 < 1 > 1 == 1 >= 1 <= 1 != 1 != 1 in 1 not in 1 is 1 is not 1: pass # binary x = 1 & 1 Modified: python/branches/p3yk/Lib/tokenize.py ============================================================================== --- python/branches/p3yk/Lib/tokenize.py (original) +++ python/branches/p3yk/Lib/tokenize.py Thu Aug 24 05:53:23 2006 @@ -77,7 +77,7 @@ # Because of leftmost-then-longest match semantics, be sure to put the # longest operators first (e.g., if = came before ==, == would get # recognized as two instances of =). -Operator = group(r"\*\*=?", r">>=?", r"<<=?", r"<>", r"!=", +Operator = group(r"\*\*=?", r">>=?", r"<<=?", r"!=", r"//=?", r"[+\-*/%&|^=<>]=?", r"~") Modified: python/branches/p3yk/Lib/webbrowser.py ============================================================================== --- python/branches/p3yk/Lib/webbrowser.py (original) +++ python/branches/p3yk/Lib/webbrowser.py Thu Aug 24 05:53:23 2006 @@ -627,7 +627,7 @@ for o, a in opts: if o == '-n': new_win = 1 elif o == '-t': new_win = 2 - if len(args) <> 1: + if len(args) != 1: print >>sys.stderr, usage sys.exit(1) Modified: python/branches/p3yk/Lib/wsgiref/headers.py ============================================================================== --- python/branches/p3yk/Lib/wsgiref/headers.py (original) +++ python/branches/p3yk/Lib/wsgiref/headers.py Thu Aug 24 05:53:23 2006 @@ -63,7 +63,7 @@ Does *not* raise an exception if the header is missing. """ name = name.lower() - self._headers[:] = [kv for kv in self._headers if kv[0].lower()<>name] + self._headers[:] = [kv for kv in self._headers if kv[0].lower() != name] def __getitem__(self,name): """Get the first header value for 'name' Modified: python/branches/p3yk/Lib/wsgiref/util.py ============================================================================== --- python/branches/p3yk/Lib/wsgiref/util.py (original) +++ python/branches/p3yk/Lib/wsgiref/util.py Thu Aug 24 05:53:23 2006 @@ -98,7 +98,7 @@ return None path_parts = path_info.split('/') - path_parts[1:-1] = [p for p in path_parts[1:-1] if p and p<>'.'] + path_parts[1:-1] = [p for p in path_parts[1:-1] if p and p != '.'] name = path_parts[1] del path_parts[1] Modified: python/branches/p3yk/Parser/tokenizer.c ============================================================================== --- python/branches/p3yk/Parser/tokenizer.c (original) +++ python/branches/p3yk/Parser/tokenizer.c Thu Aug 24 05:53:23 2006 @@ -982,7 +982,6 @@ break; case '<': switch (c2) { - case '>': return NOTEQUAL; case '=': return LESSEQUAL; case '<': return LEFTSHIFT; } Modified: python/branches/p3yk/Python/ast.c ============================================================================== --- python/branches/p3yk/Python/ast.c (original) +++ python/branches/p3yk/Python/ast.c Thu Aug 24 05:53:23 2006 @@ -478,7 +478,7 @@ static cmpop_ty ast_for_comp_op(const node *n) { - /* comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is' + /* comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is' |'is' 'not' */ REQ(n, comp_op); Modified: python/branches/p3yk/Python/graminit.c ============================================================================== --- python/branches/p3yk/Python/graminit.c (original) +++ python/branches/p3yk/Python/graminit.c Thu Aug 24 05:53:23 2006 @@ -1107,17 +1107,16 @@ {1, arcs_51_0}, {2, arcs_51_1}, }; -static arc arcs_52_0[10] = { +static arc arcs_52_0[9] = { {117, 1}, {118, 1}, {119, 1}, {120, 1}, {121, 1}, {122, 1}, - {123, 1}, {83, 1}, {114, 2}, - {124, 3}, + {123, 3}, }; static arc arcs_52_1[1] = { {0, 1}, @@ -1130,16 +1129,16 @@ {0, 3}, }; static state states_52[4] = { - {10, arcs_52_0}, + {9, arcs_52_0}, {1, arcs_52_1}, {1, arcs_52_2}, {2, arcs_52_3}, }; static arc arcs_53_0[1] = { - {125, 1}, + {124, 1}, }; static arc arcs_53_1[2] = { - {126, 0}, + {125, 0}, {0, 1}, }; static state states_53[2] = { @@ -1147,10 +1146,10 @@ {2, arcs_53_1}, }; static arc arcs_54_0[1] = { - {127, 1}, + {126, 1}, }; static arc arcs_54_1[2] = { - {128, 0}, + {127, 0}, {0, 1}, }; static state states_54[2] = { @@ -1158,10 +1157,10 @@ {2, arcs_54_1}, }; static arc arcs_55_0[1] = { - {129, 1}, + {128, 1}, }; static arc arcs_55_1[2] = { - {130, 0}, + {129, 0}, {0, 1}, }; static state states_55[2] = { @@ -1169,10 +1168,10 @@ {2, arcs_55_1}, }; static arc arcs_56_0[1] = { - {131, 1}, + {130, 1}, }; static arc arcs_56_1[3] = { - {132, 0}, + {131, 0}, {57, 0}, {0, 1}, }; @@ -1181,11 +1180,11 @@ {3, arcs_56_1}, }; static arc arcs_57_0[1] = { - {133, 1}, + {132, 1}, }; static arc arcs_57_1[3] = { + {133, 0}, {134, 0}, - {135, 0}, {0, 1}, }; static state states_57[2] = { @@ -1193,13 +1192,13 @@ {3, arcs_57_1}, }; static arc arcs_58_0[1] = { - {136, 1}, + {135, 1}, }; static arc arcs_58_1[5] = { {28, 0}, + {136, 0}, {137, 0}, {138, 0}, - {139, 0}, {0, 1}, }; static state states_58[2] = { @@ -1207,13 +1206,13 @@ {5, arcs_58_1}, }; static arc arcs_59_0[4] = { + {133, 1}, {134, 1}, - {135, 1}, - {140, 1}, - {141, 2}, + {139, 1}, + {140, 2}, }; static arc arcs_59_1[1] = { - {136, 2}, + {135, 2}, }; static arc arcs_59_2[1] = { {0, 2}, @@ -1224,15 +1223,15 @@ {1, arcs_59_2}, }; static arc arcs_60_0[1] = { - {142, 1}, + {141, 1}, }; static arc arcs_60_1[3] = { - {143, 1}, + {142, 1}, {29, 2}, {0, 1}, }; static arc arcs_60_2[1] = { - {136, 3}, + {135, 3}, }; static arc arcs_60_3[1] = { {0, 3}, @@ -1245,47 +1244,47 @@ }; static arc arcs_61_0[7] = { {13, 1}, - {145, 2}, - {148, 3}, - {151, 4}, + {144, 2}, + {147, 3}, + {150, 4}, {19, 5}, - {153, 5}, - {154, 6}, + {152, 5}, + {153, 6}, }; static arc arcs_61_1[3] = { {43, 7}, - {144, 7}, + {143, 7}, {15, 5}, }; static arc arcs_61_2[2] = { - {146, 8}, - {147, 5}, + {145, 8}, + {146, 5}, }; static arc arcs_61_3[2] = { - {149, 9}, - {150, 5}, + {148, 9}, + {149, 5}, }; static arc arcs_61_4[1] = { - {152, 10}, + {151, 10}, }; static arc arcs_61_5[1] = { {0, 5}, }; static arc arcs_61_6[2] = { - {154, 6}, + {153, 6}, {0, 6}, }; static arc arcs_61_7[1] = { {15, 5}, }; static arc arcs_61_8[1] = { - {147, 5}, + {146, 5}, }; static arc arcs_61_9[1] = { - {150, 5}, + {149, 5}, }; static arc arcs_61_10[1] = { - {151, 5}, + {150, 5}, }; static state states_61[11] = { {7, arcs_61_0}, @@ -1304,7 +1303,7 @@ {26, 1}, }; static arc arcs_62_1[3] = { - {155, 2}, + {154, 2}, {27, 3}, {0, 1}, }; @@ -1330,7 +1329,7 @@ {26, 1}, }; static arc arcs_63_1[3] = { - {156, 2}, + {155, 2}, {27, 3}, {0, 1}, }; @@ -1377,7 +1376,7 @@ }; static arc arcs_65_0[3] = { {13, 1}, - {145, 2}, + {144, 2}, {75, 3}, }; static arc arcs_65_1[2] = { @@ -1385,7 +1384,7 @@ {15, 5}, }; static arc arcs_65_2[1] = { - {157, 6}, + {156, 6}, }; static arc arcs_65_3[1] = { {19, 5}, @@ -1397,7 +1396,7 @@ {0, 5}, }; static arc arcs_65_6[1] = { - {147, 5}, + {146, 5}, }; static state states_65[7] = { {3, arcs_65_0}, @@ -1409,14 +1408,14 @@ {1, arcs_65_6}, }; static arc arcs_66_0[1] = { - {158, 1}, + {157, 1}, }; static arc arcs_66_1[2] = { {27, 2}, {0, 1}, }; static arc arcs_66_2[2] = { - {158, 1}, + {157, 1}, {0, 2}, }; static state states_66[3] = { @@ -1438,14 +1437,14 @@ }; static arc arcs_67_3[3] = { {26, 5}, - {159, 6}, + {158, 6}, {0, 3}, }; static arc arcs_67_4[1] = { {75, 6}, }; static arc arcs_67_5[2] = { - {159, 6}, + {158, 6}, {0, 5}, }; static arc arcs_67_6[1] = { @@ -1532,7 +1531,7 @@ {2, arcs_71_4}, }; static arc arcs_72_0[1] = { - {160, 1}, + {159, 1}, }; static arc arcs_72_1[1] = { {19, 2}, @@ -1568,7 +1567,7 @@ {1, arcs_72_7}, }; static arc arcs_73_0[3] = { - {161, 1}, + {160, 1}, {28, 2}, {29, 3}, }; @@ -1583,7 +1582,7 @@ {26, 6}, }; static arc arcs_73_4[4] = { - {161, 1}, + {160, 1}, {28, 2}, {29, 3}, {0, 4}, @@ -1612,7 +1611,7 @@ {26, 1}, }; static arc arcs_74_1[3] = { - {156, 2}, + {155, 2}, {25, 3}, {0, 1}, }; @@ -1629,8 +1628,8 @@ {1, arcs_74_3}, }; static arc arcs_75_0[2] = { - {155, 1}, - {163, 1}, + {154, 1}, + {162, 1}, }; static arc arcs_75_1[1] = { {0, 1}, @@ -1652,7 +1651,7 @@ {104, 4}, }; static arc arcs_76_4[2] = { - {162, 5}, + {161, 5}, {0, 4}, }; static arc arcs_76_5[1] = { @@ -1673,7 +1672,7 @@ {105, 2}, }; static arc arcs_77_2[2] = { - {162, 3}, + {161, 3}, {0, 2}, }; static arc arcs_77_3[1] = { @@ -1686,8 +1685,8 @@ {1, arcs_77_3}, }; static arc arcs_78_0[2] = { - {156, 1}, - {165, 1}, + {155, 1}, + {164, 1}, }; static arc arcs_78_1[1] = { {0, 1}, @@ -1709,7 +1708,7 @@ {106, 4}, }; static arc arcs_79_4[2] = { - {164, 5}, + {163, 5}, {0, 4}, }; static arc arcs_79_5[1] = { @@ -1730,7 +1729,7 @@ {105, 2}, }; static arc arcs_80_2[2] = { - {164, 3}, + {163, 3}, {0, 2}, }; static arc arcs_80_3[1] = { @@ -1764,7 +1763,7 @@ {1, arcs_82_1}, }; static arc arcs_83_0[1] = { - {167, 1}, + {166, 1}, }; static arc arcs_83_1[2] = { {9, 2}, @@ -1780,11 +1779,11 @@ }; static dfa dfas[84] = { {256, "single_input", 0, 3, states_0, - "\004\050\014\000\000\000\000\025\074\005\023\310\011\020\004\000\300\020\222\006\201"}, + "\004\050\014\000\000\000\000\025\074\005\023\310\011\020\004\000\140\010\111\203\100"}, {257, "file_input", 0, 2, states_1, - "\204\050\014\000\000\000\000\025\074\005\023\310\011\020\004\000\300\020\222\006\201"}, + "\204\050\014\000\000\000\000\025\074\005\023\310\011\020\004\000\140\010\111\203\100"}, {258, "eval_input", 0, 3, states_2, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\300\020\222\006\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\111\003\000"}, {259, "decorator", 0, 7, states_3, "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {260, "decorators", 0, 2, states_4, @@ -1800,13 +1799,13 @@ {265, "fplist", 0, 3, states_9, "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {266, "stmt", 0, 2, states_10, - "\000\050\014\000\000\000\000\025\074\005\023\310\011\020\004\000\300\020\222\006\201"}, + "\000\050\014\000\000\000\000\025\074\005\023\310\011\020\004\000\140\010\111\203\100"}, {267, "simple_stmt", 0, 4, states_11, - "\000\040\010\000\000\000\000\025\074\005\023\000\000\020\004\000\300\020\222\006\200"}, + "\000\040\010\000\000\000\000\025\074\005\023\000\000\020\004\000\140\010\111\003\100"}, {268, "small_stmt", 0, 2, states_12, - "\000\040\010\000\000\000\000\025\074\005\023\000\000\020\004\000\300\020\222\006\200"}, + "\000\040\010\000\000\000\000\025\074\005\023\000\000\020\004\000\140\010\111\003\100"}, {269, "expr_stmt", 0, 6, states_13, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\300\020\222\006\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\111\003\000"}, {270, "augassign", 0, 2, states_14, "\000\000\000\000\000\360\377\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {271, "print_stmt", 0, 9, states_15, @@ -1816,7 +1815,7 @@ {273, "pass_stmt", 0, 2, states_17, "\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {274, "flow_stmt", 0, 2, states_18, - "\000\000\000\000\000\000\000\000\074\000\000\000\000\000\000\000\000\000\000\000\200"}, + "\000\000\000\000\000\000\000\000\074\000\000\000\000\000\000\000\000\000\000\000\100"}, {275, "break_stmt", 0, 2, states_19, "\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000\000\000"}, {276, "continue_stmt", 0, 2, states_20, @@ -1824,7 +1823,7 @@ {277, "return_stmt", 0, 3, states_21, "\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000"}, {278, "yield_stmt", 0, 2, states_22, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200"}, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\100"}, {279, "raise_stmt", 0, 7, states_23, "\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000"}, {280, "import_stmt", 0, 2, states_24, @@ -1850,7 +1849,7 @@ {290, "assert_stmt", 0, 5, states_34, "\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000"}, {291, "compound_stmt", 0, 2, states_35, - "\000\010\004\000\000\000\000\000\000\000\000\310\011\000\000\000\000\000\000\000\001"}, + "\000\010\004\000\000\000\000\000\000\000\000\310\011\000\000\000\000\000\000\200\000"}, {292, "if_stmt", 0, 8, states_36, "\000\000\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000"}, {293, "while_stmt", 0, 8, states_37, @@ -1866,69 +1865,69 @@ {298, "except_clause", 0, 5, states_42, "\000\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000"}, {299, "suite", 0, 5, states_43, - "\004\040\010\000\000\000\000\025\074\005\023\000\000\020\004\000\300\020\222\006\200"}, + "\004\040\010\000\000\000\000\025\074\005\023\000\000\020\004\000\140\010\111\003\100"}, {300, "testlist_safe", 0, 5, states_44, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\300\020\222\006\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\111\003\000"}, {301, "old_test", 0, 2, states_45, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\300\020\222\006\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\111\003\000"}, {302, "old_lambdef", 0, 5, states_46, "\000\000\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000"}, {303, "test", 0, 6, states_47, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\300\020\222\006\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\111\003\000"}, {304, "or_test", 0, 2, states_48, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\004\000\300\020\222\006\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\004\000\140\010\111\003\000"}, {305, "and_test", 0, 2, states_49, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\004\000\300\020\222\006\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\004\000\140\010\111\003\000"}, {306, "not_test", 0, 3, states_50, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\004\000\300\020\222\006\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\004\000\140\010\111\003\000"}, {307, "comparison", 0, 2, states_51, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\300\020\222\006\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\140\010\111\003\000"}, {308, "comp_op", 0, 4, states_52, - "\000\000\000\000\000\000\000\000\000\000\010\000\000\000\344\037\000\000\000\000\000"}, + "\000\000\000\000\000\000\000\000\000\000\010\000\000\000\344\017\000\000\000\000\000"}, {309, "expr", 0, 2, states_53, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\300\020\222\006\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\140\010\111\003\000"}, {310, "xor_expr", 0, 2, states_54, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\300\020\222\006\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\140\010\111\003\000"}, {311, "and_expr", 0, 2, states_55, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\300\020\222\006\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\140\010\111\003\000"}, {312, "shift_expr", 0, 2, states_56, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\300\020\222\006\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\140\010\111\003\000"}, {313, "arith_expr", 0, 2, states_57, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\300\020\222\006\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\140\010\111\003\000"}, {314, "term", 0, 2, states_58, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\300\020\222\006\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\140\010\111\003\000"}, {315, "factor", 0, 3, states_59, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\300\020\222\006\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\140\010\111\003\000"}, {316, "power", 0, 4, states_60, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\222\006\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\111\003\000"}, {317, "atom", 0, 11, states_61, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\222\006\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\111\003\000"}, {318, "listmaker", 0, 5, states_62, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\300\020\222\006\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\111\003\000"}, {319, "testlist_gexp", 0, 5, states_63, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\300\020\222\006\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\111\003\000"}, {320, "lambdef", 0, 5, states_64, "\000\000\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000"}, {321, "trailer", 0, 7, states_65, - "\000\040\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\002\000\000"}, + "\000\040\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\001\000\000"}, {322, "subscriptlist", 0, 3, states_66, - "\000\040\050\000\000\000\000\000\000\010\000\000\000\020\004\000\300\020\222\006\000"}, + "\000\040\050\000\000\000\000\000\000\010\000\000\000\020\004\000\140\010\111\003\000"}, {323, "subscript", 0, 7, states_67, - "\000\040\050\000\000\000\000\000\000\010\000\000\000\020\004\000\300\020\222\006\000"}, + "\000\040\050\000\000\000\000\000\000\010\000\000\000\020\004\000\140\010\111\003\000"}, {324, "sliceop", 0, 3, states_68, "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {325, "exprlist", 0, 3, states_69, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\300\020\222\006\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\140\010\111\003\000"}, {326, "testlist", 0, 3, states_70, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\300\020\222\006\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\111\003\000"}, {327, "dictmaker", 0, 5, states_71, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\300\020\222\006\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\111\003\000"}, {328, "classdef", 0, 8, states_72, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\001"}, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200\000"}, {329, "arglist", 0, 8, states_73, - "\000\040\010\060\000\000\000\000\000\000\000\000\000\020\004\000\300\020\222\006\000"}, + "\000\040\010\060\000\000\000\000\000\000\000\000\000\020\004\000\140\010\111\003\000"}, {330, "argument", 0, 4, states_74, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\300\020\222\006\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\111\003\000"}, {331, "list_iter", 0, 2, states_75, "\000\000\000\000\000\000\000\000\000\000\000\210\000\000\000\000\000\000\000\000\000"}, {332, "list_for", 0, 6, states_76, @@ -1942,13 +1941,13 @@ {336, "gen_if", 0, 4, states_80, "\000\000\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000"}, {337, "testlist1", 0, 2, states_81, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\300\020\222\006\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\111\003\000"}, {338, "encoding_decl", 0, 2, states_82, "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {339, "yield_expr", 0, 3, states_83, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200"}, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\100"}, }; -static label labels[168] = { +static label labels[167] = { {0, "EMPTY"}, {256, 0}, {4, 0}, @@ -2072,7 +2071,6 @@ {31, 0}, {30, 0}, {29, 0}, - {29, 0}, {1, "is"}, {310, 0}, {18, 0}, @@ -2121,6 +2119,6 @@ grammar _PyParser_Grammar = { 84, dfas, - {168, labels}, + {167, labels}, 256 }; From python-3000-checkins at python.org Thu Aug 24 06:03:54 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Thu, 24 Aug 2006 06:03:54 +0200 (CEST) Subject: [Python-3000-checkins] r51539 - python/branches/p3yk/Lib/tarfile.py Message-ID: <20060824040354.40F571E4004@bag.python.org> Author: guido.van.rossum Date: Thu Aug 24 06:03:53 2006 New Revision: 51539 Modified: python/branches/p3yk/Lib/tarfile.py Log: Fix fallout from Anna's file -> open changes. Modified: python/branches/p3yk/Lib/tarfile.py ============================================================================== --- python/branches/p3yk/Lib/tarfile.py (original) +++ python/branches/p3yk/Lib/tarfile.py Thu Aug 24 06:03:53 2006 @@ -65,6 +65,8 @@ # from tarfile import * __all__ = ["TarFile", "TarInfo", "is_tarfile", "TarError"] +from __builtin__ import open as _open # Since 'open' is TarFile.open + #--------------------------------------------------------- # tar constants #--------------------------------------------------------- @@ -934,7 +936,7 @@ self.mode = {"r": "rb", "a": "r+b", "w": "wb"}[mode] if not fileobj: - fileobj = open(self.name, self.mode) + fileobj = _open(self.name, self.mode) self._extfileobj = False else: if self.name is None and hasattr(fileobj, "name"): @@ -1083,7 +1085,7 @@ tarname = pre + ext if fileobj is None: - fileobj = open(name, mode + "b") + fileobj = _open(name, mode + "b") if mode != "r": name = tarname @@ -1355,7 +1357,7 @@ # Append the tar header and data to the archive. if tarinfo.isreg(): - f = open(name, "rb") + f = _open(name, "rb") self.addfile(tarinfo, f) f.close() @@ -1617,7 +1619,7 @@ """Make a file called targetpath. """ source = self.extractfile(tarinfo) - target = open(targetpath, "wb") + target = _open(targetpath, "wb") copyfileobj(source, target) source.close() target.close() From python-3000-checkins at python.org Thu Aug 24 06:12:19 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Thu, 24 Aug 2006 06:12:19 +0200 (CEST) Subject: [Python-3000-checkins] r51540 - python/branches/p3yk/Objects/codeobject.c Message-ID: <20060824041219.191261E4004@bag.python.org> Author: guido.van.rossum Date: Thu Aug 24 06:12:18 2006 New Revision: 51540 Modified: python/branches/p3yk/Objects/codeobject.c Log: Implement == and != comparisons for code objects by value. This makes test_codeop and test_marshal pass. Modified: python/branches/p3yk/Objects/codeobject.c ============================================================================== --- python/branches/p3yk/Objects/codeobject.c (original) +++ python/branches/p3yk/Objects/codeobject.c Thu Aug 24 06:12:18 2006 @@ -294,44 +294,60 @@ static PyObject * code_richcompare(PyObject *self, PyObject *other, int op) { - /* Temporarily make this unsupported */ - _Py_Break(); - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - -#if 0 - int cmp; - cmp = PyObject_Compare(co->co_name, cp->co_name); - if (cmp) return cmp; - cmp = co->co_argcount - cp->co_argcount; - if (cmp) goto normalize; - cmp = co->co_nlocals - cp->co_nlocals; - if (cmp) goto normalize; - cmp = co->co_flags - cp->co_flags; - if (cmp) goto normalize; - cmp = co->co_firstlineno - cp->co_firstlineno; - if (cmp) goto normalize; - cmp = PyObject_Compare(co->co_code, cp->co_code); - if (cmp) return cmp; - cmp = PyObject_Compare(co->co_consts, cp->co_consts); - if (cmp) return cmp; - cmp = PyObject_Compare(co->co_names, cp->co_names); - if (cmp) return cmp; - cmp = PyObject_Compare(co->co_varnames, cp->co_varnames); - if (cmp) return cmp; - cmp = PyObject_Compare(co->co_freevars, cp->co_freevars); - if (cmp) return cmp; - cmp = PyObject_Compare(co->co_cellvars, cp->co_cellvars); - return cmp; - - normalize: - if (cmp > 0) - return 1; - else if (cmp < 0) - return -1; + PyCodeObject *co, *cp; + int eq; + PyObject *res; + + if ((op != Py_EQ && op != Py_NE) || + !PyCode_Check(self) || + !PyCode_Check(other)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + co = (PyCodeObject *)self; + cp = (PyCodeObject *)other; + + eq = PyObject_RichCompare(co->co_name, cp->co_name, Py_EQ); + if (eq <= 0) goto unequal; + eq = co->co_argcount == cp->co_argcount; + if (!eq) goto unequal; + eq = co->co_nlocals == cp->co_nlocals; + if (!eq) goto unequal; + eq = co->co_flags == cp->co_flags; + if (!eq) goto unequal; + eq = co->co_firstlineno == cp->co_firstlineno; + if (!eq) goto unequal; + eq = PyObject_RichCompare(co->co_code, cp->co_code, Py_EQ); + if (eq <= 0) goto unequal; + eq = PyObject_RichCompare(co->co_consts, cp->co_consts, Py_EQ); + if (eq <= 0) goto unequal; + eq = PyObject_RichCompare(co->co_names, cp->co_names, Py_EQ); + if (eq <= 0) goto unequal; + eq = PyObject_RichCompare(co->co_varnames, cp->co_varnames, Py_EQ); + if (eq <= 0) goto unequal; + eq = PyObject_RichCompare(co->co_freevars, cp->co_freevars, Py_EQ); + if (eq <= 0) goto unequal; + eq = PyObject_RichCompare(co->co_cellvars, cp->co_cellvars, Py_EQ); + if (eq <= 0) goto unequal; + + if (op == Py_EQ) + res = Py_True; else - return 0; -#endif + res = Py_False; + goto done; + + unequal: + if (eq < 0) + return NULL; + if (op == Py_NE) + res = Py_True; + else + res = Py_False; + + done: + Py_INCREF(res); + return res; } static long @@ -375,7 +391,7 @@ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ - 0, /* tp_hash */ + (hashfunc)code_hash, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ @@ -385,7 +401,7 @@ code_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ - 0, /* tp_richcompare */ + code_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ From python-3000-checkins at python.org Thu Aug 24 19:29:40 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Thu, 24 Aug 2006 19:29:40 +0200 (CEST) Subject: [Python-3000-checkins] r51561 - in python/branches/p3yk: Lib/test/test_datetime.py Modules/datetimemodule.c Message-ID: <20060824172940.22E9E1E4007@bag.python.org> Author: guido.van.rossum Date: Thu Aug 24 19:29:38 2006 New Revision: 51561 Modified: python/branches/p3yk/Lib/test/test_datetime.py python/branches/p3yk/Modules/datetimemodule.c Log: Fix the datetime comparison conundrum. The special-casing of other objects with a timetuple attribute is gone. Let's hope Tim agrees. Modified: python/branches/p3yk/Lib/test/test_datetime.py ============================================================================== --- python/branches/p3yk/Lib/test/test_datetime.py (original) +++ python/branches/p3yk/Lib/test/test_datetime.py Thu Aug 24 19:29:38 2006 @@ -954,41 +954,60 @@ def test_mixed_compare(self): our = self.theclass(2000, 4, 5) + + # Our class can be compared for equality to other classes + self.assertEqual(our == 1, False) + self.assertEqual(1 == our, False) + self.assertEqual(our != 1, True) + self.assertEqual(1 != our, True) + + # But the ordering is undefined + self.assertRaises(TypeError, lambda: our < 1) + self.assertRaises(TypeError, lambda: 1 < our) self.assertRaises(TypeError, cmp, our, 1) self.assertRaises(TypeError, cmp, 1, our) - class AnotherDateTimeClass(object): - def __cmp__(self, other): - # Return "equal" so calling this can't be confused with - # compare-by-address (which never says "equal" for distinct - # objects). - return 0 - - # This still errors, because date and datetime comparison raise - # TypeError instead of NotImplemented when they don't know what to - # do, in order to stop comparison from falling back to the default - # compare-by-address. - their = AnotherDateTimeClass() + # Repeat those tests with a different class + + class SomeClass: + pass + + their = SomeClass() + self.assertEqual(our == their, False) + self.assertEqual(their == our, False) + self.assertEqual(our != their, True) + self.assertEqual(their != our, True) + self.assertRaises(TypeError, lambda: our < their) + self.assertRaises(TypeError, lambda: their < our) self.assertRaises(TypeError, cmp, our, their) - # Oops: The next stab raises TypeError in the C implementation, - # but not in the Python implementation of datetime. The difference - # is due to that the Python implementation defines __cmp__ but - # the C implementation defines tp_richcompare. This is more pain - # to fix than it's worth, so commenting out the test. - # self.assertEqual(cmp(their, our), 0) - - # But date and datetime comparison return NotImplemented instead if the - # other object has a timetuple attr. This gives the other object a - # chance to do the comparison. - class Comparable(AnotherDateTimeClass): - def timetuple(self): - return () - - their = Comparable() - self.assertEqual(cmp(our, their), 0) - self.assertEqual(cmp(their, our), 0) - self.failUnless(our == their) - self.failUnless(their == our) + self.assertRaises(TypeError, cmp, their, our) + + # However, if the other class explicitly defines ordering + # relative to our class, it is allowed to do so + + class LargerThanAnything: + def __lt__(self, other): + return False + def __le__(self, other): + return isinstance(other, LargerThanAnything) + def __eq__(self, other): + return isinstance(other, LargerThanAnything) + def __ne__(self, other): + return not isinstance(other, LargerThanAnything) + def __gt__(self, other): + return not isinstance(other, LargerThanAnything) + def __ge__(self, other): + return True + + their = LargerThanAnything() + self.assertEqual(our == their, False) + self.assertEqual(their == our, False) + self.assertEqual(our != their, True) + self.assertEqual(their != our, True) + self.assertEqual(our < their, True) + self.assertEqual(their < our, False) + self.assertEqual(cmp(our, their), -1) + self.assertEqual(cmp(their, our), 1) def test_bool(self): # All dates are considered true. @@ -3217,10 +3236,10 @@ # Neverthelss, comparison should work with the base-class (date) # projection if use of a date method is forced. - self.assert_(as_date.__eq__(as_datetime)) + self.assertEqual(as_date.__eq__(as_datetime), True) different_day = (as_date.day + 1) % 20 + 1 - self.assert_(not as_date.__eq__(as_datetime.replace(day= - different_day))) + as_different = as_datetime.replace(day= different_day) + self.assertEqual(as_date.__eq__(as_different), False) # And date should compare with other subclasses of date. If a # subclass wants to stop this, it's up to the subclass to do so. Modified: python/branches/p3yk/Modules/datetimemodule.c ============================================================================== --- python/branches/p3yk/Modules/datetimemodule.c (original) +++ python/branches/p3yk/Modules/datetimemodule.c Thu Aug 24 19:29:38 2006 @@ -1387,7 +1387,7 @@ * Miscellaneous helpers. */ -/* For obscure reasons, we need to use tp_richcompare instead of tp_compare. +/* For various reasons, we need to use tp_richcompare instead of tp_compare. * The comparisons here all most naturally compute a cmp()-like result. * This little helper turns that into a bool result for rich comparisons. */ @@ -1705,31 +1705,23 @@ return result; } -/* This is more natural as a tp_compare, but doesn't work then: for whatever - * reason, Python's try_3way_compare ignores tp_compare unless - * PyInstance_Check returns true, but these aren't old-style classes. - */ static PyObject * -delta_richcompare(PyDateTime_Delta *self, PyObject *other, int op) +delta_richcompare(PyObject *self, PyObject *other, int op) { - int diff = 42; /* nonsense */ - if (PyDelta_Check(other)) { - diff = GET_TD_DAYS(self) - GET_TD_DAYS(other); + int diff = GET_TD_DAYS(self) - GET_TD_DAYS(other); if (diff == 0) { diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other); if (diff == 0) diff = GET_TD_MICROSECONDS(self) - GET_TD_MICROSECONDS(other); } + return diff_to_bool(diff, op); + } + else { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } - else if (op == Py_EQ || op == Py_NE) - diff = 1; /* any non-zero value will do */ - - else /* stop this from falling back to address comparison */ - return cmperror((PyObject *)self, other); - - return diff_to_bool(diff, op); } static PyObject *delta_getstate(PyDateTime_Delta *self); @@ -2145,7 +2137,7 @@ delta_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ - (richcmpfunc)delta_richcompare, /* tp_richcompare */ + delta_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ @@ -2499,31 +2491,19 @@ /* Miscellaneous methods. */ -/* This is more natural as a tp_compare, but doesn't work then: for whatever - * reason, Python's try_3way_compare ignores tp_compare unless - * PyInstance_Check returns true, but these aren't old-style classes. - */ static PyObject * -date_richcompare(PyDateTime_Date *self, PyObject *other, int op) +date_richcompare(PyObject *self, PyObject *other, int op) { - int diff = 42; /* nonsense */ - - if (PyDate_Check(other)) - diff = memcmp(self->data, ((PyDateTime_Date *)other)->data, - _PyDateTime_DATE_DATASIZE); - - else if (PyObject_HasAttrString(other, "timetuple")) { - /* A hook for other kinds of date objects. */ + if (PyDate_Check(other)) { + int diff = memcmp(((PyDateTime_Date *)self)->data, + ((PyDateTime_Date *)other)->data, + _PyDateTime_DATE_DATASIZE); + return diff_to_bool(diff, op); + } + else { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } - else if (op == Py_EQ || op == Py_NE) - diff = 1; /* any non-zero value will do */ - - else /* stop this from falling back to address comparison */ - return cmperror((PyObject *)self, other); - - return diff_to_bool(diff, op); } static PyObject * @@ -2701,7 +2681,7 @@ date_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ - (richcmpfunc)date_richcompare, /* tp_richcompare */ + date_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ @@ -3223,28 +3203,19 @@ * Miscellaneous methods. */ -/* This is more natural as a tp_compare, but doesn't work then: for whatever - * reason, Python's try_3way_compare ignores tp_compare unless - * PyInstance_Check returns true, but these aren't old-style classes. - */ static PyObject * -time_richcompare(PyDateTime_Time *self, PyObject *other, int op) +time_richcompare(PyObject *self, PyObject *other, int op) { int diff; naivety n1, n2; int offset1, offset2; if (! PyTime_Check(other)) { - if (op == Py_EQ || op == Py_NE) { - PyObject *result = op == Py_EQ ? Py_False : Py_True; - Py_INCREF(result); - return result; - } - /* Stop this from falling back to address comparison. */ - return cmperror((PyObject *)self, other); + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; } - if (classify_two_utcoffsets((PyObject *)self, &offset1, &n1, Py_None, - other, &offset2, &n2, Py_None) < 0) + if (classify_two_utcoffsets(self, &offset1, &n1, Py_None, + other, &offset2, &n2, Py_None) < 0) return NULL; assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN); /* If they're both naive, or both aware and have the same offsets, @@ -3252,7 +3223,8 @@ * offset2 == 0 at this point. */ if (n1 == n2 && offset1 == offset2) { - diff = memcmp(self->data, ((PyDateTime_Time *)other)->data, + diff = memcmp(((PyDateTime_Time *)self)->data, + ((PyDateTime_Time *)other)->data, _PyDateTime_TIME_DATASIZE); return diff_to_bool(diff, op); } @@ -3474,7 +3446,7 @@ time_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ - (richcmpfunc)time_richcompare, /* tp_richcompare */ + time_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ @@ -4115,46 +4087,34 @@ /* Miscellaneous methods. */ -/* This is more natural as a tp_compare, but doesn't work then: for whatever - * reason, Python's try_3way_compare ignores tp_compare unless - * PyInstance_Check returns true, but these aren't old-style classes. - */ static PyObject * -datetime_richcompare(PyDateTime_DateTime *self, PyObject *other, int op) +datetime_richcompare(PyObject *self, PyObject *other, int op) { int diff; naivety n1, n2; int offset1, offset2; if (! PyDateTime_Check(other)) { - /* If other has a "timetuple" attr, that's an advertised - * hook for other classes to ask to get comparison control. - * However, date instances have a timetuple attr, and we - * don't want to allow that comparison. Because datetime - * is a subclass of date, when mixing date and datetime - * in a comparison, Python gives datetime the first shot - * (it's the more specific subtype). So we can stop that - * combination here reliably. - */ - if (PyObject_HasAttrString(other, "timetuple") && - ! PyDate_Check(other)) { - /* A hook for other kinds of datetime objects. */ - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - if (op == Py_EQ || op == Py_NE) { - PyObject *result = op == Py_EQ ? Py_False : Py_True; - Py_INCREF(result); - return result; - } - /* Stop this from falling back to address comparison. */ - return cmperror((PyObject *)self, other); - } - - if (classify_two_utcoffsets((PyObject *)self, &offset1, &n1, - (PyObject *)self, - other, &offset2, &n2, - other) < 0) + if (PyDate_Check(other)) { + /* Prevent invocation of date_richcompare. We want to + return NotImplemented here to give the other object + a chance. But since DateTime is a subclass of + Date, if the other object is a Date, it would + compute an ordering based on the date part alone, + and we don't want that. So force unequal or + uncomparable here in that case. */ + if (op == Py_EQ) + Py_RETURN_FALSE; + if (op == Py_NE) + Py_RETURN_TRUE; + return cmperror(self, other); + } + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + + if (classify_two_utcoffsets(self, &offset1, &n1, self, + other, &offset2, &n2, other) < 0) return NULL; assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN); /* If they're both naive, or both aware and have the same offsets, @@ -4162,7 +4122,8 @@ * offset2 == 0 at this point. */ if (n1 == n2 && offset1 == offset2) { - diff = memcmp(self->data, ((PyDateTime_DateTime *)other)->data, + diff = memcmp(((PyDateTime_DateTime *)self)->data, + ((PyDateTime_DateTime *)other)->data, _PyDateTime_DATETIME_DATASIZE); return diff_to_bool(diff, op); } @@ -4568,7 +4529,7 @@ datetime_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ - (richcmpfunc)datetime_richcompare, /* tp_richcompare */ + datetime_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ From python-3000-checkins at python.org Thu Aug 24 20:19:44 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Thu, 24 Aug 2006 20:19:44 +0200 (CEST) Subject: [Python-3000-checkins] r51564 - python/branches/p3yk/Lib/bsddb/test/test_basics.py python/branches/p3yk/Lib/bsddb/test/test_dbshelve.py Message-ID: <20060824181944.C879F1E4004@bag.python.org> Author: guido.van.rossum Date: Thu Aug 24 20:19:44 2006 New Revision: 51564 Modified: python/branches/p3yk/Lib/bsddb/test/test_basics.py python/branches/p3yk/Lib/bsddb/test/test_dbshelve.py Log: Fix the bsddb3 unit tests. This essentially meant fixing one case where a list of custom objects was being sorted, and fixing one genuine bug where a method call was missing parentheses. Modified: python/branches/p3yk/Lib/bsddb/test/test_basics.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_basics.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_basics.py Thu Aug 24 20:19:44 2006 @@ -697,7 +697,7 @@ for log in logs: if verbose: print 'log file: ' + log - if db.version >= (4,2): + if db.version() >= (4,2): logs = self.env.log_archive(db.DB_ARCH_REMOVE) assert not logs Modified: python/branches/p3yk/Lib/bsddb/test/test_dbshelve.py ============================================================================== --- python/branches/p3yk/Lib/bsddb/test/test_dbshelve.py (original) +++ python/branches/p3yk/Lib/bsddb/test/test_dbshelve.py Thu Aug 24 20:19:44 2006 @@ -23,11 +23,24 @@ # We want the objects to be comparable so we can test dbshelve.values # later on. class DataClass: + def __init__(self): self.value = random.random() - def __cmp__(self, other): - return cmp(self.value, other) + def __repr__(self): + return "DataClass(%r)" % self.value + + def __eq__(self, other): + value = self.value + if isinstance(other, DataClass): + other = other.value + return value == other + + def __lt__(self, other): + value = self.value + if isinstance(other, DataClass): + other = other.value + return value < other class DBShelveTestCase(unittest.TestCase): def setUp(self): @@ -103,11 +116,10 @@ print "%s: %s" % (key, value) self.checkrec(key, value) - dbvalues = d.values() + dbvalues = sorted(d.values(), key=lambda x: (str(type(x)), x)) assert len(dbvalues) == len(d.keys()) - values.sort() - dbvalues.sort() - assert values == dbvalues + values.sort(key=lambda x: (str(type(x)), x)) + assert values == dbvalues, "%r != %r" % (values, dbvalues) items = d.items() assert len(items) == len(values) From python-3000-checkins at python.org Thu Aug 24 21:12:59 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Thu, 24 Aug 2006 21:12:59 +0200 (CEST) Subject: [Python-3000-checkins] r51567 - python/branches/p3yk/BROKEN Message-ID: <20060824191259.41B7D1E4004@bag.python.org> Author: guido.van.rossum Date: Thu Aug 24 21:12:58 2006 New Revision: 51567 Removed: python/branches/p3yk/BROKEN Log: Get rid of empty file. Deleted: /python/branches/p3yk/BROKEN ============================================================================== --- /python/branches/p3yk/BROKEN Thu Aug 24 21:12:58 2006 +++ (empty file) @@ -1 +0,0 @@ -(Nothing is broken at the moment AFAIK.) From python-3000-checkins at python.org Thu Aug 24 21:48:12 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Thu, 24 Aug 2006 21:48:12 +0200 (CEST) Subject: [Python-3000-checkins] r51569 - in python/branches/p3yk: Lib/test/test_builtin.py Lib/test/test_enumerate.py Lib/test/test_iter.py Lib/test/test_itertools.py Lib/test/test_tuple.py Python/bltinmodule.c Message-ID: <20060824194812.2472E1E4007@bag.python.org> Author: guido.van.rossum Date: Thu Aug 24 21:48:10 2006 New Revision: 51569 Modified: python/branches/p3yk/Lib/test/test_builtin.py python/branches/p3yk/Lib/test/test_enumerate.py python/branches/p3yk/Lib/test/test_iter.py python/branches/p3yk/Lib/test/test_itertools.py python/branches/p3yk/Lib/test/test_tuple.py python/branches/p3yk/Python/bltinmodule.c Log: Make built-in zip() equal to itertools.izip(). I mea, *really* equal -- for now, the implementation just imports itertools. :-) The only other changes necessary were various unit tests that were assuming zip() returns a real list. No "real" code made this assumption. Modified: python/branches/p3yk/Lib/test/test_builtin.py ============================================================================== --- python/branches/p3yk/Lib/test/test_builtin.py (original) +++ python/branches/p3yk/Lib/test/test_builtin.py Thu Aug 24 21:48:10 2006 @@ -1554,18 +1554,18 @@ a = (1, 2, 3) b = (4, 5, 6) t = [(1, 4), (2, 5), (3, 6)] - self.assertEqual(zip(a, b), t) + self.assertEqual(list(zip(a, b)), t) b = [4, 5, 6] - self.assertEqual(zip(a, b), t) + self.assertEqual(list(zip(a, b)), t) b = (4, 5, 6, 7) - self.assertEqual(zip(a, b), t) + self.assertEqual(list(zip(a, b)), t) class I: def __getitem__(self, i): if i < 0 or i > 2: raise IndexError return i + 4 - self.assertEqual(zip(a, I()), t) - self.assertEqual(zip(), []) - self.assertEqual(zip(*[]), []) + self.assertEqual(list(zip(a, I())), t) + self.assertEqual(list(zip()), []) + self.assertEqual(list(zip(*[])), []) self.assertRaises(TypeError, zip, None) class G: pass @@ -1581,7 +1581,7 @@ else: return i self.assertEqual( - zip(SequenceWithoutALength(), xrange(2**30)), + list(zip(SequenceWithoutALength(), xrange(2**30))), list(enumerate(range(5))) ) @@ -1591,7 +1591,7 @@ raise ValueError else: return i - self.assertRaises(ValueError, zip, BadSeq(), BadSeq()) + self.assertRaises(ValueError, list, zip(BadSeq(), BadSeq())) class TestSorted(unittest.TestCase): Modified: python/branches/p3yk/Lib/test/test_enumerate.py ============================================================================== --- python/branches/p3yk/Lib/test/test_enumerate.py (original) +++ python/branches/p3yk/Lib/test/test_enumerate.py Thu Aug 24 21:48:10 2006 @@ -122,7 +122,7 @@ class TestBig(EnumerateTestCase): seq = range(10,20000,2) - res = zip(range(20000), seq) + res = list(zip(range(20000), seq)) class TestReversed(unittest.TestCase): Modified: python/branches/p3yk/Lib/test/test_iter.py ============================================================================== --- python/branches/p3yk/Lib/test/test_iter.py (original) +++ python/branches/p3yk/Lib/test/test_iter.py Thu Aug 24 21:48:10 2006 @@ -423,21 +423,21 @@ # Test zip()'s use of iterators. def test_builtin_zip(self): - self.assertEqual(zip(), []) - self.assertEqual(zip(*[]), []) - self.assertEqual(zip(*[(1, 2), 'ab']), [(1, 'a'), (2, 'b')]) + self.assertEqual(list(zip()), []) + self.assertEqual(list(zip(*[])), []) + self.assertEqual(list(zip(*[(1, 2), 'ab'])), [(1, 'a'), (2, 'b')]) self.assertRaises(TypeError, zip, None) self.assertRaises(TypeError, zip, range(10), 42) self.assertRaises(TypeError, zip, range(10), zip) - self.assertEqual(zip(IteratingSequenceClass(3)), + self.assertEqual(list(zip(IteratingSequenceClass(3))), [(0,), (1,), (2,)]) - self.assertEqual(zip(SequenceClass(3)), + self.assertEqual(list(zip(SequenceClass(3))), [(0,), (1,), (2,)]) d = {"one": 1, "two": 2, "three": 3} - self.assertEqual(d.items(), zip(d, d.itervalues())) + self.assertEqual(d.items(), list(zip(d, d.itervalues()))) # Generate all ints starting at constructor arg. class IntsFrom: @@ -459,7 +459,7 @@ f.close() f = open(TESTFN, "r") try: - self.assertEqual(zip(IntsFrom(0), f, IntsFrom(-100)), + self.assertEqual(list(zip(IntsFrom(0), f, IntsFrom(-100))), [(0, "a\n", -100), (1, "bbb\n", -99), (2, "cc\n", -98)]) @@ -470,7 +470,7 @@ except OSError: pass - self.assertEqual(zip(xrange(5)), [(i,) for i in range(5)]) + self.assertEqual(list(zip(xrange(5))), [(i,) for i in range(5)]) # Classes that lie about their lengths. class NoGuessLen5: @@ -487,16 +487,19 @@ def __len__(self): return 30 + def lzip(*args): + return list(zip(*args)) + self.assertEqual(len(Guess3Len5()), 3) self.assertEqual(len(Guess30Len5()), 30) - self.assertEqual(zip(NoGuessLen5()), zip(range(5))) - self.assertEqual(zip(Guess3Len5()), zip(range(5))) - self.assertEqual(zip(Guess30Len5()), zip(range(5))) + self.assertEqual(lzip(NoGuessLen5()), lzip(range(5))) + self.assertEqual(lzip(Guess3Len5()), lzip(range(5))) + self.assertEqual(lzip(Guess30Len5()), lzip(range(5))) expected = [(i, i) for i in range(5)] for x in NoGuessLen5(), Guess3Len5(), Guess30Len5(): for y in NoGuessLen5(), Guess3Len5(), Guess30Len5(): - self.assertEqual(zip(x, y), expected) + self.assertEqual(lzip(x, y), expected) # This test case will be removed if we don't have Unicode def test_unicode_join_endcase(self): @@ -861,7 +864,7 @@ a = range(5) e = enumerate(a) b = iter(e) - self.assertEqual(list(b), zip(range(5), range(5))) + self.assertEqual(list(b), list(zip(range(5), range(5)))) self.assertEqual(list(b), []) Modified: python/branches/p3yk/Lib/test/test_itertools.py ============================================================================== --- python/branches/p3yk/Lib/test/test_itertools.py (original) +++ python/branches/p3yk/Lib/test/test_itertools.py Thu Aug 24 21:48:10 2006 @@ -6,6 +6,9 @@ import operator import random +def lzip(*args): + return list(zip(*args)) + def onearg(x): 'Test function of one argument' return 2*x @@ -47,9 +50,9 @@ self.assertRaises(TypeError, chain, 2, 3) def test_count(self): - self.assertEqual(zip('abc',count()), [('a', 0), ('b', 1), ('c', 2)]) - self.assertEqual(zip('abc',count(3)), [('a', 3), ('b', 4), ('c', 5)]) - self.assertEqual(take(2, zip('abc',count(3))), [('a', 3), ('b', 4)]) + self.assertEqual(lzip('abc',count()), [('a', 0), ('b', 1), ('c', 2)]) + self.assertEqual(lzip('abc',count(3)), [('a', 3), ('b', 4), ('c', 5)]) + self.assertEqual(take(2, lzip('abc',count(3))), [('a', 3), ('b', 4)]) self.assertRaises(TypeError, count, 2, 3) self.assertRaises(TypeError, count, 'a') c = count(sys.maxint-2) # verify that rollover doesn't crash @@ -176,27 +179,28 @@ self.assertRaises(TypeError, ifilterfalse(range(6), range(6)).next) def test_izip(self): + # XXX This is rather silly now that builtin zip() calls izip()... ans = [(x,y) for x, y in izip('abc',count())] self.assertEqual(ans, [('a', 0), ('b', 1), ('c', 2)]) - self.assertEqual(list(izip('abc', range(6))), zip('abc', range(6))) - self.assertEqual(list(izip('abcdef', range(3))), zip('abcdef', range(3))) - self.assertEqual(take(3,izip('abcdef', count())), zip('abcdef', range(3))) - self.assertEqual(list(izip('abcdef')), zip('abcdef')) - self.assertEqual(list(izip()), zip()) + self.assertEqual(list(izip('abc', range(6))), lzip('abc', range(6))) + self.assertEqual(list(izip('abcdef', range(3))), lzip('abcdef', range(3))) + self.assertEqual(take(3,izip('abcdef', count())), lzip('abcdef', range(3))) + self.assertEqual(list(izip('abcdef')), lzip('abcdef')) + self.assertEqual(list(izip()), lzip()) self.assertRaises(TypeError, izip, 3) self.assertRaises(TypeError, izip, range(3), 3) # Check tuple re-use (implementation detail) self.assertEqual([tuple(list(pair)) for pair in izip('abc', 'def')], - zip('abc', 'def')) + lzip('abc', 'def')) self.assertEqual([pair for pair in izip('abc', 'def')], - zip('abc', 'def')) + lzip('abc', 'def')) ids = map(id, izip('abc', 'def')) self.assertEqual(min(ids), max(ids)) ids = map(id, list(izip('abc', 'def'))) self.assertEqual(len(dict.fromkeys(ids)), len(ids)) def test_repeat(self): - self.assertEqual(zip(xrange(3),repeat('a')), + self.assertEqual(lzip(xrange(3),repeat('a')), [(0, 'a'), (1, 'a'), (2, 'a')]) self.assertEqual(list(repeat('a', 3)), ['a', 'a', 'a']) self.assertEqual(take(3, repeat('a')), ['a', 'a', 'a']) @@ -320,7 +324,7 @@ self.assertEqual(list(b), []) a, b = tee(irange(n)) # test 100% interleaved - self.assertEqual(zip(a,b), zip(range(n),range(n))) + self.assertEqual(lzip(a,b), lzip(range(n), range(n))) a, b = tee(irange(n)) # test 0% interleaved self.assertEqual(list(a), range(n)) @@ -601,8 +605,8 @@ def test_izip(self): for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)): for g in (G, I, Ig, S, L, R): - self.assertEqual(list(izip(g(s))), zip(g(s))) - self.assertEqual(list(izip(g(s), g(s))), zip(g(s), g(s))) + self.assertEqual(list(izip(g(s))), lzip(g(s))) + self.assertEqual(list(izip(g(s), g(s))), lzip(g(s), g(s))) self.assertRaises(TypeError, izip, X(s)) self.assertRaises(TypeError, izip, N(s)) self.assertRaises(ZeroDivisionError, list, izip(E(s))) @@ -627,7 +631,7 @@ def test_starmap(self): for s in (range(10), range(0), range(100), (7,11), xrange(20,50,5)): for g in (G, I, Ig, S, L, R): - ss = zip(s, s) + ss = lzip(s, s) self.assertEqual(list(starmap(operator.pow, g(ss))), map(operator.pow, g(s), g(s))) self.assertRaises(TypeError, starmap, operator.pow, X(ss)) self.assertRaises(TypeError, starmap, operator.pow, N(ss)) Modified: python/branches/p3yk/Lib/test/test_tuple.py ============================================================================== --- python/branches/p3yk/Lib/test/test_tuple.py (original) +++ python/branches/p3yk/Lib/test/test_tuple.py Thu Aug 24 21:48:10 2006 @@ -61,7 +61,7 @@ base = range(N) xp = [(i, j) for i in base for j in base] inps = base + [(i, j) for i in base for j in xp] + \ - [(i, j) for i in xp for j in base] + xp + zip(base) + [(i, j) for i in xp for j in base] + xp + list(zip(base)) collisions = len(inps) - len(set(map(hash, inps))) self.assert_(collisions <= 15) Modified: python/branches/p3yk/Python/bltinmodule.c ============================================================================== --- python/branches/p3yk/Python/bltinmodule.c (original) +++ python/branches/p3yk/Python/bltinmodule.c Thu Aug 24 21:48:10 2006 @@ -1855,116 +1855,32 @@ static PyObject* builtin_zip(PyObject *self, PyObject *args) { - PyObject *ret; - const Py_ssize_t itemsize = PySequence_Length(args); - Py_ssize_t i; - PyObject *itlist; /* tuple of iterators */ - Py_ssize_t len; /* guess at result length */ - - if (itemsize == 0) - return PyList_New(0); - - /* args must be a tuple */ - assert(PyTuple_Check(args)); - - /* Guess at result length: the shortest of the input lengths. - If some argument refuses to say, we refuse to guess too, lest - an argument like xrange(sys.maxint) lead us astray.*/ - len = -1; /* unknown */ - for (i = 0; i < itemsize; ++i) { - PyObject *item = PyTuple_GET_ITEM(args, i); - Py_ssize_t thislen = _PyObject_LengthHint(item); - if (thislen < 0) { - if (!PyErr_ExceptionMatches(PyExc_TypeError) && - !PyErr_ExceptionMatches(PyExc_AttributeError)) { - return NULL; - } - PyErr_Clear(); - len = -1; - break; - } - else if (len < 0 || thislen < len) - len = thislen; - } + PyObject *itertools = NULL, *izip = NULL, *result = NULL; - /* allocate result list */ - if (len < 0) - len = 10; /* arbitrary */ - if ((ret = PyList_New(len)) == NULL) + itertools = PyImport_ImportModule("itertools"); + if (itertools == NULL) return NULL; - - /* obtain iterators */ - itlist = PyTuple_New(itemsize); - if (itlist == NULL) - goto Fail_ret; - for (i = 0; i < itemsize; ++i) { - PyObject *item = PyTuple_GET_ITEM(args, i); - PyObject *it = PyObject_GetIter(item); - if (it == NULL) { - if (PyErr_ExceptionMatches(PyExc_TypeError)) - PyErr_Format(PyExc_TypeError, - "zip argument #%zd must support iteration", - i+1); - goto Fail_ret_itlist; - } - PyTuple_SET_ITEM(itlist, i, it); - } - - /* build result into ret list */ - for (i = 0; ; ++i) { - int j; - PyObject *next = PyTuple_New(itemsize); - if (!next) - goto Fail_ret_itlist; - - for (j = 0; j < itemsize; j++) { - PyObject *it = PyTuple_GET_ITEM(itlist, j); - PyObject *item = PyIter_Next(it); - if (!item) { - if (PyErr_Occurred()) { - Py_DECREF(ret); - ret = NULL; - } - Py_DECREF(next); - Py_DECREF(itlist); - goto Done; - } - PyTuple_SET_ITEM(next, j, item); - } - - if (i < len) - PyList_SET_ITEM(ret, i, next); - else { - int status = PyList_Append(ret, next); - Py_DECREF(next); - ++len; - if (status < 0) - goto Fail_ret_itlist; - } - } - -Done: - if (ret != NULL && i < len) { - /* The list is too big. */ - if (PyList_SetSlice(ret, i, len, NULL) < 0) - return NULL; - } - return ret; - -Fail_ret_itlist: - Py_DECREF(itlist); -Fail_ret: - Py_DECREF(ret); - return NULL; + + izip = PyObject_GetAttrString(itertools, "izip"); + if (izip == NULL) + goto done; + + result = PyObject_Call(izip, args, NULL); + + done: + Py_XDECREF(itertools); + Py_XDECREF(izip); + return result; } PyDoc_STRVAR(zip_doc, -"zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]\n\ +"zip(it1 [, it2 [...]]) -> iter([(it1[0], it2[0] ...), ...])\n\ \n\ -Return a list of tuples, where each tuple contains the i-th element\n\ -from each of the argument sequences. The returned list is truncated\n\ -in length to the length of the shortest argument sequence."); +Return an iterator yielding tuples, where each tuple contains the\n\ +corresponding element from each of the argument iterables.\n\ +The returned iterator ends when the shortest argument iterable is exhausted.\n\ +NOTE: This is implemented using itertools.izip()."); static PyMethodDef builtin_methods[] = { From python-3000-checkins at python.org Thu Aug 24 23:29:27 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Thu, 24 Aug 2006 23:29:27 +0200 (CEST) Subject: [Python-3000-checkins] r51572 - in python/branches/p3yk: Lib/test/test_mutants.py Objects/dictobject.c Message-ID: <20060824212927.4B5BD1E4004@bag.python.org> Author: guido.van.rossum Date: Thu Aug 24 23:29:26 2006 New Revision: 51572 Modified: python/branches/p3yk/Lib/test/test_mutants.py python/branches/p3yk/Objects/dictobject.c Log: Got test_mutants.py working. One set of changes was straightforward: use __eq__ instead of __cmp__. The other change is unexplained: with a random hash code as before, it would run forever; with a constant hash code, it fails quickly. This found a refcount bug in dict_equal() -- I wonder if that bug is also present in 2.5... Modified: python/branches/p3yk/Lib/test/test_mutants.py ============================================================================== --- python/branches/p3yk/Lib/test/test_mutants.py (original) +++ python/branches/p3yk/Lib/test/test_mutants.py Thu Aug 24 23:29:26 2006 @@ -27,7 +27,7 @@ # ran it. Indeed, at the start, the driver never got beyond 6 iterations # before the test died. -# The dicts are global to make it easy to mutate them from within functions. +# The dicts are global to make it easy to mutate tham from within functions. dict1 = {} dict2 = {} @@ -88,15 +88,22 @@ # have any systematic relationship between comparison outcomes # (based on self.i and other.i) and relative position within the # hash vector (based on hashcode). - self.hashcode = random.randrange(1000000000) + # XXX This is no longer effective. + ##self.hashcode = random.randrange(1000000000) def __hash__(self): - return self.hashcode + ##return self.hashcode + return 42 def __eq__(self, other): maybe_mutate() # The point of the test. return self.i == other.i + def __ne__(self, other): + raise RuntimeError("I didn't expect some kind of Spanish inquisition!") + + __lt__ = __le__ = __gt__ = __ge__ = __ne__ + def __repr__(self): return "Horrid(%d)" % self.i @@ -133,7 +140,6 @@ if verbose: print ".", c = dict1 == dict2 - XXX # Can't figure out how to make this work if verbose: print Modified: python/branches/p3yk/Objects/dictobject.c ============================================================================== --- python/branches/p3yk/Objects/dictobject.c (original) +++ python/branches/p3yk/Objects/dictobject.c Thu Aug 24 23:29:26 2006 @@ -24,11 +24,11 @@ important hash functions (for strings and ints) are very regular in common cases: ->>> map(hash, (0, 1, 2, 3)) -[0, 1, 2, 3] ->>> map(hash, ("namea", "nameb", "namec", "named")) -[-1658398457, -1658398460, -1658398459, -1658398462] ->>> + >>> map(hash, (0, 1, 2, 3)) + [0, 1, 2, 3] + >>> map(hash, ("namea", "nameb", "namec", "named")) + [-1658398457, -1658398460, -1658398459, -1658398462] + >>> This isn't necessarily bad! To the contrary, in a table of size 2**i, taking the low-order i bits as the initial table index is extremely fast, and there @@ -39,9 +39,9 @@ OTOH, when collisions occur, the tendency to fill contiguous slices of the hash table makes a good collision resolution strategy crucial. Taking only the last i bits of the hash code is also vulnerable: for example, consider -[i << 16 for i in range(20000)] as a set of keys. Since ints are their own -hash codes, and this fits in a dict of size 2**15, the last 15 bits of every -hash code are all 0: they *all* map to the same table index. +the list [i << 16 for i in range(20000)] as a set of keys. Since ints are +their own hash codes, and this fits in a dict of size 2**15, the last 15 bits + of every hash code are all 0: they *all* map to the same table index. But catering to unusual cases should not slow the usual ones, so we just take the last i bits anyway. It's up to collision resolution to do the rest. If @@ -97,19 +97,19 @@ best" in minimizing total collisions across experiments Tim Peters ran (on both normal and pathological cases), but 4 and 6 weren't significantly worse. -Historical: Reimer Behrends contributed the idea of using a polynomial-based +Historical: Reimer Behrends contributed the idea of using a polynomial-based approach, using repeated multiplication by x in GF(2**n) where an irreducible polynomial for each table size was chosen such that x was a primitive root. Christian Tismer later extended that to use division by x instead, as an efficient way to get the high bits of the hash code into play. This scheme -also gave excellent collision statistics, but was more expensive: two -if-tests were required inside the loop; computing "the next" index took about -the same number of operations but without as much potential parallelism -(e.g., computing 5*j can go on at the same time as computing 1+perturb in the -above, and then shifting perturb can be done while the table index is being -masked); and the dictobject struct required a member to hold the table's -polynomial. In Tim's experiments the current scheme ran faster, produced -equally good collision statistics, needed less code & used less memory. +also gave excellent collision statistics, but was more expensive: two if-tests +were required inside the loop; computing "the next" index took about the same +number of operations but without as much potential parallelism (e.g., +computing 5*j can go on at the same time as computing 1+perturb in the above, +and then shifting perturb can be done while the table index is being masked); +and the dictobject struct required a member to hold the table's polynomial. +In Tim's experiments the current scheme ran faster, produced equally good +collision statistics, needed less code & used less memory. Theoretical Python 2.5 headache: hash codes are only C "long", but sizeof(Py_ssize_t) > sizeof(long) may be possible. In that case, and if a @@ -223,9 +223,9 @@ All arithmetic on hash should ignore overflow. -(The details in this version are due to Tim Peters, building on many past +The details in this version are due to Tim Peters, building on many past contributions by Reimer Behrends, Jyrki Alakuijala, Vladimir Marangozov and -Christian Tismer). +Christian Tismer. lookdict() is general-purpose, and may return NULL if (and only if) a comparison raises an exception (this was new in Python 2.5). @@ -1485,7 +1485,10 @@ /* temporarily bump aval's refcount to ensure it stays alive until we're done with it */ Py_INCREF(aval); + /* ditto for key */ + Py_INCREF(key); bval = PyDict_GetItemWithError((PyObject *)b, key); + Py_DECREF(key); if (bval == NULL) { Py_DECREF(aval); if (PyErr_Occurred()) From python-3000-checkins at python.org Fri Aug 25 01:43:52 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Fri, 25 Aug 2006 01:43:52 +0200 (CEST) Subject: [Python-3000-checkins] r51577 - python/branches/p3yk/Objects/codeobject.c python/branches/p3yk/Objects/listobject.c Message-ID: <20060824234352.CA96E1E4004@bag.python.org> Author: guido.van.rossum Date: Fri Aug 25 01:43:52 2006 New Revision: 51577 Modified: python/branches/p3yk/Objects/codeobject.c python/branches/p3yk/Objects/listobject.c Log: Fix a bunch of compiler warnings. In at least one case these were serious bugs! Modified: python/branches/p3yk/Objects/codeobject.c ============================================================================== --- python/branches/p3yk/Objects/codeobject.c (original) +++ python/branches/p3yk/Objects/codeobject.c Fri Aug 25 01:43:52 2006 @@ -308,7 +308,7 @@ co = (PyCodeObject *)self; cp = (PyCodeObject *)other; - eq = PyObject_RichCompare(co->co_name, cp->co_name, Py_EQ); + eq = PyObject_RichCompareBool(co->co_name, cp->co_name, Py_EQ); if (eq <= 0) goto unequal; eq = co->co_argcount == cp->co_argcount; if (!eq) goto unequal; @@ -318,17 +318,17 @@ if (!eq) goto unequal; eq = co->co_firstlineno == cp->co_firstlineno; if (!eq) goto unequal; - eq = PyObject_RichCompare(co->co_code, cp->co_code, Py_EQ); + eq = PyObject_RichCompareBool(co->co_code, cp->co_code, Py_EQ); if (eq <= 0) goto unequal; - eq = PyObject_RichCompare(co->co_consts, cp->co_consts, Py_EQ); + eq = PyObject_RichCompareBool(co->co_consts, cp->co_consts, Py_EQ); if (eq <= 0) goto unequal; - eq = PyObject_RichCompare(co->co_names, cp->co_names, Py_EQ); + eq = PyObject_RichCompareBool(co->co_names, cp->co_names, Py_EQ); if (eq <= 0) goto unequal; - eq = PyObject_RichCompare(co->co_varnames, cp->co_varnames, Py_EQ); + eq = PyObject_RichCompareBool(co->co_varnames, cp->co_varnames, Py_EQ); if (eq <= 0) goto unequal; - eq = PyObject_RichCompare(co->co_freevars, cp->co_freevars, Py_EQ); + eq = PyObject_RichCompareBool(co->co_freevars, cp->co_freevars, Py_EQ); if (eq <= 0) goto unequal; - eq = PyObject_RichCompare(co->co_cellvars, cp->co_cellvars, Py_EQ); + eq = PyObject_RichCompareBool(co->co_cellvars, cp->co_cellvars, Py_EQ); if (eq <= 0) goto unequal; if (op == Py_EQ) Modified: python/branches/p3yk/Objects/listobject.c ============================================================================== --- python/branches/p3yk/Objects/listobject.c (original) +++ python/branches/p3yk/Objects/listobject.c Fri Aug 25 01:43:52 2006 @@ -1979,7 +1979,7 @@ return 1; if (!PyCFunction_Check(cmpfunc)) return 0; - f = (PyCFunction *)cmpfunc; + f = (PyCFunctionObject *)cmpfunc; if (f->m_self != NULL) return 0; if (!PyString_Check(f->m_module)) From python-3000-checkins at python.org Fri Aug 25 01:44:43 2006 From: python-3000-checkins at python.org (brett.cannon) Date: Fri, 25 Aug 2006 01:44:43 +0200 (CEST) Subject: [Python-3000-checkins] r51578 - python/branches/p3yk/Parser/asdl.py python/branches/p3yk/Parser/asdl_c.py Message-ID: <20060824234443.6D6F11E4004@bag.python.org> Author: brett.cannon Date: Fri Aug 25 01:44:42 2006 New Revision: 51578 Modified: python/branches/p3yk/Parser/asdl.py python/branches/p3yk/Parser/asdl_c.py Log: Get rid of all two uses of backticks (bad Jeremy!). Modified: python/branches/p3yk/Parser/asdl.py ============================================================================== --- python/branches/p3yk/Parser/asdl.py (original) +++ python/branches/p3yk/Parser/asdl.py Fri Aug 25 01:44:42 2006 @@ -98,7 +98,7 @@ def t_default(self, s): r" . +" - raise ValueError, "unmatched input: %s" % `s` + raise ValueError, "unmatched input: %s" % repr(s) class ASDLParser(spark.GenericParser, object): def __init__(self): Modified: python/branches/p3yk/Parser/asdl_c.py ============================================================================== --- python/branches/p3yk/Parser/asdl_c.py (original) +++ python/branches/p3yk/Parser/asdl_c.py Fri Aug 25 01:44:42 2006 @@ -47,7 +47,7 @@ # XXX this should be fixed for real if i == -1 and 'GeneratorExp' in cur: i = size + 3 - assert i != -1, "Impossible line %d to reflow: %s" % (size, `s`) + assert i != -1, "Impossible line %d to reflow: %s" % (size, repr(s)) lines.append(padding + cur[:i]) if len(lines) == 1: # find new size based on brace From nnorwitz at gmail.com Fri Aug 25 02:12:06 2006 From: nnorwitz at gmail.com (Neal Norwitz) Date: Thu, 24 Aug 2006 20:12:06 -0400 Subject: [Python-3000-checkins] r51578 - python/branches/p3yk/Parser/asdl.py python/branches/p3yk/Parser/asdl_c.py In-Reply-To: <20060824234443.6D6F11E4004@bag.python.org> References: <20060824234443.6D6F11E4004@bag.python.org> Message-ID: Would it be better to do '... %r ...' % value, instead of doing repr(value)? n -- On 8/24/06, brett.cannon wrote: > Author: brett.cannon > Date: Fri Aug 25 01:44:42 2006 > New Revision: 51578 > > Modified: > python/branches/p3yk/Parser/asdl.py > python/branches/p3yk/Parser/asdl_c.py > Log: > Get rid of all two uses of backticks (bad Jeremy!). > > > Modified: python/branches/p3yk/Parser/asdl.py > ============================================================================== > --- python/branches/p3yk/Parser/asdl.py (original) > +++ python/branches/p3yk/Parser/asdl.py Fri Aug 25 01:44:42 2006 > @@ -98,7 +98,7 @@ > > def t_default(self, s): > r" . +" > - raise ValueError, "unmatched input: %s" % `s` > + raise ValueError, "unmatched input: %s" % repr(s) > > class ASDLParser(spark.GenericParser, object): > def __init__(self): > > Modified: python/branches/p3yk/Parser/asdl_c.py > ============================================================================== > --- python/branches/p3yk/Parser/asdl_c.py (original) > +++ python/branches/p3yk/Parser/asdl_c.py Fri Aug 25 01:44:42 2006 > @@ -47,7 +47,7 @@ > # XXX this should be fixed for real > if i == -1 and 'GeneratorExp' in cur: > i = size + 3 > - assert i != -1, "Impossible line %d to reflow: %s" % (size, `s`) > + assert i != -1, "Impossible line %d to reflow: %s" % (size, repr(s)) > lines.append(padding + cur[:i]) > if len(lines) == 1: > # find new size based on brace > _______________________________________________ > Python-3000-checkins mailing list > Python-3000-checkins at python.org > http://mail.python.org/mailman/listinfo/python-3000-checkins > From brett at python.org Fri Aug 25 02:16:08 2006 From: brett at python.org (Brett Cannon) Date: Thu, 24 Aug 2006 17:16:08 -0700 Subject: [Python-3000-checkins] r51578 - python/branches/p3yk/Parser/asdl.py python/branches/p3yk/Parser/asdl_c.py In-Reply-To: References: <20060824234443.6D6F11E4004@bag.python.org> Message-ID: Possibly. There are a few other places in the testing suite where there are backticks. I can change to use %r where appropriate when I check in those removals as well. -Brett On 8/24/06, Neal Norwitz wrote: > > Would it be better to do '... %r ...' % value, instead of doing > repr(value)? > > n > -- > > On 8/24/06, brett.cannon wrote: > > Author: brett.cannon > > Date: Fri Aug 25 01:44:42 2006 > > New Revision: 51578 > > > > Modified: > > python/branches/p3yk/Parser/asdl.py > > python/branches/p3yk/Parser/asdl_c.py > > Log: > > Get rid of all two uses of backticks (bad Jeremy!). > > > > > > Modified: python/branches/p3yk/Parser/asdl.py > > > ============================================================================== > > --- python/branches/p3yk/Parser/asdl.py (original) > > +++ python/branches/p3yk/Parser/asdl.py Fri Aug 25 01:44:42 2006 > > @@ -98,7 +98,7 @@ > > > > def t_default(self, s): > > r" . +" > > - raise ValueError, "unmatched input: %s" % `s` > > + raise ValueError, "unmatched input: %s" % repr(s) > > > > class ASDLParser(spark.GenericParser, object): > > def __init__(self): > > > > Modified: python/branches/p3yk/Parser/asdl_c.py > > > ============================================================================== > > --- python/branches/p3yk/Parser/asdl_c.py (original) > > +++ python/branches/p3yk/Parser/asdl_c.py Fri Aug 25 01:44:42 2006 > > @@ -47,7 +47,7 @@ > > # XXX this should be fixed for real > > if i == -1 and 'GeneratorExp' in cur: > > i = size + 3 > > - assert i != -1, "Impossible line %d to reflow: %s" % (size, > `s`) > > + assert i != -1, "Impossible line %d to reflow: %s" % (size, > repr(s)) > > lines.append(padding + cur[:i]) > > if len(lines) == 1: > > # find new size based on brace > > _______________________________________________ > > Python-3000-checkins mailing list > > Python-3000-checkins at python.org > > http://mail.python.org/mailman/listinfo/python-3000-checkins > > > _______________________________________________ > Python-3000-checkins mailing list > Python-3000-checkins at python.org > http://mail.python.org/mailman/listinfo/python-3000-checkins > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/python-3000-checkins/attachments/20060824/a527650b/attachment.html From python-3000-checkins at python.org Fri Aug 25 03:00:48 2006 From: python-3000-checkins at python.org (brett.cannon) Date: Fri, 25 Aug 2006 03:00:48 +0200 (CEST) Subject: [Python-3000-checkins] r51582 - python/branches/p3yk/Lib/plat-riscos/riscosenviron.py python/branches/p3yk/Lib/plat-riscos/rourl2path.py Message-ID: <20060825010048.D573D1E400D@bag.python.org> Author: brett.cannon Date: Fri Aug 25 03:00:47 2006 New Revision: 51582 Modified: python/branches/p3yk/Lib/plat-riscos/riscosenviron.py python/branches/p3yk/Lib/plat-riscos/rourl2path.py Log: Remove some uses of '<>'. Modified: python/branches/p3yk/Lib/plat-riscos/riscosenviron.py ============================================================================== --- python/branches/p3yk/Lib/plat-riscos/riscosenviron.py (original) +++ python/branches/p3yk/Lib/plat-riscos/riscosenviron.py Fri Aug 25 03:00:47 2006 @@ -13,7 +13,7 @@ return len(riscos.getenvdict()) def __getitem__(self, key): ret = riscos.getenv(key) - if ret<>None: + if ret != None: return ret else: raise KeyError Modified: python/branches/p3yk/Lib/plat-riscos/rourl2path.py ============================================================================== --- python/branches/p3yk/Lib/plat-riscos/rourl2path.py (original) +++ python/branches/p3yk/Lib/plat-riscos/rourl2path.py Fri Aug 25 03:00:47 2006 @@ -14,7 +14,7 @@ """OS-specific conversion from a relative URL of the 'file' scheme to a file system path; not recommended for general use.""" tp = urllib.splittype(url)[0] - if tp and tp <> 'file': + if tp and tp != 'file': raise RuntimeError, 'Cannot convert non-local URL to pathname' # Turn starting /// into /, an empty hostname means current host if url[:3] == '///': From python-3000-checkins at python.org Fri Aug 25 03:02:04 2006 From: python-3000-checkins at python.org (brett.cannon) Date: Fri, 25 Aug 2006 03:02:04 +0200 (CEST) Subject: [Python-3000-checkins] r51583 - python/branches/p3yk/Lib/plat-sunos5/STROPTS.py Message-ID: <20060825010204.063FB1E4004@bag.python.org> Author: brett.cannon Date: Fri Aug 25 03:02:03 2006 New Revision: 51583 Modified: python/branches/p3yk/Lib/plat-sunos5/STROPTS.py Log: Remove a use of 'as' as a parameter. Modified: python/branches/p3yk/Lib/plat-sunos5/STROPTS.py ============================================================================== --- python/branches/p3yk/Lib/plat-sunos5/STROPTS.py (original) +++ python/branches/p3yk/Lib/plat-sunos5/STROPTS.py Fri Aug 25 03:02:03 2006 @@ -1550,7 +1550,7 @@ AS_PAGLCK = 0x80 AS_CLAIMGAP = 0x40 AS_UNMAPWAIT = 0x20 -def AS_TYPE_64BIT(as): return \ +def AS_TYPE_64BIT(as_): return \ AS_LREP_LINKEDLIST = 0 AS_LREP_SKIPLIST = 1 From nnorwitz at gmail.com Fri Aug 25 03:05:02 2006 From: nnorwitz at gmail.com (Neal Norwitz) Date: Thu, 24 Aug 2006 21:05:02 -0400 Subject: [Python-3000-checkins] r51583 - python/branches/p3yk/Lib/plat-sunos5/STROPTS.py In-Reply-To: <20060825010204.063FB1E4004@bag.python.org> References: <20060825010204.063FB1E4004@bag.python.org> Message-ID: Note the first line of this file is: # Generated by h2py from /usr/include/sys/stropts.h n On 8/24/06, brett.cannon wrote: > Author: brett.cannon > Date: Fri Aug 25 03:02:03 2006 > New Revision: 51583 > > Modified: > python/branches/p3yk/Lib/plat-sunos5/STROPTS.py > Log: > Remove a use of 'as' as a parameter. > > > Modified: python/branches/p3yk/Lib/plat-sunos5/STROPTS.py > ============================================================================== > --- python/branches/p3yk/Lib/plat-sunos5/STROPTS.py (original) > +++ python/branches/p3yk/Lib/plat-sunos5/STROPTS.py Fri Aug 25 03:02:03 2006 > @@ -1550,7 +1550,7 @@ > AS_PAGLCK = 0x80 > AS_CLAIMGAP = 0x40 > AS_UNMAPWAIT = 0x20 > -def AS_TYPE_64BIT(as): return \ > +def AS_TYPE_64BIT(as_): return \ > > AS_LREP_LINKEDLIST = 0 > AS_LREP_SKIPLIST = 1 > _______________________________________________ > Python-3000-checkins mailing list > Python-3000-checkins at python.org > http://mail.python.org/mailman/listinfo/python-3000-checkins > From python-3000-checkins at python.org Fri Aug 25 03:06:14 2006 From: python-3000-checkins at python.org (brett.cannon) Date: Fri, 25 Aug 2006 03:06:14 +0200 (CEST) Subject: [Python-3000-checkins] r51584 - python/branches/p3yk/Lib/plat-riscos/riscosenviron.py python/branches/p3yk/Lib/plat-riscos/rourl2path.py Message-ID: <20060825010614.90EE61E4011@bag.python.org> Author: brett.cannon Date: Fri Aug 25 03:06:13 2006 New Revision: 51584 Modified: python/branches/p3yk/Lib/plat-riscos/riscosenviron.py python/branches/p3yk/Lib/plat-riscos/rourl2path.py Log: Even more removals of '<>'; I can hear Barry shedding a manly tear ... Modified: python/branches/p3yk/Lib/plat-riscos/riscosenviron.py ============================================================================== --- python/branches/p3yk/Lib/plat-riscos/riscosenviron.py (original) +++ python/branches/p3yk/Lib/plat-riscos/riscosenviron.py Fri Aug 25 03:06:13 2006 @@ -31,7 +31,7 @@ def values(self): return riscos.getenvdict().values() def has_key(self, key): value = riscos.getenv(key) - return value<>None + return value != None def __contains__(self, key): return riscos.getenv(key) is not None def update(self, dict): Modified: python/branches/p3yk/Lib/plat-riscos/rourl2path.py ============================================================================== --- python/branches/p3yk/Lib/plat-riscos/rourl2path.py (original) +++ python/branches/p3yk/Lib/plat-riscos/rourl2path.py Fri Aug 25 03:06:13 2006 @@ -39,7 +39,7 @@ elif components[i] == '..': components[i] = '^' i += 1 - elif components[i] == '' and i > 0 and components[i-1] <> '': + elif components[i] == '' and i > 0 and components[i-1] != '': del components[i] else: i += 1 From python-3000-checkins at python.org Fri Aug 25 03:08:24 2006 From: python-3000-checkins at python.org (brett.cannon) Date: Fri, 25 Aug 2006 03:08:24 +0200 (CEST) Subject: [Python-3000-checkins] r51585 - python/branches/p3yk/Lib/plat-riscos/riscosenviron.py Message-ID: <20060825010824.C249A1E4004@bag.python.org> Author: brett.cannon Date: Fri Aug 25 03:08:24 2006 New Revision: 51585 Modified: python/branches/p3yk/Lib/plat-riscos/riscosenviron.py Log: For some reason Vim was just not wanting to tell me there was more instances of '<>'. Modified: python/branches/p3yk/Lib/plat-riscos/riscosenviron.py ============================================================================== --- python/branches/p3yk/Lib/plat-riscos/riscosenviron.py (original) +++ python/branches/p3yk/Lib/plat-riscos/riscosenviron.py Fri Aug 25 03:08:24 2006 @@ -39,7 +39,7 @@ riscos.putenv(k, v) def get(self, key, failobj=None): value = riscos.getenv(key) - if value<>None: + if value != None: return value else: return failobj From thomas at python.org Fri Aug 25 03:11:44 2006 From: thomas at python.org (Thomas Wouters) Date: Thu, 24 Aug 2006 21:11:44 -0400 Subject: [Python-3000-checkins] r51584 - python/branches/p3yk/Lib/plat-riscos/riscosenviron.py python/branches/p3yk/Lib/plat-riscos/rourl2path.py In-Reply-To: <20060825010614.90EE61E4011@bag.python.org> References: <20060825010614.90EE61E4011@bag.python.org> Message-ID: <9e804ac0608241811o500e126dy5712b63970aadf2@mail.gmail.com> On 8/24/06, brett.cannon wrote: > Even more removals of '<>'; I can hear Barry shedding a manly tear ... Not just Barry, although I already shed most of my tears when Guido actually removed <>. >;-< -- Thomas Wouters Hi! I'm a .signature virus! copy me into your .signature file to help me spread! -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/python-3000-checkins/attachments/20060824/ddcf6185/attachment.html From brett at python.org Fri Aug 25 03:14:44 2006 From: brett at python.org (Brett Cannon) Date: Thu, 24 Aug 2006 18:14:44 -0700 Subject: [Python-3000-checkins] r51583 - python/branches/p3yk/Lib/plat-sunos5/STROPTS.py In-Reply-To: References: <20060825010204.063FB1E4004@bag.python.org> Message-ID: Well, I obviously don't have that app. Crap. Well, I needed to make the change so that I could use compileall to find syntax errors from removing backticks. I will back out the change. -Brett On 8/24/06, Neal Norwitz wrote: > > Note the first line of this file is: > > # Generated by h2py from /usr/include/sys/stropts.h > > n > > On 8/24/06, brett.cannon wrote: > > Author: brett.cannon > > Date: Fri Aug 25 03:02:03 2006 > > New Revision: 51583 > > > > Modified: > > python/branches/p3yk/Lib/plat-sunos5/STROPTS.py > > Log: > > Remove a use of 'as' as a parameter. > > > > > > Modified: python/branches/p3yk/Lib/plat-sunos5/STROPTS.py > > > ============================================================================== > > --- python/branches/p3yk/Lib/plat-sunos5/STROPTS.py (original) > > +++ python/branches/p3yk/Lib/plat-sunos5/STROPTS.py Fri Aug 25 > 03:02:03 2006 > > @@ -1550,7 +1550,7 @@ > > AS_PAGLCK = 0x80 > > AS_CLAIMGAP = 0x40 > > AS_UNMAPWAIT = 0x20 > > -def AS_TYPE_64BIT(as): return \ > > +def AS_TYPE_64BIT(as_): return \ > > > > AS_LREP_LINKEDLIST = 0 > > AS_LREP_SKIPLIST = 1 > > _______________________________________________ > > Python-3000-checkins mailing list > > Python-3000-checkins at python.org > > http://mail.python.org/mailman/listinfo/python-3000-checkins > > > _______________________________________________ > Python-3000-checkins mailing list > Python-3000-checkins at python.org > http://mail.python.org/mailman/listinfo/python-3000-checkins > -------------- next part -------------- An HTML attachment was scrubbed... URL: http://mail.python.org/pipermail/python-3000-checkins/attachments/20060824/24d5ca90/attachment.htm From python-3000-checkins at python.org Fri Aug 25 03:16:13 2006 From: python-3000-checkins at python.org (brett.cannon) Date: Fri, 25 Aug 2006 03:16:13 +0200 (CEST) Subject: [Python-3000-checkins] r51587 - python/branches/p3yk/Lib/plat-sunos5/STROPTS.py Message-ID: <20060825011613.1E89D1E4004@bag.python.org> Author: brett.cannon Date: Fri Aug 25 03:16:12 2006 New Revision: 51587 Modified: python/branches/p3yk/Lib/plat-sunos5/STROPTS.py Log: Back out rev. 51583 as this file is auto-generated. Obviously the program that auto-generates this file will need to get fixed. Modified: python/branches/p3yk/Lib/plat-sunos5/STROPTS.py ============================================================================== --- python/branches/p3yk/Lib/plat-sunos5/STROPTS.py (original) +++ python/branches/p3yk/Lib/plat-sunos5/STROPTS.py Fri Aug 25 03:16:12 2006 @@ -1550,7 +1550,7 @@ AS_PAGLCK = 0x80 AS_CLAIMGAP = 0x40 AS_UNMAPWAIT = 0x20 -def AS_TYPE_64BIT(as_): return \ +def AS_TYPE_64BIT(as): return \ AS_LREP_LINKEDLIST = 0 AS_LREP_SKIPLIST = 1 From python-3000-checkins at python.org Fri Aug 25 04:57:28 2006 From: python-3000-checkins at python.org (brett.cannon) Date: Fri, 25 Aug 2006 04:57:28 +0200 (CEST) Subject: [Python-3000-checkins] r51590 - python/branches/p3yk/Modules/cgen.py Message-ID: <20060825025728.D25951E4007@bag.python.org> Author: brett.cannon Date: Fri Aug 25 04:57:28 2006 New Revision: 51590 Modified: python/branches/p3yk/Modules/cgen.py Log: Remove more '<>' usage. Modified: python/branches/p3yk/Modules/cgen.py ============================================================================== --- python/branches/p3yk/Modules/cgen.py (original) +++ python/branches/p3yk/Modules/cgen.py Fri Aug 25 04:57:28 2006 @@ -148,7 +148,7 @@ # N*argN # N*retval # - if rest[:1] <> '[' or rest[-1:] <> ']': + if rest[:1] != '[' or rest[-1:] != ']': raise arg_error, ('subscript expected', rest) sub = rest[1:-1] # From python-3000-checkins at python.org Fri Aug 25 05:00:01 2006 From: python-3000-checkins at python.org (brett.cannon) Date: Fri, 25 Aug 2006 05:00:01 +0200 (CEST) Subject: [Python-3000-checkins] r51591 - in python/branches/p3yk/Lib: idlelib/EditorWindow.py idlelib/HyperParser.py plat-mac/aetypes.py test/list_tests.py test/test_doctest.py test/test_grammar.py test/test_mutants.py test/test_site.py test/test_userdict.py test/test_weakref.py test/tokenize_tests.txt wsgiref/headers.py wsgiref/simple_server.py Message-ID: <20060825030001.059CA1E4007@bag.python.org> Author: brett.cannon Date: Fri Aug 25 04:59:59 2006 New Revision: 51591 Modified: python/branches/p3yk/Lib/idlelib/EditorWindow.py python/branches/p3yk/Lib/idlelib/HyperParser.py python/branches/p3yk/Lib/plat-mac/aetypes.py python/branches/p3yk/Lib/test/list_tests.py python/branches/p3yk/Lib/test/test_doctest.py python/branches/p3yk/Lib/test/test_grammar.py python/branches/p3yk/Lib/test/test_mutants.py python/branches/p3yk/Lib/test/test_site.py python/branches/p3yk/Lib/test/test_userdict.py python/branches/p3yk/Lib/test/test_weakref.py python/branches/p3yk/Lib/test/tokenize_tests.txt python/branches/p3yk/Lib/wsgiref/headers.py python/branches/p3yk/Lib/wsgiref/simple_server.py Log: Remove usage of backticks. Modified: python/branches/p3yk/Lib/idlelib/EditorWindow.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/EditorWindow.py (original) +++ python/branches/p3yk/Lib/idlelib/EditorWindow.py Fri Aug 25 04:59:59 2006 @@ -1138,7 +1138,7 @@ if not self.context_use_ps1: for context in self.num_context_lines: startat = max(lno - context, 1) - startatindex = `startat` + ".0" + startatindex = repr(startat) + ".0" rawtext = text.get(startatindex, "insert") y.set_str(rawtext) bod = y.find_good_parse_start( Modified: python/branches/p3yk/Lib/idlelib/HyperParser.py ============================================================================== --- python/branches/p3yk/Lib/idlelib/HyperParser.py (original) +++ python/branches/p3yk/Lib/idlelib/HyperParser.py Fri Aug 25 04:59:59 2006 @@ -31,7 +31,7 @@ if not editwin.context_use_ps1: for context in editwin.num_context_lines: startat = max(lno - context, 1) - startatindex = `startat` + ".0" + startatindex = repr(startat) + ".0" stopatindex = "%d.end" % lno # We add the newline because PyParse requires a newline at end. # We add a space so that index won't be at end of line, so that Modified: python/branches/p3yk/Lib/plat-mac/aetypes.py ============================================================================== --- python/branches/p3yk/Lib/plat-mac/aetypes.py (original) +++ python/branches/p3yk/Lib/plat-mac/aetypes.py Fri Aug 25 04:59:59 2006 @@ -128,7 +128,7 @@ self.keyword = "%-4.4s" % str(keyword) def __repr__(self): - return "Keyword(%r)" % `self.keyword` + return "Keyword(%r)" % self.keyword def __str__(self): return string.strip(self.keyword) Modified: python/branches/p3yk/Lib/test/list_tests.py ============================================================================== --- python/branches/p3yk/Lib/test/list_tests.py (original) +++ python/branches/p3yk/Lib/test/list_tests.py Fri Aug 25 04:59:59 2006 @@ -37,7 +37,7 @@ self.assertEqual(str(a0), str(l0)) self.assertEqual(repr(a0), repr(l0)) - self.assertEqual(`a2`, `l2`) + self.assertEqual(repr(a2), repr(l2)) self.assertEqual(str(a2), "[0, 1, 2]") self.assertEqual(repr(a2), "[0, 1, 2]") Modified: python/branches/p3yk/Lib/test/test_doctest.py ============================================================================== --- python/branches/p3yk/Lib/test/test_doctest.py (original) +++ python/branches/p3yk/Lib/test/test_doctest.py Fri Aug 25 04:59:59 2006 @@ -605,7 +605,7 @@ ... if isinstance(piece, doctest.Example): ... print 'Example:', (piece.source, piece.want, piece.lineno) ... else: - ... print ' Text:', `piece` + ... print ' Text:', repr(piece) Text: '\n' Example: ('x, y = 2, 3 # no output expected\n', '', 1) Text: '' Modified: python/branches/p3yk/Lib/test/test_grammar.py ============================================================================== --- python/branches/p3yk/Lib/test/test_grammar.py (original) +++ python/branches/p3yk/Lib/test/test_grammar.py Fri Aug 25 04:59:59 2006 @@ -685,7 +685,7 @@ print 'atoms' -### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING +### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictmaker] '}' | NAME | NUMBER | STRING ### dictmaker: test ':' test (',' test ':' test)* [','] x = (1) @@ -706,8 +706,6 @@ x = {'one': 1, 'two': 2,} x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6} -x = `x` -x = `1 or 2 or 3` x = x x = 'x' x = 123 Modified: python/branches/p3yk/Lib/test/test_mutants.py ============================================================================== --- python/branches/p3yk/Lib/test/test_mutants.py (original) +++ python/branches/p3yk/Lib/test/test_mutants.py Fri Aug 25 04:59:59 2006 @@ -209,7 +209,7 @@ # Tim sez: "luck of the draw; crashes with or without for me." print >> f - return `"machiavelli"` + return repr("machiavelli") def __hash__(self): return 0 Modified: python/branches/p3yk/Lib/test/test_site.py ============================================================================== --- python/branches/p3yk/Lib/test/test_site.py (original) +++ python/branches/p3yk/Lib/test/test_site.py Fri Aug 25 04:59:59 2006 @@ -164,7 +164,7 @@ site.abs__file__() for module in (sys, os, __builtin__): try: - self.failUnless(os.path.isabs(module.__file__), `module`) + self.failUnless(os.path.isabs(module.__file__), repr(module)) except AttributeError: continue # We could try everything in sys.modules; however, when regrtest.py Modified: python/branches/p3yk/Lib/test/test_userdict.py ============================================================================== --- python/branches/p3yk/Lib/test/test_userdict.py (original) +++ python/branches/p3yk/Lib/test/test_userdict.py Fri Aug 25 04:59:59 2006 @@ -46,7 +46,7 @@ # Test __repr__ self.assertEqual(str(u0), str(d0)) self.assertEqual(repr(u1), repr(d1)) - self.assertEqual(`u2`, `d2`) + self.assertEqual(repr(u2), repr(d2)) # Test __cmp__ and __len__ all = [d0, d1, d2, u, u0, u1, u2, uu, uu0, uu1, uu2] Modified: python/branches/p3yk/Lib/test/test_weakref.py ============================================================================== --- python/branches/p3yk/Lib/test/test_weakref.py (original) +++ python/branches/p3yk/Lib/test/test_weakref.py Fri Aug 25 04:59:59 2006 @@ -51,10 +51,10 @@ # Live reference: o = C() wr = weakref.ref(o) - `wr` + repr(wr) # Dead reference: del o - `wr` + repr(wr) def test_basic_callback(self): self.check_basic_callback(C) Modified: python/branches/p3yk/Lib/test/tokenize_tests.txt ============================================================================== --- python/branches/p3yk/Lib/test/tokenize_tests.txt (original) +++ python/branches/p3yk/Lib/test/tokenize_tests.txt Fri Aug 25 04:59:59 2006 @@ -21,7 +21,7 @@ 5] z = {'a':5, 'b':6} -x = (len(`y`) + 5*x - a[ +x = (len(repr(y)) + 5*x - a[ 3 ] - x + len({ } Modified: python/branches/p3yk/Lib/wsgiref/headers.py ============================================================================== --- python/branches/p3yk/Lib/wsgiref/headers.py (original) +++ python/branches/p3yk/Lib/wsgiref/headers.py Fri Aug 25 04:59:59 2006 @@ -140,7 +140,7 @@ return self._headers[:] def __repr__(self): - return "Headers(%s)" % `self._headers` + return "Headers(%r)" % self._headers def __str__(self): """str() returns the formatted headers, complete with end line, Modified: python/branches/p3yk/Lib/wsgiref/simple_server.py ============================================================================== --- python/branches/p3yk/Lib/wsgiref/simple_server.py (original) +++ python/branches/p3yk/Lib/wsgiref/simple_server.py Fri Aug 25 04:59:59 2006 @@ -169,7 +169,7 @@ print >>stdout h = environ.items(); h.sort() for k,v in h: - print >>stdout, k,'=',`v` + print >>stdout, k,'=',repr(v) start_response("200 OK", [('Content-Type','text/plain')]) return [stdout.getvalue()] From python-3000-checkins at python.org Fri Aug 25 05:01:14 2006 From: python-3000-checkins at python.org (brett.cannon) Date: Fri, 25 Aug 2006 05:01:14 +0200 (CEST) Subject: [Python-3000-checkins] r51592 - python/branches/p3yk/Lib/test/test_rfc822.py Message-ID: <20060825030114.C102D1E4007@bag.python.org> Author: brett.cannon Date: Fri Aug 25 05:01:11 2006 New Revision: 51592 Modified: python/branches/p3yk/Lib/test/test_rfc822.py Log: The backtick removal crusade continues ... Modified: python/branches/p3yk/Lib/test/test_rfc822.py ============================================================================== --- python/branches/p3yk/Lib/test/test_rfc822.py (original) +++ python/branches/p3yk/Lib/test/test_rfc822.py Fri Aug 25 05:01:11 2006 @@ -46,9 +46,9 @@ continue i = i + 1 self.assertEqual(mn, n, - "Un-expected name: %s != %s" % (`mn`, `n`)) + "Un-expected name: %r != %r" % (mn, n)) self.assertEqual(ma, a, - "Un-expected address: %s != %s" % (`ma`, `a`)) + "Un-expected address: %r != %r" % (ma, a)) if mn == n and ma == a: pass else: From python-3000-checkins at python.org Fri Aug 25 05:15:05 2006 From: python-3000-checkins at python.org (brett.cannon) Date: Fri, 25 Aug 2006 05:15:05 +0200 (CEST) Subject: [Python-3000-checkins] r51593 - python/branches/p3yk/Lib/test/test_ast.py Message-ID: <20060825031505.020551E4007@bag.python.org> Author: brett.cannon Date: Fri Aug 25 05:15:03 2006 New Revision: 51593 Modified: python/branches/p3yk/Lib/test/test_ast.py Log: Don't test AST for backticks. Modified: python/branches/p3yk/Lib/test/test_ast.py ============================================================================== --- python/branches/p3yk/Lib/test/test_ast.py (original) +++ python/branches/p3yk/Lib/test/test_ast.py Fri Aug 25 05:15:03 2006 @@ -94,8 +94,6 @@ "1 < 2 < 3", # Call "f(1,2,c=3,*d,**e)", - # Repr - "`v`", # Num "10L", # Str @@ -191,7 +189,6 @@ ('Expression', ('GeneratorExp', (1, 1), ('Name', (1, 1), 'a', ('Load',)), [('comprehension', ('Name', (1, 7), 'b', ('Store',)), ('Name', (1, 12), 'c', ('Load',)), [('Name', (1, 17), 'd', ('Load',))])])), ('Expression', ('Compare', (1, 0), ('Num', (1, 0), 1), [('Lt',), ('Lt',)], [('Num', (1, 4), 2), ('Num', (1, 8), 3)])), ('Expression', ('Call', (1, 0), ('Name', (1, 0), 'f', ('Load',)), [('Num', (1, 2), 1), ('Num', (1, 4), 2)], [('keyword', 'c', ('Num', (1, 8), 3))], ('Name', (1, 11), 'd', ('Load',)), ('Name', (1, 15), 'e', ('Load',)))), -('Expression', ('Repr', (1, 0), ('Name', (1, 1), 'v', ('Load',)))), ('Expression', ('Num', (1, 0), 10L)), ('Expression', ('Str', (1, 0), 'string')), ('Expression', ('Attribute', (1, 0), ('Name', (1, 0), 'a', ('Load',)), 'b', ('Load',))), From python-3000-checkins at python.org Fri Aug 25 06:06:35 2006 From: python-3000-checkins at python.org (brett.cannon) Date: Fri, 25 Aug 2006 06:06:35 +0200 (CEST) Subject: [Python-3000-checkins] r51594 - python/branches/p3yk/Parser/asdl.py python/branches/p3yk/Parser/asdl_c.py Message-ID: <20060825040635.E00AF1E4007@bag.python.org> Author: brett.cannon Date: Fri Aug 25 06:06:31 2006 New Revision: 51594 Modified: python/branches/p3yk/Parser/asdl.py python/branches/p3yk/Parser/asdl_c.py Log: Switch to using %r in the format string. Modified: python/branches/p3yk/Parser/asdl.py ============================================================================== --- python/branches/p3yk/Parser/asdl.py (original) +++ python/branches/p3yk/Parser/asdl.py Fri Aug 25 06:06:31 2006 @@ -98,7 +98,7 @@ def t_default(self, s): r" . +" - raise ValueError, "unmatched input: %s" % repr(s) + raise ValueError, "unmatched input: %r" % s class ASDLParser(spark.GenericParser, object): def __init__(self): Modified: python/branches/p3yk/Parser/asdl_c.py ============================================================================== --- python/branches/p3yk/Parser/asdl_c.py (original) +++ python/branches/p3yk/Parser/asdl_c.py Fri Aug 25 06:06:31 2006 @@ -47,7 +47,7 @@ # XXX this should be fixed for real if i == -1 and 'GeneratorExp' in cur: i = size + 3 - assert i != -1, "Impossible line %d to reflow: %s" % (size, repr(s)) + assert i != -1, "Impossible line %d to reflow: %r" % (size, s) lines.append(padding + cur[:i]) if len(lines) == 1: # find new size based on brace From python-3000-checkins at python.org Fri Aug 25 06:07:04 2006 From: python-3000-checkins at python.org (brett.cannon) Date: Fri, 25 Aug 2006 06:07:04 +0200 (CEST) Subject: [Python-3000-checkins] r51595 - python/branches/p3yk/Lib/test/output/test_tokenize Message-ID: <20060825040704.1C37E1E4007@bag.python.org> Author: brett.cannon Date: Fri Aug 25 06:07:01 2006 New Revision: 51595 Modified: python/branches/p3yk/Lib/test/output/test_tokenize Log: Check in new output for test_tokenize. Modified: python/branches/p3yk/Lib/test/output/test_tokenize ============================================================================== --- python/branches/p3yk/Lib/test/output/test_tokenize (original) +++ python/branches/p3yk/Lib/test/output/test_tokenize Fri Aug 25 06:07:01 2006 @@ -63,18 +63,19 @@ 24,4-24,5: OP '(' 24,5-24,8: NAME 'len' 24,8-24,9: OP '(' -24,9-24,10: OP '`' -24,10-24,11: NAME 'y' -24,11-24,12: OP '`' -24,12-24,13: OP ')' -24,14-24,15: OP '+' -24,16-24,17: NUMBER '5' -24,17-24,18: OP '*' -24,18-24,19: NAME 'x' -24,20-24,21: OP '-' -24,22-24,23: NAME 'a' -24,23-24,24: OP '[' -24,24-24,25: NL '\n' +24,9-24,13: NAME 'repr' +24,13-24,14: OP '(' +24,14-24,15: NAME 'y' +24,15-24,16: OP ')' +24,16-24,17: OP ')' +24,18-24,19: OP '+' +24,20-24,21: NUMBER '5' +24,21-24,22: OP '*' +24,22-24,23: NAME 'x' +24,24-24,25: OP '-' +24,26-24,27: NAME 'a' +24,27-24,28: OP '[' +24,28-24,29: NL '\n' 25,3-25,4: NUMBER '3' 25,5-25,6: OP ']' 25,6-25,7: NL '\n' From python-3000-checkins at python.org Fri Aug 25 06:12:11 2006 From: python-3000-checkins at python.org (brett.cannon) Date: Fri, 25 Aug 2006 06:12:11 +0200 (CEST) Subject: [Python-3000-checkins] r51596 - python/branches/p3yk/Lib/test/test_syntax.py Message-ID: <20060825041211.5B5281E4009@bag.python.org> Author: brett.cannon Date: Fri Aug 25 06:12:10 2006 New Revision: 51596 Modified: python/branches/p3yk/Lib/test/test_syntax.py Log: Change test of assignment of backticked expression to be an "invalid syntax" SyntaxError. This is probably not the proper solution to this failing test, but removing the test itself causes 19 other tests to fail for some odd reason because doctest doesn't expect a complete traceback (or something; rather odd problem for just removing a single test). Modified: python/branches/p3yk/Lib/test/test_syntax.py ============================================================================== --- python/branches/p3yk/Lib/test/test_syntax.py (original) +++ python/branches/p3yk/Lib/test/test_syntax.py Fri Aug 25 06:12:10 2006 @@ -71,7 +71,7 @@ >>> `1` = 1 Traceback (most recent call last): -SyntaxError: can't assign to repr (, line 1) +SyntaxError: invalid syntax If the left-hand side of an assignment is a list or tuple, an illegal expression inside that contain should still cause a syntax error. From python-3000-checkins at python.org Fri Aug 25 06:24:13 2006 From: python-3000-checkins at python.org (brett.cannon) Date: Fri, 25 Aug 2006 06:24:13 +0200 (CEST) Subject: [Python-3000-checkins] r51597 - python/branches/p3yk/Lib/test/test_peepholer.py Message-ID: <20060825042413.6BD181E4009@bag.python.org> Author: brett.cannon Date: Fri Aug 25 06:24:12 2006 New Revision: 51597 Modified: python/branches/p3yk/Lib/test/test_peepholer.py Log: UNARY_CONVERT can no longer be generated, so remove a test for the peepholer optimization for it. Modified: python/branches/p3yk/Lib/test/test_peepholer.py ============================================================================== --- python/branches/p3yk/Lib/test/test_peepholer.py (original) +++ python/branches/p3yk/Lib/test/test_peepholer.py Fri Aug 25 06:24:12 2006 @@ -135,7 +135,6 @@ def test_folding_of_unaryops_on_constants(self): for line, elem in ( - ('`1`', "('1')"), # unary convert ('-0.5', '(-0.5)'), # unary negative ('~-2', '(1)'), # unary invert ): From python-3000-checkins at python.org Fri Aug 25 06:28:24 2006 From: python-3000-checkins at python.org (brett.cannon) Date: Fri, 25 Aug 2006 06:28:24 +0200 (CEST) Subject: [Python-3000-checkins] r51598 - in python/branches/p3yk: Doc/ref/ref5.tex Grammar/Grammar Lib/tokenize.py Parser/tokenizer.c Python/ast.c Python/compile.c Python/graminit.c Message-ID: <20060825042824.0576E1E4007@bag.python.org> Author: brett.cannon Date: Fri Aug 25 06:28:18 2006 New Revision: 51598 Modified: python/branches/p3yk/Doc/ref/ref5.tex python/branches/p3yk/Grammar/Grammar python/branches/p3yk/Lib/tokenize.py python/branches/p3yk/Parser/tokenizer.c python/branches/p3yk/Python/ast.c python/branches/p3yk/Python/compile.c python/branches/p3yk/Python/graminit.c Log: Remove support for backticks from the grammar and compiler. Still need to remove traces of the UNARY_CONVERT opcode. Modified: python/branches/p3yk/Doc/ref/ref5.tex ============================================================================== --- python/branches/p3yk/Doc/ref/ref5.tex (original) +++ python/branches/p3yk/Doc/ref/ref5.tex Fri Aug 25 06:28:18 2006 @@ -268,49 +268,6 @@ \indexii{immutable}{object} -\subsection{String conversions\label{string-conversions}} -\indexii{string}{conversion} -\indexii{reverse}{quotes} -\indexii{backward}{quotes} -\index{back-quotes} - -A string conversion is an expression list enclosed in reverse (a.k.a. -backward) quotes: - -\begin{productionlist} - \production{string_conversion} - {"`" \token{expression_list} "`"} -\end{productionlist} - -A string conversion evaluates the contained expression list and -converts the resulting object into a string according to rules -specific to its type. - -If the object is a string, a number, \code{None}, or a tuple, list or -dictionary containing only objects whose type is one of these, the -resulting string is a valid Python expression which can be passed to -the built-in function \function{eval()} to yield an expression with the -same value (or an approximation, if floating point numbers are -involved). - -(In particular, converting a string adds quotes around it and converts -``funny'' characters to escape sequences that are safe to print.) - -Recursive objects (for example, lists or dictionaries that contain a -reference to themselves, directly or indirectly) use \samp{...} to -indicate a recursive reference, and the result cannot be passed to -\function{eval()} to get an equal value (\exception{SyntaxError} will -be raised instead). -\obindex{recursive} - -The built-in function \function{repr()} performs exactly the same -conversion in its argument as enclosing it in parentheses and reverse -quotes does. The built-in function \function{str()} performs a -similar but more user-friendly conversion. -\bifuncindex{repr} -\bifuncindex{str} - - \section{Primaries\label{primaries}} \index{primary} Modified: python/branches/p3yk/Grammar/Grammar ============================================================================== --- python/branches/p3yk/Grammar/Grammar (original) +++ python/branches/p3yk/Grammar/Grammar Fri Aug 25 06:28:18 2006 @@ -102,7 +102,6 @@ atom: ('(' [yield_expr|testlist_gexp] ')' | '[' [listmaker] ']' | '{' [dictmaker] '}' | - '`' testlist1 '`' | NAME | NUMBER | STRING+) listmaker: test ( list_for | (',' test)* [','] ) testlist_gexp: test ( gen_for | (',' test)* [','] ) Modified: python/branches/p3yk/Lib/tokenize.py ============================================================================== --- python/branches/p3yk/Lib/tokenize.py (original) +++ python/branches/p3yk/Lib/tokenize.py Fri Aug 25 06:28:18 2006 @@ -83,7 +83,7 @@ r"~") Bracket = '[][(){}]' -Special = group(r'\r?\n', r'[:;.,`@]') +Special = group(r'\r?\n', r'[:;.,@]') Funny = group(Operator, Bracket, Special) PlainToken = group(Number, Funny, String, Name) Modified: python/branches/p3yk/Parser/tokenizer.c ============================================================================== --- python/branches/p3yk/Parser/tokenizer.c (original) +++ python/branches/p3yk/Parser/tokenizer.c Fri Aug 25 06:28:18 2006 @@ -67,7 +67,6 @@ "EQUAL", "DOT", "PERCENT", - "BACKQUOTE", "LBRACE", "RBRACE", "EQEQUAL", @@ -955,7 +954,6 @@ case '=': return EQUAL; case '.': return DOT; case '%': return PERCENT; - case '`': return BACKQUOTE; case '{': return LBRACE; case '}': return RBRACE; case '^': return CIRCUMFLEX; Modified: python/branches/p3yk/Python/ast.c ============================================================================== --- python/branches/p3yk/Python/ast.c (original) +++ python/branches/p3yk/Python/ast.c Fri Aug 25 06:28:18 2006 @@ -1190,7 +1190,7 @@ ast_for_atom(struct compiling *c, const node *n) { /* atom: '(' [yield_expr|testlist_gexp] ')' | '[' [listmaker] ']' - | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING+ + | '{' [dictmaker] '}' | NAME | NUMBER | STRING+ */ node *ch = CHILD(n, 0); @@ -1276,13 +1276,6 @@ } return Dict(keys, values, LINENO(n), n->n_col_offset, c->c_arena); } - case BACKQUOTE: { /* repr */ - expr_ty expression = ast_for_testlist(c, CHILD(n, 1)); - if (!expression) - return NULL; - - return Repr(expression, LINENO(n), n->n_col_offset, c->c_arena); - } default: PyErr_Format(PyExc_SystemError, "unhandled atom %d", TYPE(ch)); return NULL; Modified: python/branches/p3yk/Python/compile.c ============================================================================== --- python/branches/p3yk/Python/compile.c (original) +++ python/branches/p3yk/Python/compile.c Fri Aug 25 06:28:18 2006 @@ -721,7 +721,6 @@ case UNARY_POSITIVE: case UNARY_NEGATIVE: case UNARY_NOT: - case UNARY_CONVERT: case UNARY_INVERT: return 0; @@ -2983,10 +2982,6 @@ return compiler_compare(c, e); case Call_kind: return compiler_call(c, e); - case Repr_kind: - VISIT(c, expr, e->v.Repr.value); - ADDOP(c, UNARY_CONVERT); - break; case Num_kind: ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts); break; Modified: python/branches/p3yk/Python/graminit.c ============================================================================== --- python/branches/p3yk/Python/graminit.c (original) +++ python/branches/p3yk/Python/graminit.c Fri Aug 25 06:28:18 2006 @@ -1242,68 +1242,59 @@ {1, arcs_60_2}, {1, arcs_60_3}, }; -static arc arcs_61_0[7] = { +static arc arcs_61_0[6] = { {13, 1}, {144, 2}, {147, 3}, + {19, 4}, {150, 4}, - {19, 5}, - {152, 5}, - {153, 6}, + {151, 5}, }; static arc arcs_61_1[3] = { - {43, 7}, - {143, 7}, - {15, 5}, + {43, 6}, + {143, 6}, + {15, 4}, }; static arc arcs_61_2[2] = { - {145, 8}, - {146, 5}, + {145, 7}, + {146, 4}, }; static arc arcs_61_3[2] = { - {148, 9}, - {149, 5}, + {148, 8}, + {149, 4}, }; static arc arcs_61_4[1] = { - {151, 10}, + {0, 4}, }; -static arc arcs_61_5[1] = { +static arc arcs_61_5[2] = { + {151, 5}, {0, 5}, }; -static arc arcs_61_6[2] = { - {153, 6}, - {0, 6}, +static arc arcs_61_6[1] = { + {15, 4}, }; static arc arcs_61_7[1] = { - {15, 5}, + {146, 4}, }; static arc arcs_61_8[1] = { - {146, 5}, -}; -static arc arcs_61_9[1] = { - {149, 5}, + {149, 4}, }; -static arc arcs_61_10[1] = { - {150, 5}, -}; -static state states_61[11] = { - {7, arcs_61_0}, +static state states_61[9] = { + {6, arcs_61_0}, {3, arcs_61_1}, {2, arcs_61_2}, {2, arcs_61_3}, {1, arcs_61_4}, - {1, arcs_61_5}, - {2, arcs_61_6}, + {2, arcs_61_5}, + {1, arcs_61_6}, {1, arcs_61_7}, {1, arcs_61_8}, - {1, arcs_61_9}, - {1, arcs_61_10}, }; static arc arcs_62_0[1] = { {26, 1}, }; static arc arcs_62_1[3] = { - {154, 2}, + {152, 2}, {27, 3}, {0, 1}, }; @@ -1329,7 +1320,7 @@ {26, 1}, }; static arc arcs_63_1[3] = { - {155, 2}, + {153, 2}, {27, 3}, {0, 1}, }; @@ -1384,7 +1375,7 @@ {15, 5}, }; static arc arcs_65_2[1] = { - {156, 6}, + {154, 6}, }; static arc arcs_65_3[1] = { {19, 5}, @@ -1408,14 +1399,14 @@ {1, arcs_65_6}, }; static arc arcs_66_0[1] = { - {157, 1}, + {155, 1}, }; static arc arcs_66_1[2] = { {27, 2}, {0, 1}, }; static arc arcs_66_2[2] = { - {157, 1}, + {155, 1}, {0, 2}, }; static state states_66[3] = { @@ -1437,14 +1428,14 @@ }; static arc arcs_67_3[3] = { {26, 5}, - {158, 6}, + {156, 6}, {0, 3}, }; static arc arcs_67_4[1] = { {75, 6}, }; static arc arcs_67_5[2] = { - {158, 6}, + {156, 6}, {0, 5}, }; static arc arcs_67_6[1] = { @@ -1531,7 +1522,7 @@ {2, arcs_71_4}, }; static arc arcs_72_0[1] = { - {159, 1}, + {157, 1}, }; static arc arcs_72_1[1] = { {19, 2}, @@ -1567,7 +1558,7 @@ {1, arcs_72_7}, }; static arc arcs_73_0[3] = { - {160, 1}, + {158, 1}, {28, 2}, {29, 3}, }; @@ -1582,7 +1573,7 @@ {26, 6}, }; static arc arcs_73_4[4] = { - {160, 1}, + {158, 1}, {28, 2}, {29, 3}, {0, 4}, @@ -1611,7 +1602,7 @@ {26, 1}, }; static arc arcs_74_1[3] = { - {155, 2}, + {153, 2}, {25, 3}, {0, 1}, }; @@ -1628,8 +1619,8 @@ {1, arcs_74_3}, }; static arc arcs_75_0[2] = { - {154, 1}, - {162, 1}, + {152, 1}, + {160, 1}, }; static arc arcs_75_1[1] = { {0, 1}, @@ -1651,7 +1642,7 @@ {104, 4}, }; static arc arcs_76_4[2] = { - {161, 5}, + {159, 5}, {0, 4}, }; static arc arcs_76_5[1] = { @@ -1672,7 +1663,7 @@ {105, 2}, }; static arc arcs_77_2[2] = { - {161, 3}, + {159, 3}, {0, 2}, }; static arc arcs_77_3[1] = { @@ -1685,8 +1676,8 @@ {1, arcs_77_3}, }; static arc arcs_78_0[2] = { - {155, 1}, - {164, 1}, + {153, 1}, + {162, 1}, }; static arc arcs_78_1[1] = { {0, 1}, @@ -1708,7 +1699,7 @@ {106, 4}, }; static arc arcs_79_4[2] = { - {163, 5}, + {161, 5}, {0, 4}, }; static arc arcs_79_5[1] = { @@ -1729,7 +1720,7 @@ {105, 2}, }; static arc arcs_80_2[2] = { - {163, 3}, + {161, 3}, {0, 2}, }; static arc arcs_80_3[1] = { @@ -1763,7 +1754,7 @@ {1, arcs_82_1}, }; static arc arcs_83_0[1] = { - {166, 1}, + {165, 1}, }; static arc arcs_83_1[2] = { {9, 2}, @@ -1779,11 +1770,11 @@ }; static dfa dfas[84] = { {256, "single_input", 0, 3, states_0, - "\004\050\014\000\000\000\000\025\074\005\023\310\011\020\004\000\140\010\111\203\100"}, + "\004\050\014\000\000\000\000\025\074\005\023\310\011\020\004\000\140\010\311\040\040"}, {257, "file_input", 0, 2, states_1, - "\204\050\014\000\000\000\000\025\074\005\023\310\011\020\004\000\140\010\111\203\100"}, + "\204\050\014\000\000\000\000\025\074\005\023\310\011\020\004\000\140\010\311\040\040"}, {258, "eval_input", 0, 3, states_2, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\111\003\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\311\000\000"}, {259, "decorator", 0, 7, states_3, "\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {260, "decorators", 0, 2, states_4, @@ -1799,13 +1790,13 @@ {265, "fplist", 0, 3, states_9, "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {266, "stmt", 0, 2, states_10, - "\000\050\014\000\000\000\000\025\074\005\023\310\011\020\004\000\140\010\111\203\100"}, + "\000\050\014\000\000\000\000\025\074\005\023\310\011\020\004\000\140\010\311\040\040"}, {267, "simple_stmt", 0, 4, states_11, - "\000\040\010\000\000\000\000\025\074\005\023\000\000\020\004\000\140\010\111\003\100"}, + "\000\040\010\000\000\000\000\025\074\005\023\000\000\020\004\000\140\010\311\000\040"}, {268, "small_stmt", 0, 2, states_12, - "\000\040\010\000\000\000\000\025\074\005\023\000\000\020\004\000\140\010\111\003\100"}, + "\000\040\010\000\000\000\000\025\074\005\023\000\000\020\004\000\140\010\311\000\040"}, {269, "expr_stmt", 0, 6, states_13, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\111\003\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\311\000\000"}, {270, "augassign", 0, 2, states_14, "\000\000\000\000\000\360\377\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {271, "print_stmt", 0, 9, states_15, @@ -1815,7 +1806,7 @@ {273, "pass_stmt", 0, 2, states_17, "\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {274, "flow_stmt", 0, 2, states_18, - "\000\000\000\000\000\000\000\000\074\000\000\000\000\000\000\000\000\000\000\000\100"}, + "\000\000\000\000\000\000\000\000\074\000\000\000\000\000\000\000\000\000\000\000\040"}, {275, "break_stmt", 0, 2, states_19, "\000\000\000\000\000\000\000\000\004\000\000\000\000\000\000\000\000\000\000\000\000"}, {276, "continue_stmt", 0, 2, states_20, @@ -1823,7 +1814,7 @@ {277, "return_stmt", 0, 3, states_21, "\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000\000\000"}, {278, "yield_stmt", 0, 2, states_22, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\100"}, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\040"}, {279, "raise_stmt", 0, 7, states_23, "\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000"}, {280, "import_stmt", 0, 2, states_24, @@ -1849,7 +1840,7 @@ {290, "assert_stmt", 0, 5, states_34, "\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000\000\000\000"}, {291, "compound_stmt", 0, 2, states_35, - "\000\010\004\000\000\000\000\000\000\000\000\310\011\000\000\000\000\000\000\200\000"}, + "\000\010\004\000\000\000\000\000\000\000\000\310\011\000\000\000\000\000\000\040\000"}, {292, "if_stmt", 0, 8, states_36, "\000\000\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000"}, {293, "while_stmt", 0, 8, states_37, @@ -1865,69 +1856,69 @@ {298, "except_clause", 0, 5, states_42, "\000\000\000\000\000\000\000\000\000\000\000\000\040\000\000\000\000\000\000\000\000"}, {299, "suite", 0, 5, states_43, - "\004\040\010\000\000\000\000\025\074\005\023\000\000\020\004\000\140\010\111\003\100"}, + "\004\040\010\000\000\000\000\025\074\005\023\000\000\020\004\000\140\010\311\000\040"}, {300, "testlist_safe", 0, 5, states_44, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\111\003\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\311\000\000"}, {301, "old_test", 0, 2, states_45, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\111\003\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\311\000\000"}, {302, "old_lambdef", 0, 5, states_46, "\000\000\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000"}, {303, "test", 0, 6, states_47, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\111\003\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\311\000\000"}, {304, "or_test", 0, 2, states_48, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\004\000\140\010\111\003\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\004\000\140\010\311\000\000"}, {305, "and_test", 0, 2, states_49, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\004\000\140\010\111\003\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\004\000\140\010\311\000\000"}, {306, "not_test", 0, 3, states_50, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\004\000\140\010\111\003\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\004\000\140\010\311\000\000"}, {307, "comparison", 0, 2, states_51, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\140\010\111\003\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\140\010\311\000\000"}, {308, "comp_op", 0, 4, states_52, "\000\000\000\000\000\000\000\000\000\000\010\000\000\000\344\017\000\000\000\000\000"}, {309, "expr", 0, 2, states_53, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\140\010\111\003\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\140\010\311\000\000"}, {310, "xor_expr", 0, 2, states_54, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\140\010\111\003\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\140\010\311\000\000"}, {311, "and_expr", 0, 2, states_55, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\140\010\111\003\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\140\010\311\000\000"}, {312, "shift_expr", 0, 2, states_56, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\140\010\111\003\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\140\010\311\000\000"}, {313, "arith_expr", 0, 2, states_57, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\140\010\111\003\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\140\010\311\000\000"}, {314, "term", 0, 2, states_58, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\140\010\111\003\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\140\010\311\000\000"}, {315, "factor", 0, 3, states_59, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\140\010\111\003\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\140\010\311\000\000"}, {316, "power", 0, 4, states_60, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\111\003\000"}, - {317, "atom", 0, 11, states_61, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\111\003\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\311\000\000"}, + {317, "atom", 0, 9, states_61, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\311\000\000"}, {318, "listmaker", 0, 5, states_62, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\111\003\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\311\000\000"}, {319, "testlist_gexp", 0, 5, states_63, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\111\003\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\311\000\000"}, {320, "lambdef", 0, 5, states_64, "\000\000\000\000\000\000\000\000\000\000\000\000\000\020\000\000\000\000\000\000\000"}, {321, "trailer", 0, 7, states_65, "\000\040\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\001\000\000"}, {322, "subscriptlist", 0, 3, states_66, - "\000\040\050\000\000\000\000\000\000\010\000\000\000\020\004\000\140\010\111\003\000"}, + "\000\040\050\000\000\000\000\000\000\010\000\000\000\020\004\000\140\010\311\000\000"}, {323, "subscript", 0, 7, states_67, - "\000\040\050\000\000\000\000\000\000\010\000\000\000\020\004\000\140\010\111\003\000"}, + "\000\040\050\000\000\000\000\000\000\010\000\000\000\020\004\000\140\010\311\000\000"}, {324, "sliceop", 0, 3, states_68, "\000\000\040\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {325, "exprlist", 0, 3, states_69, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\140\010\111\003\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\140\010\311\000\000"}, {326, "testlist", 0, 3, states_70, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\111\003\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\311\000\000"}, {327, "dictmaker", 0, 5, states_71, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\111\003\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\311\000\000"}, {328, "classdef", 0, 8, states_72, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\200\000"}, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\040\000"}, {329, "arglist", 0, 8, states_73, - "\000\040\010\060\000\000\000\000\000\000\000\000\000\020\004\000\140\010\111\003\000"}, + "\000\040\010\060\000\000\000\000\000\000\000\000\000\020\004\000\140\010\311\000\000"}, {330, "argument", 0, 4, states_74, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\111\003\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\311\000\000"}, {331, "list_iter", 0, 2, states_75, "\000\000\000\000\000\000\000\000\000\000\000\210\000\000\000\000\000\000\000\000\000"}, {332, "list_for", 0, 6, states_76, @@ -1941,13 +1932,13 @@ {336, "gen_if", 0, 4, states_80, "\000\000\000\000\000\000\000\000\000\000\000\010\000\000\000\000\000\000\000\000\000"}, {337, "testlist1", 0, 2, states_81, - "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\111\003\000"}, + "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\311\000\000"}, {338, "encoding_decl", 0, 2, states_82, "\000\000\010\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000"}, {339, "yield_expr", 0, 3, states_83, - "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\100"}, + "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\040"}, }; -static label labels[167] = { +static label labels[166] = { {0, "EMPTY"}, {256, 0}, {4, 0}, @@ -2098,8 +2089,6 @@ {26, 0}, {327, 0}, {27, 0}, - {25, 0}, - {337, 0}, {2, 0}, {3, 0}, {332, 0}, @@ -2113,12 +2102,13 @@ {333, 0}, {334, 0}, {336, 0}, + {337, 0}, {338, 0}, {1, "yield"}, }; grammar _PyParser_Grammar = { 84, dfas, - {167, labels}, + {166, labels}, 256 }; From python-3000-checkins at python.org Fri Aug 25 06:36:39 2006 From: python-3000-checkins at python.org (brett.cannon) Date: Fri, 25 Aug 2006 06:36:39 +0200 (CEST) Subject: [Python-3000-checkins] r51599 - python/branches/p3yk/Modules/cgen.py Message-ID: <20060825043639.94FD41E4007@bag.python.org> Author: brett.cannon Date: Fri Aug 25 06:36:39 2006 New Revision: 51599 Modified: python/branches/p3yk/Modules/cgen.py Log: Remove more '<>' usage. ``python -m compileall -f`` is really handy for finding Python files that use invalid syntax. Modified: python/branches/p3yk/Modules/cgen.py ============================================================================== --- python/branches/p3yk/Modules/cgen.py (original) +++ python/branches/p3yk/Modules/cgen.py Fri Aug 25 06:36:39 2006 @@ -167,9 +167,9 @@ raise arg_error, ('\'*\' expected', sub) if sub == 'retval': # size is retval -- must be a reply argument - if mode <> 'r': + if mode != 'r': raise arg_error, ('non-r mode with [retval]', mode) - elif not isnum(sub) and (sub[:3] <> 'arg' or not isnum(sub[3:])): + elif not isnum(sub) and (sub[:3] != 'arg' or not isnum(sub[3:])): raise arg_error, ('bad subscript', sub) # return type, mode, num, sub @@ -218,7 +218,7 @@ # # Declare return value if any # - if type <> 'void': + if type != 'void': print '\t' + type, 'retval;' # # Declare arguments @@ -283,7 +283,7 @@ print '(!geti' + xtype + 'arraysize(args,', print repr(n_in_args) + ',', print repr(in_pos[j]) + ',', - if xtype <> a_type: + if xtype != a_type: print '('+xtype+' *)', print '&arg' + repr(i+1) + '))' print '\t\treturn NULL;' @@ -311,21 +311,21 @@ if a_factor and a_sub: print '*', if a_sub: print a_sub, print ',', - if (a_sub and a_factor) or xtype <> a_type: + if (a_sub and a_factor) or xtype != a_type: print '('+xtype+' *)', print 'arg' + repr(i+1) + '))' else: # Get a simple variable print '(!geti' + xtype + 'arg(args,', print repr(n_in_args) + ',', print repr(in_pos[i]) + ',', - if xtype <> a_type: + if xtype != a_type: print '('+xtype+' *)', print '&arg' + repr(i+1) + '))' print '\t\treturn NULL;' # # Begin of function call # - if type <> 'void': + if type != 'void': print '\tretval =', func + '(', else: print '\t' + func + '(', @@ -356,7 +356,7 @@ # # Multiple return values -- construct a tuple # - if type <> 'void': + if type != 'void': n_out_args = n_out_args + 1 if n_out_args == 1: for i in range(len(database)): @@ -372,7 +372,7 @@ print n_out_args, ');' print '\t if (v == NULL) return NULL;' i_out = 0 - if type <> 'void': + if type != 'void': print '\t PyTuple_SetItem(v,', print repr(i_out) + ',', print mkobject(type, 'retval') + ');' @@ -489,7 +489,7 @@ elif len(words) < 2: err('Line', lno, ': no funcname :', line) else: - if len(words) % 2 <> 0: + if len(words) % 2 != 0: err('Line', lno, ': odd argument list :', words[2:]) else: database = [] From python-3000-checkins at python.org Fri Aug 25 07:05:32 2006 From: python-3000-checkins at python.org (brett.cannon) Date: Fri, 25 Aug 2006 07:05:32 +0200 (CEST) Subject: [Python-3000-checkins] r51600 - in python/branches/p3yk: Doc/lib/libdis.tex Include/Python-ast.h Include/opcode.h Lib/compiler/pycodegen.py Lib/opcode.py Parser/Python.asdl Python/Python-ast.c Python/ast.c Python/ceval.c Python/import.c Python/peephole.c Python/symtable.c Message-ID: <20060825050532.A5A9D1E4007@bag.python.org> Author: brett.cannon Date: Fri Aug 25 07:05:30 2006 New Revision: 51600 Modified: python/branches/p3yk/Doc/lib/libdis.tex python/branches/p3yk/Include/Python-ast.h python/branches/p3yk/Include/opcode.h python/branches/p3yk/Lib/compiler/pycodegen.py python/branches/p3yk/Lib/opcode.py python/branches/p3yk/Parser/Python.asdl python/branches/p3yk/Python/Python-ast.c python/branches/p3yk/Python/ast.c python/branches/p3yk/Python/ceval.c python/branches/p3yk/Python/import.c python/branches/p3yk/Python/peephole.c python/branches/p3yk/Python/symtable.c Log: Remove the UNARY_CONVERT opcode (was used for backticks). Also bumped up the import MAGIC number. Modified: python/branches/p3yk/Doc/lib/libdis.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libdis.tex (original) +++ python/branches/p3yk/Doc/lib/libdis.tex Fri Aug 25 07:05:30 2006 @@ -165,10 +165,6 @@ Implements \code{TOS = not TOS}. \end{opcodedesc} -\begin{opcodedesc}{UNARY_CONVERT}{} -Implements \code{TOS = `TOS`}. -\end{opcodedesc} - \begin{opcodedesc}{UNARY_INVERT}{} Implements \code{TOS = \~{}TOS}. \end{opcodedesc} Modified: python/branches/p3yk/Include/Python-ast.h ============================================================================== --- python/branches/p3yk/Include/Python-ast.h (original) +++ python/branches/p3yk/Include/Python-ast.h Fri Aug 25 07:05:30 2006 @@ -186,9 +186,8 @@ enum _expr_kind {BoolOp_kind=1, BinOp_kind=2, UnaryOp_kind=3, Lambda_kind=4, IfExp_kind=5, Dict_kind=6, ListComp_kind=7, GeneratorExp_kind=8, Yield_kind=9, Compare_kind=10, - Call_kind=11, Repr_kind=12, Num_kind=13, Str_kind=14, - Attribute_kind=15, Subscript_kind=16, Name_kind=17, - List_kind=18, Tuple_kind=19}; + Call_kind=11, Num_kind=12, Str_kind=13, Attribute_kind=14, + Subscript_kind=15, Name_kind=16, List_kind=17, Tuple_kind=18}; struct _expr { enum _expr_kind kind; union { @@ -253,10 +252,6 @@ } Call; struct { - expr_ty value; - } Repr; - - struct { object n; } Num; @@ -414,7 +409,6 @@ expr_ty Call(expr_ty func, asdl_seq * args, asdl_seq * keywords, expr_ty starargs, expr_ty kwargs, int lineno, int col_offset, PyArena *arena); -expr_ty Repr(expr_ty value, int lineno, int col_offset, PyArena *arena); expr_ty Num(object n, int lineno, int col_offset, PyArena *arena); expr_ty Str(string s, int lineno, int col_offset, PyArena *arena); expr_ty Attribute(expr_ty value, identifier attr, expr_context_ty ctx, int Modified: python/branches/p3yk/Include/opcode.h ============================================================================== --- python/branches/p3yk/Include/opcode.h (original) +++ python/branches/p3yk/Include/opcode.h Fri Aug 25 07:05:30 2006 @@ -18,7 +18,6 @@ #define UNARY_POSITIVE 10 #define UNARY_NEGATIVE 11 #define UNARY_NOT 12 -#define UNARY_CONVERT 13 #define UNARY_INVERT 15 Modified: python/branches/p3yk/Lib/compiler/pycodegen.py ============================================================================== --- python/branches/p3yk/Lib/compiler/pycodegen.py (original) +++ python/branches/p3yk/Lib/compiler/pycodegen.py Fri Aug 25 07:05:30 2006 @@ -1207,9 +1207,6 @@ def visitNot(self, node): return self.unaryOp(node, 'UNARY_NOT') - def visitBackquote(self, node): - return self.unaryOp(node, 'UNARY_CONVERT') - # bit ops def bitOp(self, nodes, op): Modified: python/branches/p3yk/Lib/opcode.py ============================================================================== --- python/branches/p3yk/Lib/opcode.py (original) +++ python/branches/p3yk/Lib/opcode.py Fri Aug 25 07:05:30 2006 @@ -54,7 +54,6 @@ def_op('UNARY_POSITIVE', 10) def_op('UNARY_NEGATIVE', 11) def_op('UNARY_NOT', 12) -def_op('UNARY_CONVERT', 13) def_op('UNARY_INVERT', 15) Modified: python/branches/p3yk/Parser/Python.asdl ============================================================================== --- python/branches/p3yk/Parser/Python.asdl (original) +++ python/branches/p3yk/Parser/Python.asdl Fri Aug 25 07:05:30 2006 @@ -65,7 +65,6 @@ | Compare(expr left, cmpop* ops, expr* comparators) | Call(expr func, expr* args, keyword* keywords, expr? starargs, expr? kwargs) - | Repr(expr value) | Num(object n) -- a number as a PyObject. | Str(string s) -- need to specify raw, unicode, etc? -- other literals? bools? Modified: python/branches/p3yk/Python/Python-ast.c ============================================================================== --- python/branches/p3yk/Python/Python-ast.c (original) +++ python/branches/p3yk/Python/Python-ast.c Fri Aug 25 07:05:30 2006 @@ -206,10 +206,6 @@ "starargs", "kwargs", }; -static PyTypeObject *Repr_type; -static char *Repr_fields[]={ - "value", -}; static PyTypeObject *Num_type; static char *Num_fields[]={ "n", @@ -532,8 +528,6 @@ if (!Compare_type) return 0; Call_type = make_type("Call", expr_type, Call_fields, 5); if (!Call_type) return 0; - Repr_type = make_type("Repr", expr_type, Repr_fields, 1); - if (!Repr_type) return 0; Num_type = make_type("Num", expr_type, Num_fields, 1); if (!Num_type) return 0; Str_type = make_type("Str", expr_type, Str_fields, 1); @@ -1553,27 +1547,6 @@ } expr_ty -Repr(expr_ty value, int lineno, int col_offset, PyArena *arena) -{ - expr_ty p; - if (!value) { - PyErr_SetString(PyExc_ValueError, - "field value is required for Repr"); - return NULL; - } - p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); - if (!p) { - PyErr_NoMemory(); - return NULL; - } - p->kind = Repr_kind; - p->v.Repr.value = value; - p->lineno = lineno; - p->col_offset = col_offset; - return p; -} - -expr_ty Num(object n, int lineno, int col_offset, PyArena *arena) { expr_ty p; @@ -2544,15 +2517,6 @@ goto failed; Py_DECREF(value); break; - case Repr_kind: - result = PyType_GenericNew(Repr_type, NULL, NULL); - if (!result) goto failed; - value = ast2obj_expr(o->v.Repr.value); - if (!value) goto failed; - if (PyObject_SetAttrString(result, "value", value) == -1) - goto failed; - Py_DECREF(value); - break; case Num_kind: result = PyType_GenericNew(Num_type, NULL, NULL); if (!result) goto failed; @@ -3113,7 +3077,6 @@ if (PyDict_SetItemString(d, "Compare", (PyObject*)Compare_type) < 0) return; if (PyDict_SetItemString(d, "Call", (PyObject*)Call_type) < 0) return; - if (PyDict_SetItemString(d, "Repr", (PyObject*)Repr_type) < 0) return; if (PyDict_SetItemString(d, "Num", (PyObject*)Num_type) < 0) return; if (PyDict_SetItemString(d, "Str", (PyObject*)Str_type) < 0) return; if (PyDict_SetItemString(d, "Attribute", (PyObject*)Attribute_type) < Modified: python/branches/p3yk/Python/ast.c ============================================================================== --- python/branches/p3yk/Python/ast.c (original) +++ python/branches/p3yk/Python/ast.c Fri Aug 25 07:05:30 2006 @@ -401,9 +401,6 @@ case Compare_kind: expr_name = "comparison"; break; - case Repr_kind: - expr_name = "repr"; - break; case IfExp_kind: expr_name = "conditional expression"; break; Modified: python/branches/p3yk/Python/ceval.c ============================================================================== --- python/branches/p3yk/Python/ceval.c (original) +++ python/branches/p3yk/Python/ceval.c Fri Aug 25 07:05:30 2006 @@ -1040,14 +1040,6 @@ STACKADJ(-1); break; - case UNARY_CONVERT: - v = TOP(); - x = PyObject_Repr(v); - Py_DECREF(v); - SET_TOP(x); - if (x != NULL) continue; - break; - case UNARY_INVERT: v = TOP(); x = PyNumber_Invert(v); Modified: python/branches/p3yk/Python/import.c ============================================================================== --- python/branches/p3yk/Python/import.c (original) +++ python/branches/p3yk/Python/import.c Fri Aug 25 07:05:30 2006 @@ -65,9 +65,10 @@ Python 2.5c1: 62121 (fix wrong lnotab with for loops and storing constants that should have been removed) Python 3000: 3000 + 3010 (removed UNARY_CONVERT) . */ -#define MAGIC (3000 | ((long)'\r'<<16) | ((long)'\n'<<24)) +#define MAGIC (3010 | ((long)'\r'<<16) | ((long)'\n'<<24)) /* Magic word as global; note that _PyImport_Init() can change the value of this global to accommodate for alterations of how the Modified: python/branches/p3yk/Python/peephole.c ============================================================================== --- python/branches/p3yk/Python/peephole.c (original) +++ python/branches/p3yk/Python/peephole.c Fri Aug 25 07:05:30 2006 @@ -189,9 +189,6 @@ if (PyObject_IsTrue(v) == 1) newconst = PyNumber_Negative(v); break; - case UNARY_CONVERT: - newconst = PyObject_Repr(v); - break; case UNARY_INVERT: newconst = PyNumber_Invert(v); break; @@ -470,7 +467,6 @@ /* Fold unary ops on constants. LOAD_CONST c1 UNARY_OP --> LOAD_CONST unary_op(c) */ case UNARY_NEGATIVE: - case UNARY_CONVERT: case UNARY_INVERT: if (lastlc >= 1 && ISBASICBLOCK(blocks, i-3, 4) && Modified: python/branches/p3yk/Python/symtable.c ============================================================================== --- python/branches/p3yk/Python/symtable.c (original) +++ python/branches/p3yk/Python/symtable.c Fri Aug 25 07:05:30 2006 @@ -1182,9 +1182,6 @@ if (e->v.Call.kwargs) VISIT(st, expr, e->v.Call.kwargs); break; - case Repr_kind: - VISIT(st, expr, e->v.Repr.value); - break; case Num_kind: case Str_kind: /* Nothing to do here. */ From python-3000-checkins at python.org Sat Aug 26 01:26:41 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sat, 26 Aug 2006 01:26:41 +0200 (CEST) Subject: [Python-3000-checkins] r51620 - in python/branches/p3yk: Include/iterobject.h Objects/iterobject.c Python/bltinmodule.c Message-ID: <20060825232641.8BF601E4009@bag.python.org> Author: guido.van.rossum Date: Sat Aug 26 01:26:40 2006 New Revision: 51620 Modified: python/branches/p3yk/Include/iterobject.h python/branches/p3yk/Objects/iterobject.c python/branches/p3yk/Python/bltinmodule.c Log: SF patch 1546297 (with some tweaks): Create a real zip iterator object; not using itertools.izip (Brian Holmes). Modified: python/branches/p3yk/Include/iterobject.h ============================================================================== --- python/branches/p3yk/Include/iterobject.h (original) +++ python/branches/p3yk/Include/iterobject.h Sat Aug 26 01:26:40 2006 @@ -16,6 +16,9 @@ #define PyCallIter_Check(op) ((op)->ob_type == &PyCallIter_Type) PyAPI_FUNC(PyObject *) PyCallIter_New(PyObject *, PyObject *); + +PyObject* _PyZip_CreateIter(PyObject* args); + #ifdef __cplusplus } #endif Modified: python/branches/p3yk/Objects/iterobject.c ============================================================================== --- python/branches/p3yk/Objects/iterobject.c (original) +++ python/branches/p3yk/Objects/iterobject.c Sat Aug 26 01:26:40 2006 @@ -230,3 +230,174 @@ (iternextfunc)calliter_iternext, /* tp_iternext */ 0, /* tp_methods */ }; + + +/*********************** Zip Iterator **************************/ +/* Largely copied from itertools.c by Brian Holmes */ + +typedef struct zipiterobject_t { + PyObject_HEAD + PyTupleObject *it_tuple; /* Set to NULL when iterator is exhausted */ + Py_ssize_t resultsize; + PyTupleObject *result; /* Reusable tuple for optimization */ +} zipiterobject; + +static PyTypeObject PyZipIter_Type; /* Forward */ + +PyObject * +_PyZip_CreateIter(PyObject* args) +{ + Py_ssize_t i; + Py_ssize_t tuplesize; + PyObject* ziptuple; + PyObject* result; + struct zipiterobject_t* zipiter; + + assert(PyTuple_Check(args)); + + if (PyZipIter_Type.ob_type == NULL) { + if (PyType_Ready(&PyZipIter_Type) < 0) + return NULL; + } + + tuplesize = PySequence_Length((PyObject*) args); + + ziptuple = PyTuple_New(tuplesize); + if (ziptuple == NULL) + return NULL; + + for (i = 0; i < tuplesize; i++) { + PyObject *o = PyTuple_GET_ITEM(args, i); + PyObject *it = PyObject_GetIter(o); + if (it == NULL) { + /* XXX Should we do this? + if (PyErr_ExceptionMatches(PyExc_TypeError)) + PyErr_Format(PyExc_TypeError, + "zip argument #%zd must support iteration", + I+1); + */ + Py_DECREF(ziptuple); + return NULL; + } + PyTuple_SET_ITEM(ziptuple, i, it); + } + + /* create a reusable result holder */ + result = PyTuple_New(tuplesize); + if (result == NULL) { + Py_DECREF(ziptuple); + return NULL; + } + for (i = 0; i < tuplesize; i++) { + Py_INCREF(Py_None); + PyTuple_SET_ITEM(result, i, Py_None); + } + + zipiter = PyObject_GC_New(zipiterobject, &PyZipIter_Type); + if (zipiter == NULL) { + Py_DECREF(ziptuple); + Py_DECREF(result); + return NULL; + } + + zipiter->result = (PyTupleObject*) result; + zipiter->resultsize = tuplesize; + Py_INCREF(ziptuple); + zipiter->it_tuple = (PyTupleObject *) ziptuple; + _PyObject_GC_TRACK(zipiter); + return (PyObject *)zipiter; +} + +static void +zipiter_dealloc(zipiterobject *it) +{ + _PyObject_GC_UNTRACK(it); + Py_XDECREF(it->it_tuple); + Py_XDECREF(it->result); + PyObject_GC_Del(it); +} + +static int +zipiter_traverse(zipiterobject *it, visitproc visit, void *arg) +{ + Py_VISIT(it->it_tuple); + Py_VISIT(it->result); + return 0; +} + +static PyObject * +zipiter_next(zipiterobject *zit) +{ + Py_ssize_t i; + Py_ssize_t tuplesize = zit->resultsize; + PyObject *result = (PyObject*) zit->result; + PyObject *olditem; + + if (tuplesize == 0) + return NULL; + + if (result->ob_refcnt == 1) { + Py_INCREF(result); + for (i = 0; i < tuplesize; i++) { + PyObject *it = PyTuple_GET_ITEM(zit->it_tuple, i); + assert(PyIter_Check(it)); + PyObject *item = (*it->ob_type->tp_iternext)(it); + if (item == NULL) { + Py_DECREF(result); + return NULL; + } + olditem = PyTuple_GET_ITEM(result, i); + PyTuple_SET_ITEM(result, i, item); + Py_DECREF(olditem); + } + } else { + result = PyTuple_New(tuplesize); + if (result == NULL) + return NULL; + for (i = 0; i < tuplesize; i++) { + PyObject *it = PyTuple_GET_ITEM(zit->it_tuple, i); + assert(PyIter_Check(it)); + PyObject *item = (*it->ob_type->tp_iternext)(it); + if (item == NULL) { + Py_DECREF(result); + return NULL; + } + PyTuple_SET_ITEM(result, i, item); + } + } + return result; +} + +static PyTypeObject PyZipIter_Type = { + PyObject_HEAD_INIT(0) + 0, /* ob_size */ + "zipiterator", /* tp_name */ + sizeof(zipiterobject), /* tp_basicsize */ + 0, /* tp_itemsize */ + /* methods */ + (destructor)zipiter_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + 0, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + 0, /* tp_call */ + 0, /* tp_str */ + PyObject_GenericGetAttr, /* tp_getattro */ + 0, /* tp_setattro */ + 0, /* tp_as_buffer */ + Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */ + 0, /* tp_doc */ + (traverseproc)zipiter_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weakzipoffset */ + PyObject_SelfIter, /* tp_iter */ + (iternextfunc)zipiter_next, /* tp_iternext */ + 0, /* tp_methods */ + 0, /* tp_members */ +}; Modified: python/branches/p3yk/Python/bltinmodule.c ============================================================================== --- python/branches/p3yk/Python/bltinmodule.c (original) +++ python/branches/p3yk/Python/bltinmodule.c Sat Aug 26 01:26:40 2006 @@ -1855,22 +1855,10 @@ static PyObject* builtin_zip(PyObject *self, PyObject *args) { - PyObject *itertools = NULL, *izip = NULL, *result = NULL; + /* args must be a tuple */ + assert(PyTuple_Check(args)); - itertools = PyImport_ImportModule("itertools"); - if (itertools == NULL) - return NULL; - - izip = PyObject_GetAttrString(itertools, "izip"); - if (izip == NULL) - goto done; - - result = PyObject_Call(izip, args, NULL); - - done: - Py_XDECREF(itertools); - Py_XDECREF(izip); - return result; + return _PyZip_CreateIter(args); } From python-3000-checkins at python.org Sat Aug 26 01:40:33 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sat, 26 Aug 2006 01:40:33 +0200 (CEST) Subject: [Python-3000-checkins] r51621 - python/branches/p3yk/Lib/test/test_dbm.py python/branches/p3yk/Lib/test/test_gdbm.py Message-ID: <20060825234033.DEDF81E4004@bag.python.org> Author: guido.van.rossum Date: Sat Aug 26 01:40:32 2006 New Revision: 51621 Modified: python/branches/p3yk/Lib/test/test_dbm.py python/branches/p3yk/Lib/test/test_gdbm.py Log: Don't use a fixed temporary name (gdbm). Don't use our own temp name creation (dbm). Should be backported to 2.5. Modified: python/branches/p3yk/Lib/test/test_dbm.py ============================================================================== --- python/branches/p3yk/Lib/test/test_dbm.py (original) +++ python/branches/p3yk/Lib/test/test_dbm.py Sat Aug 26 01:40:32 2006 @@ -6,11 +6,11 @@ import random import dbm from dbm import error -from test.test_support import verbose, verify, TestSkipped +from test.test_support import verbose, verify, TestSkipped, TESTFN # make filename unique to allow multiple concurrent tests # and to minimize the likelihood of a problem from an old file -filename = '/tmp/delete_me_' + str(random.random())[-6:] +filename = TESTFN def cleanup(): for suffix in ['', '.pag', '.dir', '.db']: Modified: python/branches/p3yk/Lib/test/test_gdbm.py ============================================================================== --- python/branches/p3yk/Lib/test/test_gdbm.py (original) +++ python/branches/p3yk/Lib/test/test_gdbm.py Sat Aug 26 01:40:32 2006 @@ -5,9 +5,9 @@ import gdbm from gdbm import error -from test.test_support import verbose, verify, TestFailed +from test.test_support import verbose, verify, TestFailed, TESTFN -filename= '/tmp/delete_me' +filename = TESTFN g = gdbm.open(filename, 'c') verify(g.keys() == []) From python-3000-checkins at python.org Sat Aug 26 04:54:41 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sat, 26 Aug 2006 04:54:41 +0200 (CEST) Subject: [Python-3000-checkins] r51623 - python/branches/p3yk/Objects/iterobject.c Message-ID: <20060826025441.AF08D1E4004@bag.python.org> Author: guido.van.rossum Date: Sat Aug 26 04:54:40 2006 New Revision: 51623 Modified: python/branches/p3yk/Objects/iterobject.c Log: The daily ritual: fix C89 violations. Modified: python/branches/p3yk/Objects/iterobject.c ============================================================================== --- python/branches/p3yk/Objects/iterobject.c (original) +++ python/branches/p3yk/Objects/iterobject.c Sat Aug 26 04:54:40 2006 @@ -340,8 +340,9 @@ Py_INCREF(result); for (i = 0; i < tuplesize; i++) { PyObject *it = PyTuple_GET_ITEM(zit->it_tuple, i); + PyObject *item; assert(PyIter_Check(it)); - PyObject *item = (*it->ob_type->tp_iternext)(it); + item = (*it->ob_type->tp_iternext)(it); if (item == NULL) { Py_DECREF(result); return NULL; @@ -356,8 +357,9 @@ return NULL; for (i = 0; i < tuplesize; i++) { PyObject *it = PyTuple_GET_ITEM(zit->it_tuple, i); + PyObject *item; assert(PyIter_Check(it)); - PyObject *item = (*it->ob_type->tp_iternext)(it); + item = (*it->ob_type->tp_iternext)(it); if (item == NULL) { Py_DECREF(result); return NULL; From python-3000-checkins at python.org Sat Aug 26 22:37:46 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sat, 26 Aug 2006 22:37:46 +0200 (CEST) Subject: [Python-3000-checkins] r51625 - in python/branches/p3yk/Lib: decimal.py doctest.py test/test_doctest.py test/test_traceback.py test/test_unpack.py traceback.py Message-ID: <20060826203746.596641E4003@bag.python.org> Author: guido.van.rossum Date: Sat Aug 26 22:37:44 2006 New Revision: 51625 Modified: python/branches/p3yk/Lib/decimal.py python/branches/p3yk/Lib/doctest.py python/branches/p3yk/Lib/test/test_doctest.py python/branches/p3yk/Lib/test/test_traceback.py python/branches/p3yk/Lib/test/test_unpack.py python/branches/p3yk/Lib/traceback.py Log: Inspired by SF patch #860326, make the exception formatting by traceback.py be closer to the built-in formatting. A few unittests had to be fixed, too. Modified: python/branches/p3yk/Lib/decimal.py ============================================================================== --- python/branches/p3yk/Lib/decimal.py (original) +++ python/branches/p3yk/Lib/decimal.py Sat Aug 26 22:37:44 2006 @@ -85,7 +85,7 @@ ... ... ... -DivisionByZero: x / 0 +decimal.DivisionByZero: x / 0 >>> c = Context() >>> c.traps[InvalidOperation] = 0 >>> print c.flags[InvalidOperation] @@ -103,7 +103,7 @@ ... ... ... -InvalidOperation: 0 / 0 +decimal.InvalidOperation: 0 / 0 >>> print c.flags[InvalidOperation] 1 >>> c.flags[InvalidOperation] = 0 Modified: python/branches/p3yk/Lib/doctest.py ============================================================================== --- python/branches/p3yk/Lib/doctest.py (original) +++ python/branches/p3yk/Lib/doctest.py Sat Aug 26 22:37:44 2006 @@ -1581,7 +1581,7 @@ - test: the DocTest object being run - - excample: the Example object that failed + - example: the Example object that failed - exc_info: the exception info """ @@ -1664,7 +1664,7 @@ >>> runner.run(test) Traceback (most recent call last): ... - UnexpectedException: + doctest.UnexpectedException: >>> del test.globs['__builtins__'] >>> test.globs Modified: python/branches/p3yk/Lib/test/test_doctest.py ============================================================================== --- python/branches/p3yk/Lib/test/test_doctest.py (original) +++ python/branches/p3yk/Lib/test/test_doctest.py Sat Aug 26 22:37:44 2006 @@ -2234,7 +2234,7 @@ >>> doctest.testfile('test_doctest.txt', raise_on_error=True) ... # doctest: +ELLIPSIS Traceback (most recent call last): - UnexpectedException: ... + doctest.UnexpectedException: ... >>> doctest.master = None # Reset master. If the tests contain non-ASCII characters, the tests might fail, since Modified: python/branches/p3yk/Lib/test/test_traceback.py ============================================================================== --- python/branches/p3yk/Lib/test/test_traceback.py (original) +++ python/branches/p3yk/Lib/test/test_traceback.py Sat Aug 26 22:37:44 2006 @@ -118,7 +118,9 @@ err = traceback.format_exception_only(X, X()) self.assertEqual(len(err), 1) str_value = '' % X.__name__ - self.assertEqual(err[0], X.__name__ + ': ' + str_value + '\n') + self.assertEqual(err[0], "%s.%s: %s\n" % (X.__module__, + X.__name__, + str_value)) def test_main(): Modified: python/branches/p3yk/Lib/test/test_unpack.py ============================================================================== --- python/branches/p3yk/Lib/test/test_unpack.py (original) +++ python/branches/p3yk/Lib/test/test_unpack.py Sat Aug 26 22:37:44 2006 @@ -107,7 +107,7 @@ >>> a, b, c, d, e = BadSeq() Traceback (most recent call last): ... - BozoError + test.test_unpack.BozoError Trigger code while expecting an IndexError (unpack sequence too short, wrong error) @@ -115,7 +115,7 @@ >>> a, b, c = BadSeq() Traceback (most recent call last): ... - BozoError + test.test_unpack.BozoError """ Modified: python/branches/p3yk/Lib/traceback.py ============================================================================== --- python/branches/p3yk/Lib/traceback.py (original) +++ python/branches/p3yk/Lib/traceback.py Sat Aug 26 22:37:44 2006 @@ -163,6 +163,9 @@ """ stype = etype.__name__ + smod = etype.__module__ + if smod not in ("exceptions", "__main__", "__builtin__"): + stype = smod + '.' + stype if not issubclass(etype, SyntaxError): return [_format_final_exc_line(stype, value)] From python-3000-checkins at python.org Sat Aug 26 22:49:07 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Sat, 26 Aug 2006 22:49:07 +0200 (CEST) Subject: [Python-3000-checkins] r51626 - in python/branches/p3yk: Doc/howto/doanddont.tex Doc/lib/libfuncs.tex Doc/lib/libfunctools.tex Doc/tut/tut.tex Lib/functools.py Lib/test/test_functools.py Misc/Vim/python.vim Misc/cheatsheet Misc/python-mode.el Modules/_functoolsmodule.c Python/Python-ast.c Message-ID: <20060826204907.E8A9D1E4003@bag.python.org> Author: guido.van.rossum Date: Sat Aug 26 22:49:04 2006 New Revision: 51626 Modified: python/branches/p3yk/Doc/howto/doanddont.tex python/branches/p3yk/Doc/lib/libfuncs.tex python/branches/p3yk/Doc/lib/libfunctools.tex python/branches/p3yk/Doc/tut/tut.tex python/branches/p3yk/Lib/functools.py python/branches/p3yk/Lib/test/test_functools.py python/branches/p3yk/Misc/Vim/python.vim python/branches/p3yk/Misc/cheatsheet python/branches/p3yk/Misc/python-mode.el python/branches/p3yk/Modules/_functoolsmodule.c python/branches/p3yk/Python/Python-ast.c Log: Part of SF patch #1513870 (the still relevant part) -- add reduce() to functools, and adjust docs etc. Modified: python/branches/p3yk/Doc/howto/doanddont.tex ============================================================================== --- python/branches/p3yk/Doc/howto/doanddont.tex (original) +++ python/branches/p3yk/Doc/howto/doanddont.tex Sat Aug 26 22:49:04 2006 @@ -289,19 +289,7 @@ aware of for some reason: \function{min()} and \function{max()} can find the minimum/maximum of any sequence with comparable semantics, for example, yet many people write their own -\function{max()}/\function{min()}. Another highly useful function is -\function{reduce()}. A classical use of \function{reduce()} -is something like - -\begin{verbatim} -import sys, operator -nums = map(float, sys.argv[1:]) -print reduce(operator.add, nums)/len(nums) -\end{verbatim} - -This cute little script prints the average of all numbers given on the -command line. The \function{reduce()} adds up all the numbers, and -the rest is just some pre- and postprocessing. +\function{max()}/\function{min()}. On the same note, note that \function{float()}, \function{int()} and \function{long()} all accept arguments of type string, and so are Modified: python/branches/p3yk/Doc/lib/libfuncs.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libfuncs.tex (original) +++ python/branches/p3yk/Doc/lib/libfuncs.tex Sat Aug 26 22:49:04 2006 @@ -836,19 +836,6 @@ \end{verbatim} \end{funcdesc} -\begin{funcdesc}{reduce}{function, sequence\optional{, initializer}} - Apply \var{function} of two arguments cumulatively to the items of - \var{sequence}, from left to right, so as to reduce the sequence to - a single value. For example, \code{reduce(lambda x, y: x+y, [1, 2, - 3, 4, 5])} calculates \code{((((1+2)+3)+4)+5)}. The left argument, - \var{x}, is the accumulated value and the right argument, \var{y}, - is the update value from the \var{sequence}. If the optional - \var{initializer} is present, it is placed before the items of the - sequence in the calculation, and serves as a default when the - sequence is empty. If \var{initializer} is not given and - \var{sequence} contains only one item, the first item is returned. -\end{funcdesc} - \begin{funcdesc}{reload}{module} Reload a previously imported \var{module}. The argument must be a module object, so it must have been successfully @@ -1058,8 +1045,6 @@ The \var{sequence}'s items are normally numbers, and are not allowed to be strings. The fast, correct way to concatenate sequence of strings is by calling \code{''.join(\var{sequence})}. - Note that \code{sum(range(\var{n}), \var{m})} is equivalent to - \code{reduce(operator.add, range(\var{n}), \var{m})} \versionadded{2.3} \end{funcdesc} Modified: python/branches/p3yk/Doc/lib/libfunctools.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libfunctools.tex (original) +++ python/branches/p3yk/Doc/lib/libfunctools.tex Sat Aug 26 22:49:04 2006 @@ -51,6 +51,19 @@ \end{verbatim} \end{funcdesc} +\begin{funcdesc}{reduce}{function, sequence\optional{, initializer}} + Apply \var{function} of two arguments cumulatively to the items of + \var{sequence}, from left to right, so as to reduce the sequence to + a single value. For example, \code{reduce(lambda x, y: x+y, [1, 2, + 3, 4, 5])} calculates \code{((((1+2)+3)+4)+5)}. The left argument, + \var{x}, is the accumulated value and the right argument, \var{y}, + is the update value from the \var{sequence}. If the optional + \var{initializer} is present, it is placed before the items of the + sequence in the calculation, and serves as a default when the + sequence is empty. If \var{initializer} is not given and + \var{sequence} contains only one item, the first item is returned. +\end{funcdesc} + \begin{funcdesc}{update_wrapper} {wrapper, wrapped\optional{, assigned}\optional{, updated}} Update a wrapper function to look like the wrapped function. The optional Modified: python/branches/p3yk/Doc/tut/tut.tex ============================================================================== --- python/branches/p3yk/Doc/tut/tut.tex (original) +++ python/branches/p3yk/Doc/tut/tut.tex Sat Aug 26 22:49:04 2006 @@ -1893,8 +1893,8 @@ \subsection{Functional Programming Tools \label{functional}} -There are three built-in functions that are very useful when used with -lists: \function{filter()}, \function{map()}, and \function{reduce()}. +There are two built-in functions that are very useful when used with +lists: \function{filter()} and \function{map()}. \samp{filter(\var{function}, \var{sequence})} returns a sequence consisting of those items from the @@ -1934,42 +1934,6 @@ >>> map(add, seq, seq) [0, 2, 4, 6, 8, 10, 12, 14] \end{verbatim} - -\samp{reduce(\var{function}, \var{sequence})} returns a single value -constructed by calling the binary function \var{function} on the first two -items of the sequence, then on the result and the next item, and so -on. For example, to compute the sum of the numbers 1 through 10: - -\begin{verbatim} ->>> def add(x,y): return x+y -... ->>> reduce(add, range(1, 11)) -55 -\end{verbatim} - -If there's only one item in the sequence, its value is returned; if -the sequence is empty, an exception is raised. - -A third argument can be passed to indicate the starting value. In this -case the starting value is returned for an empty sequence, and the -function is first applied to the starting value and the first sequence -item, then to the result and the next item, and so on. For example, - -\begin{verbatim} ->>> def sum(seq): -... def add(x,y): return x+y -... return reduce(add, seq, 0) -... ->>> sum(range(1, 11)) -55 ->>> sum([]) -0 -\end{verbatim} - -Don't use this example's definition of \function{sum()}: since summing -numbers is such a common need, a built-in function -\code{sum(\var{sequence})} is already provided, and works exactly like -this. \versionadded{2.3} \subsection{List Comprehensions} @@ -2739,7 +2703,7 @@ 'id', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min', 'object', 'oct', 'open', 'ord', 'pow', 'property', 'quit', 'range', - 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', + 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip'] \end{verbatim} Modified: python/branches/p3yk/Lib/functools.py ============================================================================== --- python/branches/p3yk/Lib/functools.py (original) +++ python/branches/p3yk/Lib/functools.py Sat Aug 26 22:49:04 2006 @@ -7,7 +7,7 @@ # Copyright (C) 2006 Python Software Foundation. # See C source code for _functools credits/copyright -from _functools import partial +from _functools import partial, reduce # update_wrapper() and wraps() are tools to help write # wrapper functions that can handle naive introspection Modified: python/branches/p3yk/Lib/test/test_functools.py ============================================================================== --- python/branches/p3yk/Lib/test/test_functools.py (original) +++ python/branches/p3yk/Lib/test/test_functools.py Sat Aug 26 22:49:04 2006 @@ -259,6 +259,74 @@ self.assertEqual(wrapper.attr, 'This is a different test') self.assertEqual(wrapper.dict_attr, f.dict_attr) +class TestReduce(unittest.TestCase): + func = functools.reduce + + def test_reduce(self): + class Squares: + def __init__(self, max): + self.max = max + self.sofar = [] + + def __len__(self): + return len(self.sofar) + + def __getitem__(self, i): + if not 0 <= i < self.max: raise IndexError + n = len(self.sofar) + while n <= i: + self.sofar.append(n*n) + n += 1 + return self.sofar[i] + + self.assertEqual(self.func(lambda x, y: x+y, ['a', 'b', 'c'], ''), 'abc') + self.assertEqual( + self.func(lambda x, y: x+y, [['a', 'c'], [], ['d', 'w']], []), + ['a','c','d','w'] + ) + self.assertEqual(self.func(lambda x, y: x*y, range(2,8), 1), 5040) + self.assertEqual( + self.func(lambda x, y: x*y, range(2,21), 1L), + 2432902008176640000L + ) + self.assertEqual(self.func(lambda x, y: x+y, Squares(10)), 285) + self.assertEqual(self.func(lambda x, y: x+y, Squares(10), 0), 285) + self.assertEqual(self.func(lambda x, y: x+y, Squares(0), 0), 0) + self.assertRaises(TypeError, self.func) + self.assertRaises(TypeError, self.func, 42, 42) + self.assertRaises(TypeError, self.func, 42, 42, 42) + self.assertEqual(self.func(42, "1"), "1") # func is never called with one item + self.assertEqual(self.func(42, "", "1"), "1") # func is never called with one item + self.assertRaises(TypeError, self.func, 42, (42, 42)) + + class BadSeq: + def __getitem__(self, index): + raise ValueError + self.assertRaises(ValueError, self.func, 42, BadSeq()) + + # Test reduce()'s use of iterators. + def test_iterator_usage(self): + class SequenceClass: + def __init__(self, n): + self.n = n + def __getitem__(self, i): + if 0 <= i < self.n: + return i + else: + raise IndexError + + from operator import add + self.assertEqual(self.func(add, SequenceClass(5)), 10) + self.assertEqual(self.func(add, SequenceClass(5), 42), 52) + self.assertRaises(TypeError, self.func, add, SequenceClass(0)) + self.assertEqual(self.func(add, SequenceClass(0), 42), 42) + self.assertEqual(self.func(add, SequenceClass(1)), 0) + self.assertEqual(self.func(add, SequenceClass(1), 42), 42) + + d = {"one": 1, "two": 2, "three": 3} + self.assertEqual(self.func(add, d), "".join(d.keys())) + + def test_main(verbose=None): @@ -268,7 +336,8 @@ TestPartialSubclass, TestPythonPartial, TestUpdateWrapper, - TestWraps + TestWraps, + TestReduce ) test_support.run_unittest(*test_classes) Modified: python/branches/p3yk/Misc/Vim/python.vim ============================================================================== --- python/branches/p3yk/Misc/Vim/python.vim (original) +++ python/branches/p3yk/Misc/Vim/python.vim Sat Aug 26 22:49:04 2006 @@ -63,7 +63,7 @@ if exists("python_highlight_builtins") syn keyword pythonBuiltin unichr all set abs vars int __import__ unicode - syn keyword pythonBuiltin enumerate reduce exit issubclass + syn keyword pythonBuiltin enumerate exit issubclass syn keyword pythonBuiltin divmod file Ellipsis isinstance open any syn keyword pythonBuiltin locals help filter basestring slice copyright min syn keyword pythonBuiltin super sum tuple hex execfile long id chr Modified: python/branches/p3yk/Misc/cheatsheet ============================================================================== --- python/branches/p3yk/Misc/cheatsheet (original) +++ python/branches/p3yk/Misc/cheatsheet Sat Aug 26 22:49:04 2006 @@ -901,7 +901,7 @@ -- Creates an anonymous function. returnedExpr must be an expression, not a statement (e.g., not "if xx:...", "print xxx", etc.) and thus can't contain newlines. - Used mostly for filter(), map(), reduce() functions, and GUI callbacks.. + Used mostly for filter(), map() functions, and GUI callbacks.. List comprehensions result = [expression for item1 in sequence1 [if condition1] [for item2 in sequence2 ... for itemN in sequenceN] @@ -1005,11 +1005,6 @@ range(start [,end Returns list of ints from >= start and < end.With 1 arg, [, step]]) list from 0..arg-1With 2 args, list from start..end-1With 3 args, list from start up to end by step -reduce(f, list [, Applies the binary function f to the items oflist so as to -init]) reduce the list to a single value.If init given, it is - "prepended" to list. - Re-parses and re-initializes an already imported module. - Useful in interactive mode, if you want to reload amodule reload(module) after fixing it. If module was syntacticallycorrect but had an error in initialization, mustimport it one more time before calling reload(). Modified: python/branches/p3yk/Misc/python-mode.el ============================================================================== --- python/branches/p3yk/Misc/python-mode.el (original) +++ python/branches/p3yk/Misc/python-mode.el Sat Aug 26 22:49:04 2006 @@ -386,7 +386,7 @@ "isinstance" "issubclass" "iter" "len" "license" "list" "locals" "long" "map" "max" "min" "object" "oct" "open" "ord" "pow" "property" "range" - "reduce" "reload" "repr" "round" + "reload" "repr" "round" "setattr" "slice" "staticmethod" "str" "sum" "super" "tuple" "type" "unichr" "unicode" "vars" "zip") Modified: python/branches/p3yk/Modules/_functoolsmodule.c ============================================================================== --- python/branches/p3yk/Modules/_functoolsmodule.c (original) +++ python/branches/p3yk/Modules/_functoolsmodule.c Sat Aug 26 22:49:04 2006 @@ -242,12 +242,88 @@ }; +/* reduce (used to be a builtin) ********************************************/ + +static PyObject * +functools_reduce(PyObject *self, PyObject *args) +{ + PyObject *seq, *func, *result = NULL, *it; + + if (!PyArg_UnpackTuple(args, "reduce", 2, 3, &func, &seq, &result)) + return NULL; + if (result != NULL) + Py_INCREF(result); + + it = PyObject_GetIter(seq); + if (it == NULL) { + PyErr_SetString(PyExc_TypeError, + "reduce() arg 2 must support iteration"); + Py_XDECREF(result); + return NULL; + } + + if ((args = PyTuple_New(2)) == NULL) + goto Fail; + + for (;;) { + PyObject *op2; + + if (args->ob_refcnt > 1) { + Py_DECREF(args); + if ((args = PyTuple_New(2)) == NULL) + goto Fail; + } + + op2 = PyIter_Next(it); + if (op2 == NULL) { + if (PyErr_Occurred()) + goto Fail; + break; + } + + if (result == NULL) + result = op2; + else { + PyTuple_SetItem(args, 0, result); + PyTuple_SetItem(args, 1, op2); + if ((result = PyEval_CallObject(func, args)) == NULL) + goto Fail; + } + } + + Py_DECREF(args); + + if (result == NULL) + PyErr_SetString(PyExc_TypeError, + "reduce() of empty sequence with no initial value"); + + Py_DECREF(it); + return result; + +Fail: + Py_XDECREF(args); + Py_XDECREF(result); + Py_DECREF(it); + return NULL; +} + +PyDoc_STRVAR(functools_reduce_doc, +"reduce(function, sequence[, initial]) -> value\n\ +\n\ +Apply a function of two arguments cumulatively to the items of a sequence,\n\ +from left to right, so as to reduce the sequence to a single value.\n\ +For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n\ +((((1+2)+3)+4)+5). If initial is present, it is placed before the items\n\ +of the sequence in the calculation, and serves as a default when the\n\ +sequence is empty."); + /* module level code ********************************************************/ PyDoc_STRVAR(module_doc, "Tools that operate on functions."); static PyMethodDef module_methods[] = { + {"reduce", functools_reduce, METH_VARARGS, functools_reduce_doc}, {NULL, NULL} /* sentinel */ }; Modified: python/branches/p3yk/Python/Python-ast.c ============================================================================== --- python/branches/p3yk/Python/Python-ast.c (original) +++ python/branches/p3yk/Python/Python-ast.c Sat Aug 26 22:49:04 2006 @@ -3012,7 +3012,7 @@ if (PyDict_SetItemString(d, "AST", (PyObject*)AST_type) < 0) return; if (PyModule_AddIntConstant(m, "PyCF_ONLY_AST", PyCF_ONLY_AST) < 0) return; - if (PyModule_AddStringConstant(m, "__version__", "45597") < 0) + if (PyModule_AddStringConstant(m, "__version__", "51600") < 0) return; if (PyDict_SetItemString(d, "mod", (PyObject*)mod_type) < 0) return; if (PyDict_SetItemString(d, "Module", (PyObject*)Module_type) < 0) From python-3000-checkins at python.org Sun Aug 27 03:03:38 2006 From: python-3000-checkins at python.org (brett.cannon) Date: Sun, 27 Aug 2006 03:03:38 +0200 (CEST) Subject: [Python-3000-checkins] r51627 - python/branches/p3yk/Lib/compiler/ast.py Message-ID: <20060827010338.38E211E4008@bag.python.org> Author: brett.cannon Date: Sun Aug 27 03:03:34 2006 New Revision: 51627 Modified: python/branches/p3yk/Lib/compiler/ast.py Log: Vestige of code from removing backticks. Closes patch #1500623. Thanks, Collin Winter. Modified: python/branches/p3yk/Lib/compiler/ast.py ============================================================================== --- python/branches/p3yk/Lib/compiler/ast.py (original) +++ python/branches/p3yk/Lib/compiler/ast.py Sun Aug 27 03:03:34 2006 @@ -203,20 +203,6 @@ def __repr__(self): return "AugAssign(%s, %s, %s)" % (repr(self.node), repr(self.op), repr(self.expr)) -class Backquote(Node): - def __init__(self, expr, lineno=None): - self.expr = expr - self.lineno = lineno - - def getChildren(self): - return self.expr, - - def getChildNodes(self): - return self.expr, - - def __repr__(self): - return "Backquote(%s)" % (repr(self.expr),) - class Bitand(Node): def __init__(self, nodes, lineno=None): self.nodes = nodes From barry at python.org Mon Aug 28 04:30:36 2006 From: barry at python.org (Barry Warsaw) Date: Sun, 27 Aug 2006 22:30:36 -0400 Subject: [Python-3000-checkins] r51584 - python/branches/p3yk/Lib/plat-riscos/riscosenviron.py python/branches/p3yk/Lib/plat-riscos/rourl2path.py In-Reply-To: <9e804ac0608241811o500e126dy5712b63970aadf2@mail.gmail.com> References: <20060825010614.90EE61E4011@bag.python.org> <9e804ac0608241811o500e126dy5712b63970aadf2@mail.gmail.com> Message-ID: <8EA8F090-345C-4D57-8B60-020F0483A947@python.org> On Aug 24, 2006, at 9:11 PM, Thomas Wouters wrote: > > On 8/24/06, brett.cannon wrote: > Even more removals of '<>'; I can hear Barry shedding a manly tear ... > > Not just Barry, although I already shed most of my tears when Guido > actually removed <>. >;-< Misery loves company ;} http://www.artima.com/forums/flat.jsp?forum=106&thread=173477 -Barry From python-3000-checkins at python.org Mon Aug 28 17:27:38 2006 From: python-3000-checkins at python.org (guido.van.rossum) Date: Mon, 28 Aug 2006 17:27:38 +0200 (CEST) Subject: [Python-3000-checkins] r51631 - in python/branches/p3yk: Doc/lib/libdis.tex Grammar/Grammar Include/Python-ast.h Include/graminit.h Include/opcode.h Lib/compiler/ast.py Lib/compiler/pyassem.py Lib/compiler/pycodegen.py Lib/compiler/transformer.py Lib/opcode.py Lib/test/test_grammar.py Lib/test/test_set.py Objects/setobject.c Parser/Python.asdl Python/Python-ast.c Python/ast.c Python/ceval.c Python/compile.c Python/graminit.c Python/import.c Tools/compiler/ast.txt Tools/compiler/astgen.py Message-ID: <20060828152738.EDB331E4003@bag.python.org> Author: guido.van.rossum Date: Mon Aug 28 17:27:34 2006 New Revision: 51631 Modified: python/branches/p3yk/Doc/lib/libdis.tex python/branches/p3yk/Grammar/Grammar python/branches/p3yk/Include/Python-ast.h python/branches/p3yk/Include/graminit.h python/branches/p3yk/Include/opcode.h python/branches/p3yk/Lib/compiler/ast.py python/branches/p3yk/Lib/compiler/pyassem.py python/branches/p3yk/Lib/compiler/pycodegen.py python/branches/p3yk/Lib/compiler/transformer.py python/branches/p3yk/Lib/opcode.py python/branches/p3yk/Lib/test/test_grammar.py python/branches/p3yk/Lib/test/test_set.py python/branches/p3yk/Objects/setobject.c python/branches/p3yk/Parser/Python.asdl python/branches/p3yk/Python/Python-ast.c python/branches/p3yk/Python/ast.c python/branches/p3yk/Python/ceval.c python/branches/p3yk/Python/compile.c python/branches/p3yk/Python/graminit.c python/branches/p3yk/Python/import.c python/branches/p3yk/Tools/compiler/ast.txt python/branches/p3yk/Tools/compiler/astgen.py Log: SF patch 1547796 by Georg Brandl -- set literals. Modified: python/branches/p3yk/Doc/lib/libdis.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libdis.tex (original) +++ python/branches/p3yk/Doc/lib/libdis.tex Mon Aug 28 17:27:34 2006 @@ -501,6 +501,10 @@ Works as \code{BUILD_TUPLE}, but creates a list. \end{opcodedesc} +\begin{opcodedesc}{BUILD_SET}{count} +Works as \code{BUILD_TUPLE}, but creates a set. +\end{opcodedesc} + \begin{opcodedesc}{BUILD_MAP}{zero} Pushes a new empty dictionary object onto the stack. The argument is ignored and set to zero by the compiler. Modified: python/branches/p3yk/Grammar/Grammar ============================================================================== --- python/branches/p3yk/Grammar/Grammar (original) +++ python/branches/p3yk/Grammar/Grammar Mon Aug 28 17:27:34 2006 @@ -101,7 +101,7 @@ power: atom trailer* ['**' factor] atom: ('(' [yield_expr|testlist_gexp] ')' | '[' [listmaker] ']' | - '{' [dictmaker] '}' | + '{' [dictsetmaker] '}' | NAME | NUMBER | STRING+) listmaker: test ( list_for | (',' test)* [','] ) testlist_gexp: test ( gen_for | (',' test)* [','] ) @@ -112,7 +112,7 @@ sliceop: ':' [test] exprlist: expr (',' expr)* [','] testlist: test (',' test)* [','] -dictmaker: test ':' test (',' test ':' test)* [','] +dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [',']) classdef: 'class' NAME ['(' [testlist] ')'] ':' suite Modified: python/branches/p3yk/Include/Python-ast.h ============================================================================== --- python/branches/p3yk/Include/Python-ast.h (original) +++ python/branches/p3yk/Include/Python-ast.h Mon Aug 28 17:27:34 2006 @@ -184,10 +184,10 @@ }; enum _expr_kind {BoolOp_kind=1, BinOp_kind=2, UnaryOp_kind=3, Lambda_kind=4, - IfExp_kind=5, Dict_kind=6, ListComp_kind=7, - GeneratorExp_kind=8, Yield_kind=9, Compare_kind=10, - Call_kind=11, Num_kind=12, Str_kind=13, Attribute_kind=14, - Subscript_kind=15, Name_kind=16, List_kind=17, Tuple_kind=18}; + IfExp_kind=5, Dict_kind=6, Set_kind=7, ListComp_kind=8, + GeneratorExp_kind=9, Yield_kind=10, Compare_kind=11, + Call_kind=12, Num_kind=13, Str_kind=14, Attribute_kind=15, + Subscript_kind=16, Name_kind=17, List_kind=18, Tuple_kind=19}; struct _expr { enum _expr_kind kind; union { @@ -224,6 +224,10 @@ } Dict; struct { + asdl_seq *elts; + } Set; + + struct { expr_ty elt; asdl_seq *generators; } ListComp; @@ -399,6 +403,7 @@ col_offset, PyArena *arena); expr_ty Dict(asdl_seq * keys, asdl_seq * values, int lineno, int col_offset, PyArena *arena); +expr_ty Set(asdl_seq * elts, int lineno, int col_offset, PyArena *arena); expr_ty ListComp(expr_ty elt, asdl_seq * generators, int lineno, int col_offset, PyArena *arena); expr_ty GeneratorExp(expr_ty elt, asdl_seq * generators, int lineno, int Modified: python/branches/p3yk/Include/graminit.h ============================================================================== --- python/branches/p3yk/Include/graminit.h (original) +++ python/branches/p3yk/Include/graminit.h Mon Aug 28 17:27:34 2006 @@ -69,7 +69,7 @@ #define sliceop 324 #define exprlist 325 #define testlist 326 -#define dictmaker 327 +#define dictsetmaker 327 #define classdef 328 #define arglist 329 #define argument 330 Modified: python/branches/p3yk/Include/opcode.h ============================================================================== --- python/branches/p3yk/Include/opcode.h (original) +++ python/branches/p3yk/Include/opcode.h Mon Aug 28 17:27:34 2006 @@ -97,11 +97,12 @@ #define LOAD_NAME 101 /* Index in name list */ #define BUILD_TUPLE 102 /* Number of tuple items */ #define BUILD_LIST 103 /* Number of list items */ -#define BUILD_MAP 104 /* Always zero for now */ -#define LOAD_ATTR 105 /* Index in name list */ -#define COMPARE_OP 106 /* Comparison operator */ -#define IMPORT_NAME 107 /* Index in name list */ -#define IMPORT_FROM 108 /* Index in name list */ +#define BUILD_SET 104 /* Number of set items */ +#define BUILD_MAP 105 /* Always zero for now */ +#define LOAD_ATTR 106 /* Index in name list */ +#define COMPARE_OP 107 /* Comparison operator */ +#define IMPORT_NAME 108 /* Index in name list */ +#define IMPORT_FROM 109 /* Index in name list */ #define JUMP_FORWARD 110 /* Number of bytes to skip */ #define JUMP_IF_FALSE 111 /* "" */ Modified: python/branches/p3yk/Lib/compiler/ast.py ============================================================================== --- python/branches/p3yk/Lib/compiler/ast.py (original) +++ python/branches/p3yk/Lib/compiler/ast.py Mon Aug 28 17:27:34 2006 @@ -542,7 +542,6 @@ self.kwargs = 1 - def getChildren(self): children = [] children.append(self.decorators) @@ -572,6 +571,7 @@ self.argnames = ['.0'] self.varargs = self.kwargs = None + def getChildren(self): return self.code, @@ -589,7 +589,6 @@ self.lineno = lineno self.is_outmost = False - def getChildren(self): children = [] children.append(self.assign) @@ -766,7 +765,6 @@ self.kwargs = 1 - def getChildren(self): children = [] children.append(self.argnames) @@ -1091,6 +1089,22 @@ def __repr__(self): return "RightShift((%s, %s))" % (repr(self.left), repr(self.right)) +class Set(Node): + def __init__(self, items, lineno=None): + self.items = items + self.lineno = lineno + + def getChildren(self): + return tuple(flatten(self.items)) + + def getChildNodes(self): + nodelist = [] + nodelist.extend(flatten_nodes(self.items)) + return tuple(nodelist) + + def __repr__(self): + return "Set(%s)" % (repr(self.items),) + class Slice(Node): def __init__(self, expr, flags, lower, upper, lineno=None): self.expr = expr Modified: python/branches/p3yk/Lib/compiler/pyassem.py ============================================================================== --- python/branches/p3yk/Lib/compiler/pyassem.py (original) +++ python/branches/p3yk/Lib/compiler/pyassem.py Mon Aug 28 17:27:34 2006 @@ -793,6 +793,8 @@ return -count+1 def BUILD_LIST(self, count): return -count+1 + def BUILD_SET(self, count): + return -count+1 def CALL_FUNCTION(self, argc): hi, lo = divmod(argc, 256) return -(lo + hi * 2) Modified: python/branches/p3yk/Lib/compiler/pycodegen.py ============================================================================== --- python/branches/p3yk/Lib/compiler/pycodegen.py (original) +++ python/branches/p3yk/Lib/compiler/pycodegen.py Mon Aug 28 17:27:34 2006 @@ -1241,6 +1241,12 @@ self.visit(elt) self.emit('BUILD_LIST', len(node.nodes)) + def visitSet(self, node): + self.set_lineno(node) + for elt in node.items: + self.visit(elt) + self.emit('BUILD_SET', len(node.items)) + def visitSliceobj(self, node): for child in node.nodes: self.visit(child) Modified: python/branches/p3yk/Lib/compiler/transformer.py ============================================================================== --- python/branches/p3yk/Lib/compiler/transformer.py (original) +++ python/branches/p3yk/Lib/compiler/transformer.py Mon Aug 28 17:27:34 2006 @@ -738,7 +738,7 @@ def atom_lbrace(self, nodelist): if nodelist[1][0] == token.RBRACE: return Dict((), lineno=nodelist[0][2]) - return self.com_dictmaker(nodelist[1]) + return self.com_dictsetmaker(nodelist[1]) def atom_backquote(self, nodelist): return Backquote(self.com_node(nodelist[1])) @@ -1182,13 +1182,20 @@ assert node[0] == symbol.gen_iter return node[1] - def com_dictmaker(self, nodelist): - # dictmaker: test ':' test (',' test ':' value)* [','] + def com_dictsetmaker(self, nodelist): + # dictsetmaker: (test ':' test (',' test ':' value)* [',']) | (test (',' test)* [',']) items = [] - for i in range(1, len(nodelist), 4): - items.append((self.com_node(nodelist[i]), - self.com_node(nodelist[i+2]))) - return Dict(items, lineno=items[0][0].lineno) + if nodelist[2] != ':': + # it's a set + for i in range(1, len(nodelist), 2): + items.append(self.com_node(nodelist[i])) + return Set(items, lineno=items[0].lineno) + else: + # it's a dict + for i in range(1, len(nodelist), 4): + items.append((self.com_node(nodelist[i]), + self.com_node(nodelist[i+2]))) + return Dict(items, lineno=items[0][0].lineno) def com_apply_trailer(self, primaryNode, nodelist): t = nodelist[1][0] Modified: python/branches/p3yk/Lib/opcode.py ============================================================================== --- python/branches/p3yk/Lib/opcode.py (original) +++ python/branches/p3yk/Lib/opcode.py Mon Aug 28 17:27:34 2006 @@ -137,12 +137,13 @@ name_op('LOAD_NAME', 101) # Index in name list def_op('BUILD_TUPLE', 102) # Number of tuple items def_op('BUILD_LIST', 103) # Number of list items -def_op('BUILD_MAP', 104) # Always zero for now -name_op('LOAD_ATTR', 105) # Index in name list -def_op('COMPARE_OP', 106) # Comparison operator -hascompare.append(106) -name_op('IMPORT_NAME', 107) # Index in name list -name_op('IMPORT_FROM', 108) # Index in name list +def_op('BUILD_SET', 104) # Number of set items +def_op('BUILD_MAP', 105) # Always zero for now +name_op('LOAD_ATTR', 106) # Index in name list +def_op('COMPARE_OP', 107) # Comparison operator +hascompare.append(107) +name_op('IMPORT_NAME', 108) # Index in name list +name_op('IMPORT_FROM', 109) # Index in name list jrel_op('JUMP_FORWARD', 110) # Number of bytes to skip jrel_op('JUMP_IF_FALSE', 111) # "" Modified: python/branches/p3yk/Lib/test/test_grammar.py ============================================================================== --- python/branches/p3yk/Lib/test/test_grammar.py (original) +++ python/branches/p3yk/Lib/test/test_grammar.py Mon Aug 28 17:27:34 2006 @@ -685,8 +685,8 @@ print 'atoms' -### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictmaker] '}' | NAME | NUMBER | STRING -### dictmaker: test ':' test (',' test ':' test)* [','] +### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING +### dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [',']) x = (1) x = (1 or 2 or 3) @@ -706,6 +706,11 @@ x = {'one': 1, 'two': 2,} x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6} +x = {'one'} +x = {'one', 1,} +x = {'one', 'two', 'three'} +x = {2, 3, 4,} + x = x x = 'x' x = 123 Modified: python/branches/p3yk/Lib/test/test_set.py ============================================================================== --- python/branches/p3yk/Lib/test/test_set.py (original) +++ python/branches/p3yk/Lib/test/test_set.py Mon Aug 28 17:27:34 2006 @@ -261,6 +261,11 @@ t = self.thetype(s) self.assertNotEqual(id(s), id(t)) + def test_set_literal(self): + s = set([1,2,3]) + t = {1,2,3} + self.assertEqual(s, t) + def test_hash(self): self.assertRaises(TypeError, hash, self.s) @@ -626,7 +631,7 @@ self.set = set(self.values) self.dup = set(self.values) self.length = 0 - self.repr = "set([])" + self.repr = "{}" #------------------------------------------------------------------------------ @@ -637,7 +642,7 @@ self.set = set(self.values) self.dup = set(self.values) self.length = 1 - self.repr = "set([3])" + self.repr = "{3}" def test_in(self): self.failUnless(3 in self.set) @@ -654,7 +659,7 @@ self.set = set(self.values) self.dup = set(self.values) self.length = 1 - self.repr = "set([(0, 'zero')])" + self.repr = "{(0, 'zero')}" def test_in(self): self.failUnless((0, "zero") in self.set) Modified: python/branches/p3yk/Objects/setobject.c ============================================================================== --- python/branches/p3yk/Objects/setobject.c (original) +++ python/branches/p3yk/Objects/setobject.c Mon Aug 28 17:27:34 2006 @@ -530,14 +530,20 @@ char *emit = ""; /* No separator emitted on first pass */ char *separator = ", "; - fprintf(fp, "%s([", so->ob_type->tp_name); + if (so->ob_type == &PySet_Type) + fprintf(fp, "{"); + else + fprintf(fp, "%s([", so->ob_type->tp_name); while (set_next(so, &pos, &entry)) { fputs(emit, fp); emit = separator; if (PyObject_Print(entry->key, fp, 0) != 0) return -1; } - fputs("])", fp); + if (so->ob_type == &PySet_Type) + fputs("}", fp); + else + fputs("])", fp); return 0; } @@ -554,8 +560,15 @@ if (listrepr == NULL) return NULL; - result = PyString_FromFormat("%s(%s)", so->ob_type->tp_name, - PyString_AS_STRING(listrepr)); + if (so->ob_type == &PySet_Type) { + char *s = PyString_AS_STRING(listrepr); + s += 1; + s[strlen(s)-1] = 0; + result = PyString_FromFormat("{%s}", s); + } else { + result = PyString_FromFormat("%s(%s)", so->ob_type->tp_name, + PyString_AS_STRING(listrepr)); + } Py_DECREF(listrepr); return result; } Modified: python/branches/p3yk/Parser/Python.asdl ============================================================================== --- python/branches/p3yk/Parser/Python.asdl (original) +++ python/branches/p3yk/Parser/Python.asdl Mon Aug 28 17:27:34 2006 @@ -56,6 +56,7 @@ | Lambda(arguments args, expr body) | IfExp(expr test, expr body, expr orelse) | Dict(expr* keys, expr* values) + | Set(expr* elts) | ListComp(expr elt, comprehension* generators) | GeneratorExp(expr elt, comprehension* generators) -- the grammar constrains where yield expressions can occur Modified: python/branches/p3yk/Python/Python-ast.c ============================================================================== --- python/branches/p3yk/Python/Python-ast.c (original) +++ python/branches/p3yk/Python/Python-ast.c Mon Aug 28 17:27:34 2006 @@ -178,6 +178,10 @@ "keys", "values", }; +static PyTypeObject *Set_type; +static char *Set_fields[]={ + "elts", +}; static PyTypeObject *ListComp_type; static char *ListComp_fields[]={ "elt", @@ -517,6 +521,8 @@ if (!IfExp_type) return 0; Dict_type = make_type("Dict", expr_type, Dict_fields, 2); if (!Dict_type) return 0; + Set_type = make_type("Set", expr_type, Set_fields, 1); + if (!Set_type) return 0; ListComp_type = make_type("ListComp", expr_type, ListComp_fields, 2); if (!ListComp_type) return 0; GeneratorExp_type = make_type("GeneratorExp", expr_type, @@ -1435,6 +1441,22 @@ } expr_ty +Set(asdl_seq * elts, int lineno, int col_offset, PyArena *arena) +{ + expr_ty p; + p = (expr_ty)PyArena_Malloc(arena, sizeof(*p)); + if (!p) { + PyErr_NoMemory(); + return NULL; + } + p->kind = Set_kind; + p->v.Set.elts = elts; + p->lineno = lineno; + p->col_offset = col_offset; + return p; +} + +expr_ty ListComp(expr_ty elt, asdl_seq * generators, int lineno, int col_offset, PyArena *arena) { @@ -2424,6 +2446,15 @@ goto failed; Py_DECREF(value); break; + case Set_kind: + result = PyType_GenericNew(Set_type, NULL, NULL); + if (!result) goto failed; + value = ast2obj_list(o->v.Set.elts, ast2obj_expr); + if (!value) goto failed; + if (PyObject_SetAttrString(result, "elts", value) == -1) + goto failed; + Py_DECREF(value); + break; case ListComp_kind: result = PyType_GenericNew(ListComp_type, NULL, NULL); if (!result) goto failed; @@ -3069,6 +3100,7 @@ return; if (PyDict_SetItemString(d, "IfExp", (PyObject*)IfExp_type) < 0) return; if (PyDict_SetItemString(d, "Dict", (PyObject*)Dict_type) < 0) return; + if (PyDict_SetItemString(d, "Set", (PyObject*)Set_type) < 0) return; if (PyDict_SetItemString(d, "ListComp", (PyObject*)ListComp_type) < 0) return; if (PyDict_SetItemString(d, "GeneratorExp", Modified: python/branches/p3yk/Python/ast.c ============================================================================== --- python/branches/p3yk/Python/ast.c (original) +++ python/branches/p3yk/Python/ast.c Mon Aug 28 17:27:34 2006 @@ -394,6 +394,7 @@ expr_name = "list comprehension"; break; case Dict_kind: + case Set_kind: case Num_kind: case Str_kind: expr_name = "literal"; @@ -1187,7 +1188,7 @@ ast_for_atom(struct compiling *c, const node *n) { /* atom: '(' [yield_expr|testlist_gexp] ')' | '[' [listmaker] ']' - | '{' [dictmaker] '}' | NAME | NUMBER | STRING+ + | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING+ */ node *ch = CHILD(n, 0); @@ -1242,36 +1243,55 @@ else return ast_for_listcomp(c, ch); case LBRACE: { - /* dictmaker: test ':' test (',' test ':' test)* [','] */ + /* dictsetmaker: test ':' test (',' test ':' test)* [','] | + * test (',' test)* [','] */ int i, size; asdl_seq *keys, *values; ch = CHILD(n, 1); - size = (NCH(ch) + 1) / 4; /* +1 in case no trailing comma */ - keys = asdl_seq_new(size, c->c_arena); - if (!keys) - return NULL; - - values = asdl_seq_new(size, c->c_arena); - if (!values) - return NULL; - - for (i = 0; i < NCH(ch); i += 4) { - expr_ty expression; - - expression = ast_for_expr(c, CHILD(ch, i)); - if (!expression) - return NULL; + if (NCH(ch) == 1 || (NCH(ch) > 0 && STR(CHILD(ch, 1))[0] == ',')) { + /* it's a set */ + size = (NCH(ch) + 1) / 2; /* +1 in case no trailing comma */ + keys = asdl_seq_new(size, c->c_arena); + if (!keys) + return NULL; + + for (i = 0; i < NCH(ch); i += 2) { + expr_ty expression; + expression = ast_for_expr(c, CHILD(ch, i)); + if (!expression) + return NULL; + asdl_seq_SET(keys, i / 2, expression); + } + return Set(keys, LINENO(n), n->n_col_offset, c->c_arena); + } else { + /* it's a dict */ + size = (NCH(ch) + 1) / 4; /* +1 in case no trailing comma */ + keys = asdl_seq_new(size, c->c_arena); + if (!keys) + return NULL; + + values = asdl_seq_new(size, c->c_arena); + if (!values) + return NULL; + + for (i = 0; i < NCH(ch); i += 4) { + expr_ty expression; + + expression = ast_for_expr(c, CHILD(ch, i)); + if (!expression) + return NULL; - asdl_seq_SET(keys, i / 4, expression); + asdl_seq_SET(keys, i / 4, expression); - expression = ast_for_expr(c, CHILD(ch, i + 2)); - if (!expression) - return NULL; + expression = ast_for_expr(c, CHILD(ch, i + 2)); + if (!expression) + return NULL; - asdl_seq_SET(values, i / 4, expression); - } - return Dict(keys, values, LINENO(n), n->n_col_offset, c->c_arena); + asdl_seq_SET(values, i / 4, expression); + } + return Dict(keys, values, LINENO(n), n->n_col_offset, c->c_arena); + } } default: PyErr_Format(PyExc_SystemError, "unhandled atom %d", TYPE(ch)); Modified: python/branches/p3yk/Python/ceval.c ============================================================================== --- python/branches/p3yk/Python/ceval.c (original) +++ python/branches/p3yk/Python/ceval.c Mon Aug 28 17:27:34 2006 @@ -1945,6 +1945,24 @@ } break; + case BUILD_SET: + x = PySet_New(NULL); + if (x != NULL) { + for (; --oparg >= 0;) { + w = POP(); + if (err == 0) + err = PySet_Add(x, w); + Py_DECREF(w); + } + if (err != 0) { + Py_DECREF(x); + break; + } + PUSH(x); + continue; + } + break; + case BUILD_MAP: x = PyDict_New(); PUSH(x); Modified: python/branches/p3yk/Python/compile.c ============================================================================== --- python/branches/p3yk/Python/compile.c (original) +++ python/branches/p3yk/Python/compile.c Mon Aug 28 17:27:34 2006 @@ -851,6 +851,7 @@ return 1; case BUILD_TUPLE: case BUILD_LIST: + case BUILD_SET: return 1-oparg; case BUILD_MAP: return 1; @@ -2955,6 +2956,11 @@ ADDOP(c, STORE_SUBSCR); } break; + case Set_kind: + n = asdl_seq_LEN(e->v.Set.elts); + VISIT_SEQ(c, expr, e->v.Set.elts); + ADDOP_I(c, BUILD_SET, n); + break; case ListComp_kind: return compiler_listcomp(c, e); case GeneratorExp_kind: Modified: python/branches/p3yk/Python/graminit.c ============================================================================== --- python/branches/p3yk/Python/graminit.c (original) +++ python/branches/p3yk/Python/graminit.c Mon Aug 28 17:27:34 2006 @@ -1500,26 +1500,42 @@ static arc arcs_71_0[1] = { {26, 1}, }; -static arc arcs_71_1[1] = { +static arc arcs_71_1[3] = { {21, 2}, + {27, 3}, + {0, 1}, }; static arc arcs_71_2[1] = { - {26, 3}, + {26, 4}, }; static arc arcs_71_3[2] = { - {27, 4}, + {26, 5}, {0, 3}, }; static arc arcs_71_4[2] = { - {26, 1}, + {27, 6}, {0, 4}, }; -static state states_71[5] = { +static arc arcs_71_5[2] = { + {27, 3}, + {0, 5}, +}; +static arc arcs_71_6[2] = { + {26, 7}, + {0, 6}, +}; +static arc arcs_71_7[1] = { + {21, 2}, +}; +static state states_71[8] = { {1, arcs_71_0}, - {1, arcs_71_1}, + {3, arcs_71_1}, {1, arcs_71_2}, {2, arcs_71_3}, {2, arcs_71_4}, + {2, arcs_71_5}, + {2, arcs_71_6}, + {1, arcs_71_7}, }; static arc arcs_72_0[1] = { {157, 1}, @@ -1911,7 +1927,7 @@ "\000\040\010\000\000\000\000\000\000\000\000\000\000\000\000\000\140\010\311\000\000"}, {326, "testlist", 0, 3, states_70, "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\311\000\000"}, - {327, "dictmaker", 0, 5, states_71, + {327, "dictsetmaker", 0, 8, states_71, "\000\040\010\000\000\000\000\000\000\000\000\000\000\020\004\000\140\010\311\000\000"}, {328, "classdef", 0, 8, states_72, "\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\000\040\000"}, Modified: python/branches/p3yk/Python/import.c ============================================================================== --- python/branches/p3yk/Python/import.c (original) +++ python/branches/p3yk/Python/import.c Mon Aug 28 17:27:34 2006 @@ -66,9 +66,10 @@ storing constants that should have been removed) Python 3000: 3000 3010 (removed UNARY_CONVERT) + 3020 (added BUILD_SET) . */ -#define MAGIC (3010 | ((long)'\r'<<16) | ((long)'\n'<<24)) +#define MAGIC (3020 | ((long)'\r'<<16) | ((long)'\n'<<24)) /* Magic word as global; note that _PyImport_Init() can change the value of this global to accommodate for alterations of how the Modified: python/branches/p3yk/Tools/compiler/ast.txt ============================================================================== --- python/branches/p3yk/Tools/compiler/ast.txt (original) +++ python/branches/p3yk/Tools/compiler/ast.txt Mon Aug 28 17:27:34 2006 @@ -50,11 +50,11 @@ GenExprIf: test List: nodes! Dict: items! +Set: items! Not: expr Compare: expr, ops! Name: name* Global: names* -Backquote: expr Getattr: expr, attrname* CallFunc: node, args!, star_args& = None, dstar_args& = None Keyword: name*, expr @@ -97,7 +97,7 @@ self.kwargs = 1 init(GenExpr): - self.argnames = ['[outmost-iterable]'] + self.argnames = ['.0'] self.varargs = self.kwargs = None init(GenExprFor): Modified: python/branches/p3yk/Tools/compiler/astgen.py ============================================================================== --- python/branches/p3yk/Tools/compiler/astgen.py (original) +++ python/branches/p3yk/Tools/compiler/astgen.py Mon Aug 28 17:27:34 2006 @@ -235,7 +235,7 @@ This file is automatically generated by Tools/compiler/astgen.py """ -from consts import CO_VARARGS, CO_VARKEYWORDS +from compiler.consts import CO_VARARGS, CO_VARKEYWORDS def flatten(seq): l = [] From python-3000-checkins at python.org Mon Aug 28 18:38:23 2006 From: python-3000-checkins at python.org (georg.brandl) Date: Mon, 28 Aug 2006 18:38:23 +0200 (CEST) Subject: [Python-3000-checkins] r51632 - python/branches/p3yk/Python/Python-ast.c python/branches/p3yk/Python/symtable.c Message-ID: <20060828163823.7DDCE1E4004@bag.python.org> Author: georg.brandl Date: Mon Aug 28 18:38:22 2006 New Revision: 51632 Modified: python/branches/p3yk/Python/Python-ast.c python/branches/p3yk/Python/symtable.c Log: Fix set literals not being visited in symtable creation. Modified: python/branches/p3yk/Python/Python-ast.c ============================================================================== --- python/branches/p3yk/Python/Python-ast.c (original) +++ python/branches/p3yk/Python/Python-ast.c Mon Aug 28 18:38:22 2006 @@ -3043,7 +3043,7 @@ if (PyDict_SetItemString(d, "AST", (PyObject*)AST_type) < 0) return; if (PyModule_AddIntConstant(m, "PyCF_ONLY_AST", PyCF_ONLY_AST) < 0) return; - if (PyModule_AddStringConstant(m, "__version__", "51600") < 0) + if (PyModule_AddStringConstant(m, "__version__", "51631") < 0) return; if (PyDict_SetItemString(d, "mod", (PyObject*)mod_type) < 0) return; if (PyDict_SetItemString(d, "Module", (PyObject*)Module_type) < 0) Modified: python/branches/p3yk/Python/symtable.c ============================================================================== --- python/branches/p3yk/Python/symtable.c (original) +++ python/branches/p3yk/Python/symtable.c Mon Aug 28 18:38:22 2006 @@ -1147,6 +1147,9 @@ VISIT_SEQ(st, expr, e->v.Dict.keys); VISIT_SEQ(st, expr, e->v.Dict.values); break; + case Set_kind: + VISIT_SEQ(st, expr, e->v.Set.elts); + break; case ListComp_kind: if (!symtable_new_tmpname(st)) return 0; From python-3000-checkins at python.org Mon Aug 28 19:19:22 2006 From: python-3000-checkins at python.org (georg.brandl) Date: Mon, 28 Aug 2006 19:19:22 +0200 (CEST) Subject: [Python-3000-checkins] r51633 - python/branches/p3yk/Lib/compiler/transformer.py Message-ID: <20060828171922.7FF571E4004@bag.python.org> Author: georg.brandl Date: Mon Aug 28 19:19:22 2006 New Revision: 51633 Modified: python/branches/p3yk/Lib/compiler/transformer.py Log: Small fix for compiler module ./. set literals. Modified: python/branches/p3yk/Lib/compiler/transformer.py ============================================================================== --- python/branches/p3yk/Lib/compiler/transformer.py (original) +++ python/branches/p3yk/Lib/compiler/transformer.py Mon Aug 28 19:19:22 2006 @@ -1185,7 +1185,7 @@ def com_dictsetmaker(self, nodelist): # dictsetmaker: (test ':' test (',' test ':' value)* [',']) | (test (',' test)* [',']) items = [] - if nodelist[2] != ':': + if len(nodelist) == 1 or nodelist[1] != ':': # it's a set for i in range(1, len(nodelist), 2): items.append(self.com_node(nodelist[i])) From python-3000-checkins at python.org Mon Aug 28 21:37:12 2006 From: python-3000-checkins at python.org (georg.brandl) Date: Mon, 28 Aug 2006 21:37:12 +0200 (CEST) Subject: [Python-3000-checkins] r51634 - in python/branches/p3yk: Lib/test/test_set.py Objects/setobject.c Message-ID: <20060828193712.66E471E4004@bag.python.org> Author: georg.brandl Date: Mon Aug 28 21:37:11 2006 New Revision: 51634 Modified: python/branches/p3yk/Lib/test/test_set.py python/branches/p3yk/Objects/setobject.c Log: Fix str() and repr() of empty sets. Modified: python/branches/p3yk/Lib/test/test_set.py ============================================================================== --- python/branches/p3yk/Lib/test/test_set.py (original) +++ python/branches/p3yk/Lib/test/test_set.py Mon Aug 28 21:37:11 2006 @@ -631,7 +631,7 @@ self.set = set(self.values) self.dup = set(self.values) self.length = 0 - self.repr = "{}" + self.repr = "set()" #------------------------------------------------------------------------------ Modified: python/branches/p3yk/Objects/setobject.c ============================================================================== --- python/branches/p3yk/Objects/setobject.c (original) +++ python/branches/p3yk/Objects/setobject.c Mon Aug 28 21:37:11 2006 @@ -529,10 +529,17 @@ Py_ssize_t pos=0; char *emit = ""; /* No separator emitted on first pass */ char *separator = ", "; + int literalform = 0; - if (so->ob_type == &PySet_Type) + if (!so->used) { + fprintf(fp, "%s()", so->ob_type->tp_name); + return 0; + } + + if (so->ob_type == &PySet_Type) { + literalform = 1; fprintf(fp, "{"); - else + } else fprintf(fp, "%s([", so->ob_type->tp_name); while (set_next(so, &pos, &entry)) { fputs(emit, fp); @@ -540,7 +547,7 @@ if (PyObject_Print(entry->key, fp, 0) != 0) return -1; } - if (so->ob_type == &PySet_Type) + if (literalform) fputs("}", fp); else fputs("])", fp); @@ -552,6 +559,10 @@ { PyObject *keys, *result, *listrepr; + /* shortcut for the empty set */ + if (!so->used) + return PyString_FromFormat("%s()", so->ob_type->tp_name); + keys = PySequence_List((PyObject *)so); if (keys == NULL) return NULL; @@ -567,7 +578,7 @@ result = PyString_FromFormat("{%s}", s); } else { result = PyString_FromFormat("%s(%s)", so->ob_type->tp_name, - PyString_AS_STRING(listrepr)); + PyString_AS_STRING(listrepr)); } Py_DECREF(listrepr); return result; From python-3000-checkins at python.org Tue Aug 29 06:39:16 2006 From: python-3000-checkins at python.org (neal.norwitz) Date: Tue, 29 Aug 2006 06:39:16 +0200 (CEST) Subject: [Python-3000-checkins] r51639 - in python/branches/p3yk: Demo/rpc/nfsclient.py Demo/rpc/xdr.py Demo/scripts/lpwatch.py Demo/scripts/primes.py Demo/scripts/update.py Demo/sockets/gopher.py Demo/tkinter/guido/ShellWindow.py Doc/lib/email-unpack.py Doc/lib/libstdtypes.tex Doc/lib/libstdwin.tex Doc/ref/ref2.tex Doc/ref/ref3.tex Doc/ref/ref5.tex Misc/cheatsheet Misc/python-mode.el Objects/object.c Message-ID: <20060829043916.1258A1E4006@bag.python.org> Author: neal.norwitz Date: Tue Aug 29 06:39:12 2006 New Revision: 51639 Modified: python/branches/p3yk/Demo/rpc/nfsclient.py python/branches/p3yk/Demo/rpc/xdr.py python/branches/p3yk/Demo/scripts/lpwatch.py python/branches/p3yk/Demo/scripts/primes.py python/branches/p3yk/Demo/scripts/update.py python/branches/p3yk/Demo/sockets/gopher.py python/branches/p3yk/Demo/tkinter/guido/ShellWindow.py python/branches/p3yk/Doc/lib/email-unpack.py python/branches/p3yk/Doc/lib/libstdtypes.tex python/branches/p3yk/Doc/lib/libstdwin.tex python/branches/p3yk/Doc/ref/ref2.tex python/branches/p3yk/Doc/ref/ref3.tex python/branches/p3yk/Doc/ref/ref5.tex python/branches/p3yk/Misc/cheatsheet python/branches/p3yk/Misc/python-mode.el python/branches/p3yk/Objects/object.c Log: Get rid of most of the remaining uses of <>. There's still Tools/* thogh. Modified: python/branches/p3yk/Demo/rpc/nfsclient.py ============================================================================== --- python/branches/p3yk/Demo/rpc/nfsclient.py (original) +++ python/branches/p3yk/Demo/rpc/nfsclient.py Tue Aug 29 06:39:12 2006 @@ -163,7 +163,7 @@ ra = (dir, 0, 2000) while 1: (status, rest) = self.Readdir(ra) - if status <> NFS_OK: + if status != NFS_OK: break entries, eof = rest last_cookie = None Modified: python/branches/p3yk/Demo/rpc/xdr.py ============================================================================== --- python/branches/p3yk/Demo/rpc/xdr.py (original) +++ python/branches/p3yk/Demo/rpc/xdr.py Tue Aug 29 06:39:12 2006 @@ -78,7 +78,7 @@ self.pack_uint(0) def pack_farray(self, n, list, pack_item): - if len(list) <> n: + if len(list) != n: raise ValueError, 'wrong array size' for item in list: pack_item(item) @@ -183,7 +183,7 @@ while 1: x = self.unpack_uint() if x == 0: break - if x <> 1: + if x != 1: raise RuntimeError, '0 or 1 expected, got %r' % (x, ) item = unpack_item() list.append(item) Modified: python/branches/p3yk/Demo/scripts/lpwatch.py ============================================================================== --- python/branches/p3yk/Demo/scripts/lpwatch.py (original) +++ python/branches/p3yk/Demo/scripts/lpwatch.py Tue Aug 29 06:39:12 2006 @@ -74,7 +74,7 @@ ubytes = ubytes + bytes users[user] = ujobs, ubytes else: - if fields and fields[0] <> 'Rank': + if fields and fields[0] != 'Rank': line = string.strip(line) if line == 'no entries': line = name + ': idle' @@ -84,7 +84,7 @@ # if totaljobs: line = '%d K' % ((totalbytes+1023)/1024) - if totaljobs <> len(users): + if totaljobs != len(users): line = line + ' (%d jobs)' % totaljobs if len(users) == 1: line = line + ' for %s' % (users.keys()[0],) Modified: python/branches/p3yk/Demo/scripts/primes.py ============================================================================== --- python/branches/p3yk/Demo/scripts/primes.py (original) +++ python/branches/p3yk/Demo/scripts/primes.py Tue Aug 29 06:39:12 2006 @@ -18,7 +18,7 @@ while i <= max: for p in primes: if i%p == 0 or p*p > i: break - if i%p <> 0: + if i%p != 0: primes.append(i) if i >= min: print i i = i+2 Modified: python/branches/p3yk/Demo/scripts/update.py ============================================================================== --- python/branches/p3yk/Demo/scripts/update.py (original) +++ python/branches/p3yk/Demo/scripts/update.py Tue Aug 29 06:39:12 2006 @@ -83,7 +83,7 @@ print 'Funny line:', line, continue filename, lineno = prog.group(1, 2) - if not curfile or filename <> curfile.filename: + if not curfile or filename != curfile.filename: if curfile: curfile.finish() curfile = FileObj(filename) curfile.process(lineno, line[n:]) Modified: python/branches/p3yk/Demo/sockets/gopher.py ============================================================================== --- python/branches/p3yk/Demo/sockets/gopher.py (original) +++ python/branches/p3yk/Demo/sockets/gopher.py Tue Aug 29 06:39:12 2006 @@ -246,7 +246,7 @@ def browse_telnet(selector, host, port): if selector: print 'Log in as', repr(selector) - if type(port) <> type(''): + if type(port) != type(''): port = repr(port) sts = os.system('set -x; exec telnet ' + host + ' ' + port) if sts: Modified: python/branches/p3yk/Demo/tkinter/guido/ShellWindow.py ============================================================================== --- python/branches/p3yk/Demo/tkinter/guido/ShellWindow.py (original) +++ python/branches/p3yk/Demo/tkinter/guido/ShellWindow.py Tue Aug 29 06:39:12 2006 @@ -115,11 +115,11 @@ os.close(i) except os.error: pass - if os.dup(p2cread) <> 0: + if os.dup(p2cread) != 0: sys.stderr.write('popen2: bad read dup\n') - if os.dup(c2pwrite) <> 1: + if os.dup(c2pwrite) != 1: sys.stderr.write('popen2: bad write dup\n') - if os.dup(c2pwrite) <> 2: + if os.dup(c2pwrite) != 2: sys.stderr.write('popen2: bad write dup\n') for i in range(3, MAXFD): try: Modified: python/branches/p3yk/Doc/lib/email-unpack.py ============================================================================== --- python/branches/p3yk/Doc/lib/email-unpack.py (original) +++ python/branches/p3yk/Doc/lib/email-unpack.py Tue Aug 29 06:39:12 2006 @@ -37,7 +37,7 @@ os.mkdir(opts.directory) except OSError, e: # Ignore directory exists error - if e.errno <> errno.EEXIST: + if e.errno != errno.EEXIST: raise fp = open(msgfile) Modified: python/branches/p3yk/Doc/lib/libstdtypes.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libstdtypes.tex (original) +++ python/branches/p3yk/Doc/lib/libstdtypes.tex Tue Aug 29 06:39:12 2006 @@ -126,8 +126,7 @@ \lineiii{>}{strictly greater than}{} \lineiii{>=}{greater than or equal}{} \lineiii{==}{equal}{} - \lineiii{!=}{not equal}{(1)} - \lineiii{<>}{not equal}{(1)} + \lineiii{!=}{not equal} \lineiii{is}{object identity}{} \lineiii{is not}{negated object identity}{} \end{tableiii} @@ -136,17 +135,6 @@ \opindex{is} \opindex{is not} -\noindent -Notes: - -\begin{description} - -\item[(1)] -\code{<>} and \code{!=} are alternate spellings for the same operator. -\code{!=} is the preferred spelling; \code{<>} is obsolescent. - -\end{description} - Objects of different types, except different numeric types and different string types, never compare equal; such objects are ordered consistently but arbitrarily (so that sorting a heterogeneous array yields a consistent result). Modified: python/branches/p3yk/Doc/lib/libstdwin.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libstdwin.tex (original) +++ python/branches/p3yk/Doc/lib/libstdwin.tex Tue Aug 29 06:39:12 2006 @@ -123,8 +123,8 @@ Hint: the following code tests whether you are on a machine that supports more than two colors: \begin{verbatim} -if stdwin.fetchcolor('black') <> \ - stdwin.fetchcolor('red') <> \ +if stdwin.fetchcolor('black') != \ + stdwin.fetchcolor('red') != \ stdwin.fetchcolor('white'): print 'color machine' else: Modified: python/branches/p3yk/Doc/ref/ref2.tex ============================================================================== --- python/branches/p3yk/Doc/ref/ref2.tex (original) +++ python/branches/p3yk/Doc/ref/ref2.tex Tue Aug 29 06:39:12 2006 @@ -689,13 +689,9 @@ \begin{verbatim} + - * ** / // % << >> & | ^ ~ -< > <= >= == != <> +< > <= >= == != \end{verbatim} -The comparison operators \code{<>} and \code{!=} are alternate -spellings of the same operator. \code{!=} is the preferred spelling; -\code{<>} is obsolescent. - \section{Delimiters\label{delimiters}} Modified: python/branches/p3yk/Doc/ref/ref3.tex ============================================================================== --- python/branches/p3yk/Doc/ref/ref3.tex (original) +++ python/branches/p3yk/Doc/ref/ref3.tex Tue Aug 29 06:39:12 2006 @@ -1243,8 +1243,7 @@ \code{\var{x}<\var{y}} calls \code{\var{x}.__lt__(\var{y})}, \code{\var{x}<=\var{y}} calls \code{\var{x}.__le__(\var{y})}, \code{\var{x}==\var{y}} calls \code{\var{x}.__eq__(\var{y})}, -\code{\var{x}!=\var{y}} and \code{\var{x}<>\var{y}} call -\code{\var{x}.__ne__(\var{y})}, +\code{\var{x}!=\var{y}} calls \code{\var{x}.__ne__(\var{y})}, \code{\var{x}>\var{y}} calls \code{\var{x}.__gt__(\var{y})}, and \code{\var{x}>=\var{y}} calls \code{\var{x}.__ge__(\var{y})}. These methods can return any value, but if the comparison operator is Modified: python/branches/p3yk/Doc/ref/ref5.tex ============================================================================== --- python/branches/p3yk/Doc/ref/ref5.tex (original) +++ python/branches/p3yk/Doc/ref/ref5.tex Tue Aug 29 06:39:12 2006 @@ -832,7 +832,7 @@ \production{comparison} {\token{or_expr} ( \token{comp_operator} \token{or_expr} )*} \production{comp_operator} - {"<" | ">" | "==" | ">=" | "<=" | "<>" | "!="} + {"<" | ">" | "==" | ">=" | "<=" | "!="} \productioncont{| "is" ["not"] | ["not"] "in"} \end{productionlist} @@ -854,11 +854,6 @@ between \var{a} and \var{c}, so that, e.g., \code{x < y > z} is perfectly legal (though perhaps not pretty). -The forms \code{<>} and \code{!=} are equivalent; for consistency with -C, \code{!=} is preferred; where \code{!=} is mentioned below -\code{<>} is also accepted. The \code{<>} spelling is considered -obsolescent. - The operators \code{<}, \code{>}, \code{==}, \code{>=}, \code{<=}, and \code{!=} compare the values of two objects. The objects need not have the same type. @@ -1111,7 +1106,7 @@ \lineii{\keyword{in}, \keyword{not} \keyword{in}}{Membership tests} \lineii{\keyword{is}, \keyword{is not}}{Identity tests} \lineii{\code{<}, \code{<=}, \code{>}, \code{>=}, - \code{<>}, \code{!=}, \code{==}} + \code{!=}, \code{==}} {Comparisons} \hline \lineii{\code{|}} {Bitwise OR} Modified: python/branches/p3yk/Misc/cheatsheet ============================================================================== --- python/branches/p3yk/Misc/cheatsheet (original) +++ python/branches/p3yk/Misc/cheatsheet Tue Aug 29 06:39:12 2006 @@ -215,7 +215,6 @@ x^y Bitwise exclusive or x|y Bitwise or xy x>=y x==y x!=y Comparison, - x<>y identity, x is y x is not y membership x in s x not in s not x boolean negation @@ -241,7 +240,7 @@ > strictly greater than >= greater than or equal to == equal to -!= or <> not equal to +!= not equal to is object identity (2) is not negated object identity (2) @@ -1009,9 +1008,8 @@ an error in initialization, mustimport it one more time before calling reload(). Returns a string containing a printable and if possible -repr(object) evaluable representation of an object. <=> `object` - (usingbackquotes). Class redefinissable (__repr__). See - also str() +repr(object) evaluable representation of an object. + Class redefinable (__repr__). See also str(). round(x, n=0) Returns the floating point value x rounded to n digitsafter the decimal point. setattr(object, This is the counterpart of getattr().setattr(o, 'foobar', Modified: python/branches/p3yk/Misc/python-mode.el ============================================================================== --- python/branches/p3yk/Misc/python-mode.el (original) +++ python/branches/p3yk/Misc/python-mode.el Tue Aug 29 06:39:12 2006 @@ -690,8 +690,6 @@ ;; Both single quote and double quote are string delimiters (modify-syntax-entry ?\' "\"" py-mode-syntax-table) (modify-syntax-entry ?\" "\"" py-mode-syntax-table) - ;; backquote is open and close paren - (modify-syntax-entry ?\` "$" py-mode-syntax-table) ;; comment delimiters (modify-syntax-entry ?\# "<" py-mode-syntax-table) (modify-syntax-entry ?\n ">" py-mode-syntax-table) Modified: python/branches/p3yk/Objects/object.c ============================================================================== --- python/branches/p3yk/Objects/object.c (original) +++ python/branches/p3yk/Objects/object.c Tue Aug 29 06:39:12 2006 @@ -591,7 +591,7 @@ /* Give up */ PyErr_Format(PyExc_TypeError, - "unorderable types: '%.100s' <> '%.100s'", + "unorderable types: '%.100s' != '%.100s'", v->ob_type->tp_name, w->ob_type->tp_name); return -1; From python-3000-checkins at python.org Tue Aug 29 06:40:25 2006 From: python-3000-checkins at python.org (neal.norwitz) Date: Tue, 29 Aug 2006 06:40:25 +0200 (CEST) Subject: [Python-3000-checkins] r51640 - in python/branches/p3yk: Doc/lib/asttable.tex Include/token.h Lib/compiler/transformer.py Lib/pydoc.py Lib/token.py Modules/parsermodule.c Message-ID: <20060829044025.828731E4010@bag.python.org> Author: neal.norwitz Date: Tue Aug 29 06:40:24 2006 New Revision: 51640 Modified: python/branches/p3yk/Doc/lib/asttable.tex python/branches/p3yk/Include/token.h python/branches/p3yk/Lib/compiler/transformer.py python/branches/p3yk/Lib/pydoc.py python/branches/p3yk/Lib/token.py python/branches/p3yk/Modules/parsermodule.c Log: Get rid of some more cases of backquotes. parsermodule.c doesn't compile but looks like that was a problem before this change. Modified: python/branches/p3yk/Doc/lib/asttable.tex ============================================================================== --- python/branches/p3yk/Doc/lib/asttable.tex (original) +++ python/branches/p3yk/Doc/lib/asttable.tex Tue Aug 29 06:40:24 2006 @@ -36,9 +36,6 @@ \lineiii{}{\member{expr}}{} \hline -\lineiii{Backquote}{\member{expr}}{} -\hline - \lineiii{Bitand}{\member{nodes}}{} \hline Modified: python/branches/p3yk/Include/token.h ============================================================================== --- python/branches/p3yk/Include/token.h (original) +++ python/branches/p3yk/Include/token.h Tue Aug 29 06:40:24 2006 @@ -32,7 +32,7 @@ #define EQUAL 22 #define DOT 23 #define PERCENT 24 -#define BACKQUOTE 25 +/* #define BACKQUOTE 25 */ #define LBRACE 26 #define RBRACE 27 #define EQEQUAL 28 Modified: python/branches/p3yk/Lib/compiler/transformer.py ============================================================================== --- python/branches/p3yk/Lib/compiler/transformer.py (original) +++ python/branches/p3yk/Lib/compiler/transformer.py Tue Aug 29 06:40:24 2006 @@ -111,7 +111,6 @@ self._atom_dispatch = {token.LPAR: self.atom_lpar, token.LSQB: self.atom_lsqb, token.LBRACE: self.atom_lbrace, - token.BACKQUOTE: self.atom_backquote, token.NUMBER: self.atom_number, token.STRING: self.atom_string, token.NAME: self.atom_name, @@ -740,9 +739,6 @@ return Dict((), lineno=nodelist[0][2]) return self.com_dictsetmaker(nodelist[1]) - def atom_backquote(self, nodelist): - return Backquote(self.com_node(nodelist[1])) - def atom_number(self, nodelist): ### need to verify this matches compile.c k = eval(nodelist[0][1]) Modified: python/branches/p3yk/Lib/pydoc.py ============================================================================== --- python/branches/p3yk/Lib/pydoc.py (original) +++ python/branches/p3yk/Lib/pydoc.py Tue Aug 29 06:40:24 2006 @@ -1564,7 +1564,7 @@ 'CLASSES': ('ref/types', 'class SPECIALMETHODS PRIVATENAMES'), 'MODULES': ('lib/typesmodules', 'import'), 'PACKAGES': 'import', - 'EXPRESSIONS': ('ref/summary', 'lambda or and not in is BOOLEAN COMPARISON BITWISE SHIFTING BINARY FORMATTING POWER UNARY ATTRIBUTES SUBSCRIPTS SLICINGS CALLS TUPLES LISTS DICTIONARIES BACKQUOTES'), + 'EXPRESSIONS': ('ref/summary', 'lambda or and not in is BOOLEAN COMPARISON BITWISE SHIFTING BINARY FORMATTING POWER UNARY ATTRIBUTES SUBSCRIPTS SLICINGS CALLS TUPLES LISTS DICTIONARIES'), 'OPERATORS': 'EXPRESSIONS', 'PRECEDENCE': 'EXPRESSIONS', 'OBJECTS': ('ref/objects', 'TYPES'), @@ -1587,14 +1587,13 @@ 'IDENTIFIERS': ('ref/identifiers', 'keywords SPECIALIDENTIFIERS'), 'SPECIALIDENTIFIERS': ('ref/id-classes', ''), 'PRIVATENAMES': ('ref/atom-identifiers', ''), - 'LITERALS': ('ref/atom-literals', 'STRINGS BACKQUOTES NUMBERS TUPLELITERALS LISTLITERALS DICTIONARYLITERALS'), + 'LITERALS': ('ref/atom-literals', 'STRINGS NUMBERS TUPLELITERALS LISTLITERALS DICTIONARYLITERALS'), 'TUPLES': 'SEQUENCES', 'TUPLELITERALS': ('ref/exprlists', 'TUPLES LITERALS'), 'LISTS': ('lib/typesseq-mutable', 'LISTLITERALS'), 'LISTLITERALS': ('ref/lists', 'LISTS LITERALS'), 'DICTIONARIES': ('lib/typesmapping', 'DICTIONARYLITERALS'), 'DICTIONARYLITERALS': ('ref/dict', 'DICTIONARIES LITERALS'), - 'BACKQUOTES': ('ref/string-conversions', 'repr str STRINGS LITERALS'), 'ATTRIBUTES': ('ref/attribute-references', 'getattr hasattr setattr ATTRIBUTEMETHODS'), 'SUBSCRIPTS': ('ref/subscriptions', 'SEQUENCEMETHODS1'), 'SLICINGS': ('ref/slicings', 'SEQUENCEMETHODS2'), Modified: python/branches/p3yk/Lib/token.py ============================================================================== --- python/branches/p3yk/Lib/token.py (original) +++ python/branches/p3yk/Lib/token.py Tue Aug 29 06:40:24 2006 @@ -35,7 +35,6 @@ EQUAL = 22 DOT = 23 PERCENT = 24 -BACKQUOTE = 25 LBRACE = 26 RBRACE = 27 EQEQUAL = 28 Modified: python/branches/p3yk/Modules/parsermodule.c ============================================================================== --- python/branches/p3yk/Modules/parsermodule.c (original) +++ python/branches/p3yk/Modules/parsermodule.c Tue Aug 29 06:40:24 2006 @@ -2404,11 +2404,6 @@ if (res && (nch == 3)) res = validate_dictmaker(CHILD(tree, 1)); break; - case BACKQUOTE: - res = ((nch == 3) - && validate_testlist1(CHILD(tree, 1)) - && validate_ntype(CHILD(tree, 2), BACKQUOTE)); - break; case NAME: case NUMBER: res = (nch == 1); From python-3000-checkins at python.org Tue Aug 29 07:40:09 2006 From: python-3000-checkins at python.org (neal.norwitz) Date: Tue, 29 Aug 2006 07:40:09 +0200 (CEST) Subject: [Python-3000-checkins] r51641 - python/branches/p3yk/Lib/doctest.py Message-ID: <20060829054009.93DE11E4008@bag.python.org> Author: neal.norwitz Date: Tue Aug 29 07:40:08 2006 New Revision: 51641 Modified: python/branches/p3yk/Lib/doctest.py Log: Fix another typo. Modified: python/branches/p3yk/Lib/doctest.py ============================================================================== --- python/branches/p3yk/Lib/doctest.py (original) +++ python/branches/p3yk/Lib/doctest.py Tue Aug 29 07:40:08 2006 @@ -1562,7 +1562,7 @@ - test: the DocTest object being run - - excample: the Example object that failed + - example: the Example object that failed - got: the actual output """ From python-3000-checkins at python.org Tue Aug 29 07:53:34 2006 From: python-3000-checkins at python.org (neal.norwitz) Date: Tue, 29 Aug 2006 07:53:34 +0200 (CEST) Subject: [Python-3000-checkins] r51643 - python/branches/p3yk/Modules/parsermodule.c Message-ID: <20060829055334.1C37D1E4008@bag.python.org> Author: neal.norwitz Date: Tue Aug 29 07:53:33 2006 New Revision: 51643 Modified: python/branches/p3yk/Modules/parsermodule.c Log: Get parsermodule working again after adding set literals Modified: python/branches/p3yk/Modules/parsermodule.c ============================================================================== --- python/branches/p3yk/Modules/parsermodule.c (original) +++ python/branches/p3yk/Modules/parsermodule.c Tue Aug 29 07:53:33 2006 @@ -860,7 +860,7 @@ VALIDATER(atom); VALIDATER(lambdef); VALIDATER(trailer); VALIDATER(subscript); VALIDATER(subscriptlist); VALIDATER(sliceop); -VALIDATER(exprlist); VALIDATER(dictmaker); +VALIDATER(exprlist); VALIDATER(dictsetmaker); VALIDATER(arglist); VALIDATER(argument); VALIDATER(listmaker); VALIDATER(yield_stmt); VALIDATER(testlist1); VALIDATER(gen_for); @@ -2402,7 +2402,7 @@ && validate_ntype(CHILD(tree, nch - 1), RBRACE)); if (res && (nch == 3)) - res = validate_dictmaker(CHILD(tree, 1)); + res = validate_dictsetmaker(CHILD(tree, 1)); break; case NAME: case NUMBER: @@ -2838,10 +2838,10 @@ static int -validate_dictmaker(node *tree) +validate_dictsetmaker(node *tree) { int nch = NCH(tree); - int res = (validate_ntype(tree, dictmaker) + int res = (validate_ntype(tree, dictsetmaker) && (nch >= 3) && validate_test(CHILD(tree, 0)) && validate_colon(CHILD(tree, 1)) From nnorwitz at gmail.com Tue Aug 29 08:07:47 2006 From: nnorwitz at gmail.com (Neal Norwitz) Date: Mon, 28 Aug 2006 23:07:47 -0700 Subject: [Python-3000-checkins] r51631 - in python/branches/p3yk: Doc/lib/libdis.tex Grammar/Grammar Include/Python-ast.h Include/graminit.h Include/opcode.h Lib/compiler/ast.py Lib/compiler/pyassem.py Lib/compiler/pycodegen.py Lib/compiler/transformer.py Message-ID: On 8/28/06, guido.van.rossum wrote: > Modified: python/branches/p3yk/Lib/compiler/ast.py > ============================================================================== > --- python/branches/p3yk/Lib/compiler/ast.py (original) > +++ python/branches/p3yk/Lib/compiler/ast.py Mon Aug 28 17:27:34 2006 > @@ -1091,6 +1089,22 @@ > def __repr__(self): > return "RightShift((%s, %s))" % (repr(self.left), repr(self.right)) > > +class Set(Node): > + def __init__(self, items, lineno=None): > + self.items = items > + self.lineno = lineno > + > + def getChildren(self): > + return tuple(flatten(self.items)) > + > + def getChildNodes(self): > + nodelist = [] > + nodelist.extend(flatten_nodes(self.items)) > + return tuple(nodelist) Any reason to not use: return tuple(flatten_nodes(self.items)) ? n From nnorwitz at gmail.com Tue Aug 29 08:11:48 2006 From: nnorwitz at gmail.com (Neal Norwitz) Date: Mon, 28 Aug 2006 23:11:48 -0700 Subject: [Python-3000-checkins] r51632 - python/branches/p3yk/Python/Python-ast.c python/branches/p3yk/Python/symtable.c In-Reply-To: <20060828163823.7DDCE1E4004@bag.python.org> References: <20060828163823.7DDCE1E4004@bag.python.org> Message-ID: Can you add a test for this? On 8/28/06, georg.brandl wrote: > Author: georg.brandl > Date: Mon Aug 28 18:38:22 2006 > New Revision: 51632 > > Modified: > python/branches/p3yk/Python/Python-ast.c > python/branches/p3yk/Python/symtable.c > Log: > Fix set literals not being visited in symtable creation. > > > > Modified: python/branches/p3yk/Python/Python-ast.c > ============================================================================== > --- python/branches/p3yk/Python/Python-ast.c (original) > +++ python/branches/p3yk/Python/Python-ast.c Mon Aug 28 18:38:22 2006 > @@ -3043,7 +3043,7 @@ > if (PyDict_SetItemString(d, "AST", (PyObject*)AST_type) < 0) return; > if (PyModule_AddIntConstant(m, "PyCF_ONLY_AST", PyCF_ONLY_AST) < 0) > return; > - if (PyModule_AddStringConstant(m, "__version__", "51600") < 0) > + if (PyModule_AddStringConstant(m, "__version__", "51631") < 0) > return; > if (PyDict_SetItemString(d, "mod", (PyObject*)mod_type) < 0) return; > if (PyDict_SetItemString(d, "Module", (PyObject*)Module_type) < 0) > > Modified: python/branches/p3yk/Python/symtable.c > ============================================================================== > --- python/branches/p3yk/Python/symtable.c (original) > +++ python/branches/p3yk/Python/symtable.c Mon Aug 28 18:38:22 2006 > @@ -1147,6 +1147,9 @@ > VISIT_SEQ(st, expr, e->v.Dict.keys); > VISIT_SEQ(st, expr, e->v.Dict.values); > break; > + case Set_kind: > + VISIT_SEQ(st, expr, e->v.Set.elts); > + break; > case ListComp_kind: > if (!symtable_new_tmpname(st)) > return 0; > _______________________________________________ > Python-3000-checkins mailing list > Python-3000-checkins at python.org > http://mail.python.org/mailman/listinfo/python-3000-checkins > From python-3000-checkins at python.org Tue Aug 29 09:57:23 2006 From: python-3000-checkins at python.org (neal.norwitz) Date: Tue, 29 Aug 2006 09:57:23 +0200 (CEST) Subject: [Python-3000-checkins] r51645 - python/branches/p3yk/Misc/NEWS Message-ID: <20060829075723.22F551E4008@bag.python.org> Author: neal.norwitz Date: Tue Aug 29 09:57:22 2006 New Revision: 51645 Modified: python/branches/p3yk/Misc/NEWS Log: Get rid of more coerce cruft, update NEWS Modified: python/branches/p3yk/Misc/NEWS ============================================================================== --- python/branches/p3yk/Misc/NEWS (original) +++ python/branches/p3yk/Misc/NEWS Tue Aug 29 09:57:22 2006 @@ -32,11 +32,10 @@ - Get rid of various compatibility-related flags (e.g. division flags). + Core and Builtins ----------------- -- __coerce__ has been removed. - - Classic classes are a thing of the past. All classes are new style. - Exceptions *must* derive from BaseException. @@ -55,19 +54,23 @@ - Absolute import is the default behavior for 'import foo' etc. +- Removed support for syntax: + backticks (`x`), <> + - Removed these Python builtins: apply(), coerce(), input(), raw_input() +- Removed these Python methods: + {}.has_key + - Removed these Python slots: __coerce__, __div__, __idiv__, __rdiv__ - Removed these attributes from Python modules: * operator module: div, idiv, __div__, __idiv__ -*** PyNumber_CoerceEx() and nb_coerce still need to be removed. - - Removed these C APIs: - PyNumber_Coerce(), + PyNumber_Coerce(), PyNumber_CoerceEx() - Removed these C slots/fields: nb_divide, nb_inplace_divide @@ -80,7 +83,13 @@ getreadbufferproc, getwritebufferproc, getsegcountproc, getcharbufferproc - Removed these opcodes: - BINARY_DIVIDE, INPLACE_DIVIDE + BINARY_DIVIDE, INPLACE_DIVIDE, UNARY_CONVERT + +- zip returns an iterator + +- Additions: + set literals + Extension Modules ----------------- From python-3000-checkins at python.org Tue Aug 29 09:58:00 2006 From: python-3000-checkins at python.org (neal.norwitz) Date: Tue, 29 Aug 2006 09:58:00 +0200 (CEST) Subject: [Python-3000-checkins] r51646 - in python/branches/p3yk: Doc/api/refcounts.dat Doc/lib/libfuncs.tex Doc/tut/tut.tex Include/object.h Objects/longobject.c Objects/object.c Objects/typeobject.c Message-ID: <20060829075800.87BFE1E4008@bag.python.org> Author: neal.norwitz Date: Tue Aug 29 09:57:59 2006 New Revision: 51646 Modified: python/branches/p3yk/Doc/api/refcounts.dat python/branches/p3yk/Doc/lib/libfuncs.tex python/branches/p3yk/Doc/tut/tut.tex python/branches/p3yk/Include/object.h python/branches/p3yk/Objects/longobject.c python/branches/p3yk/Objects/object.c python/branches/p3yk/Objects/typeobject.c Log: Get rid of more coerce cruft (really check in this time :-) Modified: python/branches/p3yk/Doc/api/refcounts.dat ============================================================================== --- python/branches/p3yk/Doc/api/refcounts.dat (original) +++ python/branches/p3yk/Doc/api/refcounts.dat Tue Aug 29 09:57:59 2006 @@ -712,10 +712,6 @@ PyNumber_Check:PyObject*:o:0: PyNumber_Check:int::: -PyNumber_Coerce:int::: -PyNumber_Coerce:PyObject**:p1:+1: -PyNumber_Coerce:PyObject**:p2:+1: - PyNumber_Divide:PyObject*::+1: PyNumber_Divide:PyObject*:o1:0: PyNumber_Divide:PyObject*:o2:0: Modified: python/branches/p3yk/Doc/lib/libfuncs.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libfuncs.tex (original) +++ python/branches/p3yk/Doc/lib/libfuncs.tex Tue Aug 29 09:57:59 2006 @@ -1228,12 +1228,6 @@ argument). \end{funcdesc} -\begin{funcdesc}{coerce}{x, y} - Return a tuple consisting of the two numeric arguments converted to - a common type, using the same rules as used by arithmetic - operations. If coercion is not possible, raise \exception{TypeError}. -\end{funcdesc} - \begin{funcdesc}{intern}{string} Enter \var{string} in the table of ``interned'' strings and return the interned string -- which is \var{string} itself or a copy. Modified: python/branches/p3yk/Doc/tut/tut.tex ============================================================================== --- python/branches/p3yk/Doc/tut/tut.tex (original) +++ python/branches/p3yk/Doc/tut/tut.tex Tue Aug 29 09:57:59 2006 @@ -2696,7 +2696,7 @@ 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__', '__name__', 'abs', 'basestring', 'bool', 'buffer', - 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', + 'callable', 'chr', 'classmethod', 'cmp', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', Modified: python/branches/p3yk/Include/object.h ============================================================================== --- python/branches/p3yk/Include/object.h (original) +++ python/branches/p3yk/Include/object.h Tue Aug 29 09:57:59 2006 @@ -395,7 +395,6 @@ PyAPI_FUNC(int) PyObject_IsTrue(PyObject *); PyAPI_FUNC(int) PyObject_Not(PyObject *); PyAPI_FUNC(int) PyCallable_Check(PyObject *); -PyAPI_FUNC(int) PyNumber_CoerceEx(PyObject **, PyObject **); PyAPI_FUNC(void) PyObject_ClearWeakRefs(PyObject *); Modified: python/branches/p3yk/Objects/longobject.c ============================================================================== --- python/branches/p3yk/Objects/longobject.c (original) +++ python/branches/p3yk/Objects/longobject.c Tue Aug 29 09:57:59 2006 @@ -3158,22 +3158,6 @@ return c; } -static int -long_coerce(PyObject **pv, PyObject **pw) -{ - if (PyInt_Check(*pw)) { - *pw = PyLong_FromLong(PyInt_AS_LONG(*pw)); - Py_INCREF(*pv); - return 0; - } - else if (PyLong_Check(*pw)) { - Py_INCREF(*pv); - Py_INCREF(*pw); - return 0; - } - return 1; /* Can't do it */ -} - static PyObject * long_long(PyObject *v) { @@ -3330,7 +3314,7 @@ long_and, /*nb_and*/ long_xor, /*nb_xor*/ long_or, /*nb_or*/ - long_coerce, /*nb_coerce*/ + 0, /*nb_coerce*/ long_int, /*nb_int*/ long_long, /*nb_long*/ long_float, /*nb_float*/ Modified: python/branches/p3yk/Objects/object.c ============================================================================== --- python/branches/p3yk/Objects/object.c (original) +++ python/branches/p3yk/Objects/object.c Tue Aug 29 09:57:59 2006 @@ -1273,33 +1273,6 @@ return res == 0; } -/* Coerce two numeric types to the "larger" one. - Increment the reference count on each argument. - Return value: - -1 if an error occurred; - 0 if the coercion succeeded (and then the reference counts are increased); - 1 if no coercion is possible (and no error is raised). -*/ -int -PyNumber_CoerceEx(PyObject **pv, PyObject **pw) -{ - register PyObject *v = *pv; - register PyObject *w = *pw; - int res; - - if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) { - res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw); - if (res <= 0) - return res; - } - if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) { - res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv); - if (res <= 0) - return res; - } - return 1; -} - /* Test whether an object can be called */ int Modified: python/branches/p3yk/Objects/typeobject.c ============================================================================== --- python/branches/p3yk/Objects/typeobject.c (original) +++ python/branches/p3yk/Objects/typeobject.c Tue Aug 29 09:57:59 2006 @@ -2935,7 +2935,6 @@ COPYNUM(nb_and); COPYNUM(nb_xor); COPYNUM(nb_or); - COPYNUM(nb_coerce); COPYNUM(nb_int); COPYNUM(nb_long); COPYNUM(nb_float); From python-3000-checkins at python.org Wed Aug 30 06:33:26 2006 From: python-3000-checkins at python.org (george.yoshida) Date: Wed, 30 Aug 2006 06:33:26 +0200 (CEST) Subject: [Python-3000-checkins] r51648 - python/branches/p3yk/Doc/lib/libstdtypes.tex Message-ID: <20060830043326.010EC1E4009@bag.python.org> Author: george.yoshida Date: Wed Aug 30 06:33:26 2006 New Revision: 51648 Modified: python/branches/p3yk/Doc/lib/libstdtypes.tex Log: Fix latex2html compile error Modified: python/branches/p3yk/Doc/lib/libstdtypes.tex ============================================================================== --- python/branches/p3yk/Doc/lib/libstdtypes.tex (original) +++ python/branches/p3yk/Doc/lib/libstdtypes.tex Wed Aug 30 06:33:26 2006 @@ -126,7 +126,7 @@ \lineiii{>}{strictly greater than}{} \lineiii{>=}{greater than or equal}{} \lineiii{==}{equal}{} - \lineiii{!=}{not equal} + \lineiii{!=}{not equal}{} \lineiii{is}{object identity}{} \lineiii{is not}{negated object identity}{} \end{tableiii} From python-3000-checkins at python.org Thu Aug 31 23:45:56 2006 From: python-3000-checkins at python.org (brett.cannon) Date: Thu, 31 Aug 2006 23:45:56 +0200 (CEST) Subject: [Python-3000-checkins] r51670 - python/branches/p3yk/Misc/Vim/vimrc Message-ID: <20060831214556.D73C51E4022@bag.python.org> Author: brett.cannon Date: Thu Aug 31 23:45:56 2006 New Revision: 51670 Modified: python/branches/p3yk/Misc/Vim/vimrc Log: Fix comment for indenting in C files. Modified: python/branches/p3yk/Misc/Vim/vimrc ============================================================================== --- python/branches/p3yk/Misc/Vim/vimrc (original) +++ python/branches/p3yk/Misc/Vim/vimrc Thu Aug 31 23:45:56 2006 @@ -19,7 +19,7 @@ " Number of spaces to use for an indent. " This will affect Ctrl-T and 'autoindent'. " Python: 4 spaces -" C: tab (8 spaces) +" C: 4 spaces au BufRead,BufNewFile *.py,*pyw set shiftwidth=4 au BufRead,BufNewFile *.c,*.h set shiftwidth=4