From akuchling@users.sourceforge.net Sun Dec 1 14:00:27 2002 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Sun, 01 Dec 2002 06:00:27 -0800 Subject: [Python-checkins] python/dist/src/Doc/whatsnew whatsnew23.tex,1.80,1.81 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/whatsnew In directory sc8-pr-cvs1:/tmp/cvs-serv14822 Modified Files: whatsnew23.tex Log Message: Add ossaudiodev; fix typo Index: whatsnew23.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/whatsnew/whatsnew23.tex,v retrieving revision 1.80 retrieving revision 1.81 diff -C2 -d -r1.80 -r1.81 *** whatsnew23.tex 29 Nov 2002 19:43:45 -0000 1.80 --- whatsnew23.tex 1 Dec 2002 14:00:21 -0000 1.81 *************** *** 1071,1075 **** \envvar{LDFLAGS}, and \envvar{CPPFLAGS} environment variables, using them to override the settings in Python's configuration (contributed ! by Robert Weber); the \function{get_distutils_option()} method lists recently-added extensions to Distutils. --- 1071,1075 ---- \envvar{LDFLAGS}, and \envvar{CPPFLAGS} environment variables, using them to override the settings in Python's configuration (contributed ! by Robert Weber); the \function{get_distutils_options()} method lists recently-added extensions to Distutils. *************** *** 1160,1163 **** --- 1160,1169 ---- \module{posix} module that underlies the \module{os} module. (Contributed by Gustavo Niemeyer and Geert Jansen.) + + \item The old and never-documented \module{linuxaudiodev} module has + been renamed to \module{ossaudiodev}, because the OSS sound drivers + can be used on platforms other than Linux. The interface has also + been tidied and brought up to date in various ways. (Contributed by + Greg Ward.) \item The parser objects provided by the \module{pyexpat} module From tim_one@users.sourceforge.net Sun Dec 1 19:37:31 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sun, 01 Dec 2002 11:37:31 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.c,1.28,1.29 datetime.py,1.66,1.67 obj_date.c,1.10,1.11 obj_datetime.c,1.5,1.6 obj_delta.c,1.7,1.8 test_both.py,1.10,1.11 test_datetime.py,1.52,1.53 test_cdatetime.py,1.13,NONE Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv3635 Modified Files: datetime.c datetime.py obj_date.c obj_datetime.c obj_delta.c test_both.py test_datetime.py Removed Files: test_cdatetime.py Log Message: A huge # of changes, mostly implementing missing methods and getting the arithmetic to work. All test_both.py tests pass now, under both the C and Python implementations. No unique tests remained in test_cdatetime.py, so that file was removed from the project. Index: datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.c,v retrieving revision 1.28 retrieving revision 1.29 diff -C2 -d -r1.28 -r1.29 *** datetime.c 26 Nov 2002 23:02:52 -0000 1.28 --- datetime.c 1 Dec 2002 19:37:28 -0000 1.29 *************** *** 18,22 **** PyObject_HEAD long hashcode; ! long days; /* this may be negative */ long seconds; /* 0 <= seconds < 24*3600 is invariant */ long microseconds; /* 0 <= microseconds < 1000000 is invariant */ --- 18,22 ---- PyObject_HEAD long hashcode; ! long days; /* in -TOOBIG_INPUT .. TOOBIG_INPUT */ long seconds; /* 0 <= seconds < 24*3600 is invariant */ long microseconds; /* 0 <= microseconds < 1000000 is invariant */ *************** *** 96,99 **** --- 96,126 ---- } + /* All input fields (year, month, day, hour, minute, second, millisecond, + * microsecond) are constrained to lie within -TOOBIG_INPUT .. TOOBIG_INPUT + * exclusive of endpoints. You can't make this larger without studying the + * code very carefully, as various "can't overflow" assurances follow + * from the specific value used here. + */ + #define TOOBIG_INPUT 1000000000 /* a billion; 1e9 */ + + /* Check that x is in the range given above. If so, return 0. If not, + * raise the given exception and return -1. + */ + static int + check_range(long x, const char* tag, PyObject *exception) + { + char buf[200]; + + if (-TOOBIG_INPUT < x && x < TOOBIG_INPUT) + return 0; + /* PyErr_Format() ignores the "l" in "%ld", which isn't correct + * on boxes where sizeof(long) > sizeof(int). So roll our own. + */ + PyOS_snprintf(buf, sizeof(buf), "%s=%ld; must have magnitude < %ld", + tag, x, TOOBIG_INPUT); + PyErr_SetString(exception, buf); + return -1; + } + /* For each month ordinal in 1..12, the number of days in that month, * and the number of days before that month in the same year. These *************** *** 327,460 **** ! /* Create a date instance with no range checking. */ ! static PyObject * ! new_date(int year, int month, int day) { ! PyDateTime_Date *self; ! ! self = PyObject_New(PyDateTime_Date, &PyDateTime_DateType); ! if (self != NULL) { ! self->hashcode = -1; ! SET_YEAR(self, year); ! SET_MONTH(self, month); ! SET_DAY(self, day); } ! return (PyObject *) self; } ! /* Create a datetime instance with no range checking. */ ! static PyObject * ! new_datetime(int year, int month, int day, int hour, int minute, ! int second, int usecond) { ! PyDateTime_DateTime *self; - self = PyObject_New(PyDateTime_DateTime, &PyDateTime_DateTimeType); - if (self != NULL) { - self->hashcode = -1; - SET_YEAR(self, year); - SET_MONTH(self, month); - SET_DAY(self, day); - SET_HOUR(self, hour); - SET_MINUTE(self, minute); - SET_SECOND(self, second); - SET_MICROSECOND(self, usecond); } ! return (PyObject *) self; } ! /* An internal struct used for miserable normalization tasks. */ ! typedef struct s_tmxxx { ! long year; /* may be negative on output */ ! long month; /* in 1..12 on output */ ! long day; /* in 1 .. days_in_month(year, month) on output */ ! long hour; /* in 0..23 on output */ ! long minute; /* in 0..59 on output */ ! long second; /* in 0 .. 59 on output */ ! long microsecond; /* in 0..999999 on output */ ! } tmxxx; ! ! #define TMXXX_CLEAR(PTR_TO_TMXXX) \ ! memset(PTR_TO_TMXXX, 0, sizeof(struct s_tmxxx)) ! ! /* One step of mixed-radix conversion. *lower is the lower unit and *higher ! * the higher unit, such that 1 higher unit is equal to bound lower units. ! * Normalize *lower to lie in range(bound), adding carries (if needed) to ! * higher. ! * If a carry is needed, adding into *higher may overflow. In that case, ! * retuns a non-zero value. If everything is OK, returns 0. */ ! static int ! norm1(long *higher, long *lower, long bound) { ! assert(bound > 0); ! if (*lower < 0 || *lower >= bound) { ! long carry; ! long new_higher; - carry = divmod(*lower, bound, lower); - assert(0 <= *lower && *lower < bound); - new_higher = *higher + carry; - if (SIGNED_ADD_OVERFLOWED(new_higher, *higher, carry)) - return 1; - *higher = new_higher; } ! return 0; } ! static int ! tmxxx_normalize(tmxxx *p) { ! int dim; /* days in month */ ! char *msg; ! if (norm1(&p->second, &p->microsecond, 1000000)) { ! msg = "second component too large"; ! goto Overflow; } ! assert(0 <= p->microsecond && p->microsecond < 1000000); ! if (norm1(&p->minute, &p->second, 60)) { ! msg = "minute component too large"; ! goto Overflow; } ! assert(0 <= p->second && p->second < 60); ! if (norm1(&p->hour, &p->minute, 60)) { ! msg = "hour component too large"; ! goto Overflow; } ! assert(0 <= p->minute && p->minute < 60); ! if (norm1(&p->day, &p->hour, 60)) { ! msg = "hour component too large"; ! goto Overflow; ! } ! assert(0 <= p->hour && p->hour < 24); ! /* That was easy. Now it gets muddy: the proper range for day ! * can't be determined without knowing the correct month and year, ! * but if day is, e.g., plus or minus a million, the current month ! * and year values make no sense (and may also be out of bounds ! * themselves). * Saying 12 months == 1 year should be non-controversial. */ ! if (p->month < 1 || p->month > 12) { ! --p->month; ! if (norm1(&p->year, &p->month, 12)) { ! msg = "year component too large"; ! goto Overflow; ! } ! ++p->month; ! assert (1 <= p->month && p->month <= 12); } - /* The other routines don't deal correctly with years < 0, so cut - * that off now. - */ - if (p->year < 0) { - msg = "year component is negative"; - goto Overflow; - } /* Now only day can be out of bounds (year may also be out of bounds * for a datetime object, but we don't care about that here). --- 354,519 ---- ! /* One step of a mixed-radix conversion. A "hi" unit is equivalent to ! * factor "lo" units. factor must be > 0. If *lo is less than 0, or ! * at least factor, enough of *lo is converted into "hi" units so that ! * 0 <= *lo < factor. The input values must be such that long overflow ! * is impossible. ! */ ! static void ! normalize_pair(long *hi, long *lo, long factor) { ! assert(factor > 0); ! assert(lo != hi); ! if (*lo < 0 || *lo >= factor) { ! const long num_hi = divmod(*lo, factor, lo); ! const long new_hi = *hi + num_hi; ! assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi)); ! *hi = new_hi; } ! assert(0 <= *lo && *lo < factor); } ! /* Fiddle days (d), hours (h), and minutes (m) so that ! * 0 <= *h < 24 ! * 0 <= *m < 60 ! * The input values must be such that the internals don't overflow. ! * The way this routine is used, we don't get close. ! */ ! static void ! normalize_d_h_m(long *d, long *h, long *m) { ! if (*m < 0 || *m >= 60) { ! normalize_pair(h, m, 60); ! /* |h| can't be bigger than about ! * |original h| + |original m|/60 now. ! */ } ! if (*h < 0 || *h >= 24) { ! normalize_pair(d, h, 24); ! /* |d| can't be bigger than about ! * |original d| + ! * (|original h| + |original m|/60) / 24 now. ! */ ! } ! assert(0 <= *h && *h < 24); ! assert(0 <= *m && *m < 60); } ! /* Fiddle days (d), seconds (s), and microseconds (us) so that ! * 0 <= *s < 24*3600 ! * 0 <= *us < 1000000 ! * The input values must be such that the internals don't overflow. ! * The way this routine is used, we don't get close. */ ! static void ! normalize_d_s_us(long *d, long *s, long *us) { ! if (*us < 0 || *us >= 1000000) { ! normalize_pair(s, us, 1000000); ! /* |s| can't be bigger than about ! * |original s| + |original us|/1000000 now. ! */ } ! if (*s < 0 || *s >= 24*3600) { ! normalize_pair(d, s, 24*3600); ! /* |d| can't be bigger than about ! * |original d| + ! * (|original s| + |original us|/1000000) / (24*3600) now. ! */ ! } ! assert(0 <= *s && *s < 24*3600); ! assert(0 <= *us && *us < 1000000); } ! /* Fiddle days (d), seconds (s), and microseconds (us) so that the output ! * duration is the same as the input duration, but with hours (h), ! * minutes (m), and milliseconds (ms) all 0. ! * The input values must be such that the internals don't overflow. The ! * way this routine is used, we don't get close. ! * The output d, s, and us are intended to be passed to normalize_d_s_us ! * to get them into their proper ranges. ! */ ! static void ! squash_h_m_ms_out_of_d_h_m_s_ms_us(long *d, long h, long m, ! long *s, long ms, long *us) { ! if (h) { ! long new_minutes; ! normalize_pair(d, &h, 24); ! /* |d| can't be bigger than about ! * |original d| + |original h|/24 now. ! * h can't bigger than 23. ! */ ! new_minutes = m + h*60; ! assert(! SIGNED_ADD_OVERFLOWED(new_minutes, m, h*60)); ! m = new_minutes; ! /* |m| can't be bigger than about ! * |original m| + 23*60 now. ! */ } ! if (m) { ! long new_seconds; ! normalize_pair(d, &m, 24*60); ! /* |d| can't be bigger than about ! * |original d| + |original h|/24 + ! * (|original m| + 23*60)/(24*60) now. ! * m can't bigger than 24*60-1. ! */ ! new_seconds = *s + m*60; ! assert(! SIGNED_ADD_OVERFLOWED(new_seconds, *s, m*60)); ! *s = new_seconds; ! /* |s| can't be bigger than about ! * |original s| + (24*60-1) * 60 now. ! */ } ! if (ms) { ! long new_us; ! normalize_pair(s, &ms, 1000); ! /* |s| can't be bigger than about ! * |original s| + (24*60-1) * 60 + |original ms|/1000 now. ! * ms can't be bigger than 999. ! */ ! new_us = *us + ms * 1000; ! assert(! SIGNED_ADD_OVERFLOWED(new_us, *us, ms*1000)); ! *us = new_us; ! /* |us| can't be bigger than about ! * |original us| + 999 * 1000. ! */ } ! } ! /* Fiddle years (y), months (m), and days (d) so that ! * 1 <= *m <= 12 ! * 1 <= *d <= days_in_month(*y, *m) ! * The input values must be such that the internals don't overflow. ! * The way this routine is used, we don't get close. ! */ ! static void ! normalize_y_m_d(long *y, long *m, long *d) ! { ! int dim; /* # of days in month */ ! /* This gets muddy: the proper range for day can't be determined ! * without knowing the correct month and year, but if day is, e.g., ! * plus or minus a million, the current month and year values make ! * no sense (and may also be out of bounds themselves). * Saying 12 months == 1 year should be non-controversial. */ ! if (*m < 1 || *m > 12) { ! --*m; ! normalize_pair(y, m, 12); ! ++*m; ! /* |y| can't be bigger than about ! * |original y| + |original m|/12 now. ! */ } + assert(1 <= *m && *m <= 12); + assert(INT_MIN < *y && *y < INT_MAX); /* so cast to int is safe */ /* Now only day can be out of bounds (year may also be out of bounds * for a datetime object, but we don't care about that here). *************** *** 462,503 **** * method here is principled and explainable. */ ! dim = days_in_month(p->year, p->month); ! if (p->day < 1 || p->day > dim) { /* Move day-1 days from the first of the month. First try to * get off cheap if we're only one day out of range * (adjustments for timezone alone can't be worse than that). */ ! if (p->day == 0) { ! --p->month; ! if (p->month > 0) ! p->day = days_in_month(p->year, p->month); else { ! --p->year; ! p->month = 12; ! p->day = 31; } } ! else if (p->day == dim + 1) { /* move forward a day */ ! ++p->month; ! p->day = 1; ! if (p->month > 12) { ! p->month = 1; ! ++p->year; } } else { ! long ordinal = ymd_to_ord(p->year, p->month, 1) + ! p->day - 1; ! ord_to_ymd(ordinal, &p->year, &p->month, &p->day); } } ! assert(p->month > 0); ! assert(p->day > 0); ! return 1; ! Overflow: ! PyErr_SetString(PyExc_OverflowError, msg); ! return 0; } --- 521,603 ---- * method here is principled and explainable. */ ! dim = days_in_month((int)*y, (int)*m); ! if (*d < 1 || *d > dim) { /* Move day-1 days from the first of the month. First try to * get off cheap if we're only one day out of range * (adjustments for timezone alone can't be worse than that). */ ! if (*d == 0) { ! --*m; ! if (*m > 0) ! *d = days_in_month((int)*y, (int)*m); else { ! --*y; ! *m = 12; ! *d = 31; } } ! else if (*d == dim + 1) { /* move forward a day */ ! ++*m; ! *d = 1; ! if (*m > 12) { ! *m = 1; ! ++*y; } } else { ! long ordinal = ymd_to_ord((int)*y, (int)*m, 1) + ! *d - 1; ! ord_to_ymd(ordinal, y, m, d); } } ! assert(*m > 0); ! assert(*d > 0); ! } ! static PyObject *us_per_ms = NULL; ! static PyObject *us_per_second = NULL; ! static PyObject *us_per_minute = NULL; ! static PyObject *us_per_hour = NULL; ! static PyObject *us_per_day = NULL; ! static PyObject *us_per_week = NULL; ! ! static PyObject *seconds_per_day = NULL; ! ! /* Create a date instance with no range checking. */ ! static PyObject * ! new_date(int year, int month, int day) ! { ! PyDateTime_Date *self; ! ! self = PyObject_New(PyDateTime_Date, &PyDateTime_DateType); ! if (self != NULL) { ! self->hashcode = -1; ! SET_YEAR(self, year); ! SET_MONTH(self, month); ! SET_DAY(self, day); ! } ! return (PyObject *) self; ! } ! ! /* Create a datetime instance with no range checking. */ ! static PyObject * ! new_datetime(int year, int month, int day, int hour, int minute, ! int second, int usecond) ! { ! PyDateTime_DateTime *self; ! ! self = PyObject_New(PyDateTime_DateTime, &PyDateTime_DateTimeType); ! if (self != NULL) { ! self->hashcode = -1; ! SET_YEAR(self, year); ! SET_MONTH(self, month); ! SET_DAY(self, day); ! SET_HOUR(self, hour); ! SET_MINUTE(self, minute); ! SET_SECOND(self, second); ! SET_MICROSECOND(self, usecond); ! } ! return (PyObject *) self; } *************** *** 505,539 **** new_delta(long days, long seconds, long microseconds) { ! PyDateTime_Delta *self = NULL; ! if (microseconds < 0 || microseconds >= 1000000) { ! long whole_seconds; ! long new_seconds; ! whole_seconds = divmod(microseconds, 1000000, µseconds); ! assert(microseconds >= 0); ! new_seconds = seconds + whole_seconds; ! if (SIGNED_ADD_OVERFLOWED(new_seconds, seconds, ! whole_seconds)) { ! PyErr_SetString(PyExc_OverflowError, "timedelta " ! "seconds component too large"); ! goto done; ! } ! seconds = new_seconds; ! } ! if (seconds < 0 || seconds >= 24*3600) { ! long whole_days; ! long new_days; - whole_days = divmod(seconds, 24*3600, &seconds); - assert(seconds >= 0); - new_days = days + whole_days; - if (SIGNED_ADD_OVERFLOWED(new_days, days, whole_days)) { - PyErr_SetString(PyExc_OverflowError, "timedelta " - "days component too large"); - goto done; - } - days = new_days; - } self = PyObject_New(PyDateTime_Delta, &PyDateTime_DeltaType); if (self != NULL) { --- 605,615 ---- new_delta(long days, long seconds, long microseconds) { ! PyDateTime_Delta *self; ! normalize_d_s_us(&days, &seconds, µseconds); ! if (check_range(days, "timedelta days", PyExc_OverflowError) < 0) ! return NULL; self = PyObject_New(PyDateTime_Delta, &PyDateTime_DeltaType); if (self != NULL) { *************** *** 543,547 **** SET_TD_MICROSECONDS(self, microseconds); } - done: return (PyObject *) self; } --- 619,622 ---- *************** *** 627,630 **** --- 702,717 ---- assert(DI100Y == 25 * DI4Y - 1); assert(DI100Y == days_before_year(100+1)); + + us_per_ms = PyInt_FromLong(1000); + us_per_second = PyInt_FromLong(1000000); + us_per_minute = PyInt_FromLong(60000000); + seconds_per_day = PyInt_FromLong(24 * 3600); + + /* The rest are too big for 32-bit ints, but even + * us_per_week fits in 40 bits, so doubles should be exact. + */ + us_per_hour = PyLong_FromDouble(3600000000.0); + us_per_day = PyLong_FromDouble(86400000000.0); + us_per_week = PyLong_FromDouble(604800000000.0); } Index: datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.py,v retrieving revision 1.66 retrieving revision 1.67 diff -C2 -d -r1.66 -r1.67 *** datetime.py 26 Nov 2002 18:03:19 -0000 1.66 --- datetime.py 1 Dec 2002 19:37:28 -0000 1.67 *************** *** 466,469 **** --- 466,471 ---- return 1 + def __hash__(self): + return hash((self.__days, self.__seconds, self.__microseconds)) class date(object): Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** obj_date.c 26 Nov 2002 22:51:04 -0000 1.10 --- obj_date.c 1 Dec 2002 19:37:28 -0000 1.11 *************** *** 5,34 **** /* Fiddle out-of-bounds months and days so that the result makes some kind ! * of sense. The parameters are both inputs and outputs. Returns 0 on ! * failure and > 0 for success. Failure means the adjusted year is out of ! * bounds. */ static int normalize_date(long *year, long *month, long *day) { - tmxxx t; int result; ! TMXXX_CLEAR(&t); ! t.year = *year; ! t.month = *month; ! t.day = *day; ! result = tmxxx_normalize(&t); ! if (result > 0) { ! /* looks good */ ! *year = t.year; ! *month = t.month; ! *day = t.day; ! ! if (*year < MINYEAR || *year > MAXYEAR) { ! PyErr_SetString(PyExc_OverflowError, ! "date value out of range"); ! result = 0; ! } } return result; --- 5,23 ---- /* Fiddle out-of-bounds months and days so that the result makes some kind ! * of sense. The parameters are both inputs and outputs. Returns < 0 on ! * failure, where failure means the adjusted year is out of bounds. */ static int normalize_date(long *year, long *month, long *day) { int result; ! normalize_y_m_d(year, month, day); ! if (MINYEAR <= *year && *year <= MAXYEAR) ! result = 0; ! else { ! PyErr_SetString(PyExc_OverflowError, ! "date value out of range"); ! result = -1; } return result; *************** *** 64,71 **** long int month = GET_MONTH(date); long int day = GET_DAY(date) + GET_TD_DAYS(delta); ! if (normalize_date(&year, &month, &day)) ! result = new_date(year, month, day); ! else result = NULL; } else { --- 53,60 ---- long int month = GET_MONTH(date); long int day = GET_DAY(date) + GET_TD_DAYS(delta); ! if (normalize_date(&year, &month, &day) < 0) result = NULL; + else + result = new_date(year, month, day); } else { *************** *** 145,149 **** } ! static int date_hash(PyDateTime_Date *self) { --- 134,138 ---- } ! static long date_hash(PyDateTime_Date *self) { Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** obj_datetime.c 21 Nov 2002 19:47:34 -0000 1.5 --- obj_datetime.c 1 Dec 2002 19:37:28 -0000 1.6 *************** *** 4,26 **** */ - static void - normalize_pair(long int *parent, long int *child, int size) - { - if (*child < 0) { - long int borrow = (*child / size) + 1; - *parent -= borrow; - *child += (borrow * size); - } - else if (*child >= size) { - long int carry = *child / size; - *parent += carry; - *child -= (carry * size); - } - } - static int ! normalize_datetime(long int *year, long int *month, long int *day, ! long int *hour, long int *minute, long int *second, ! long int *microsecond) { normalize_pair(second, microsecond, 1000000); --- 4,11 ---- */ static int ! normalize_datetime(long *year, long *month, long *day, ! long *hour, long *minute, long *second, ! long *microsecond) { normalize_pair(second, microsecond, 1000000); *************** *** 28,32 **** normalize_pair(hour, minute, 60); normalize_pair(day, hour, 24); - return normalize_date(year, month, day); } --- 13,16 ---- *************** *** 35,52 **** add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta) { ! long int year = GET_YEAR(date); ! long int month = GET_MONTH(date); ! long int day = GET_DAY(date) + GET_TD_DAYS(delta); ! long int hour = GET_HOUR(date); ! long int minute = GET_MINUTE(date); ! long int second = GET_SECOND(date) + GET_TD_SECONDS(delta); ! long int microsecond = GET_MICROSECOND(date) + GET_TD_MICROSECONDS(delta); if (normalize_datetime(&year, &month, &day, ! &hour, &minute, &second, µsecond)) return new_datetime(year, month, day, hour, minute, second, microsecond); ! else return NULL; } --- 19,78 ---- add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta) { ! long year = GET_YEAR(date); ! long month = GET_MONTH(date); ! long day = GET_DAY(date) + GET_TD_DAYS(delta); ! long hour = GET_HOUR(date); ! long minute = GET_MINUTE(date); ! long second = GET_SECOND(date) + GET_TD_SECONDS(delta); ! long microsecond = GET_MICROSECOND(date) + GET_TD_MICROSECONDS(delta); if (normalize_datetime(&year, &month, &day, ! &hour, &minute, &second, µsecond) < 0) ! return NULL; ! else return new_datetime(year, month, day, hour, minute, second, microsecond); ! } ! ! static PyObject * ! sub_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta) ! { ! long year = GET_YEAR(date); ! long month = GET_MONTH(date); ! long day = GET_DAY(date) - GET_TD_DAYS(delta); ! long hour = GET_HOUR(date); ! long minute = GET_MINUTE(date); ! long second = GET_SECOND(date) - GET_TD_SECONDS(delta); ! long microsecond = GET_MICROSECOND(date) - GET_TD_MICROSECONDS(delta); ! ! if (normalize_datetime(&year, &month, &day, ! &hour, &minute, &second, µsecond) < 0) return NULL; + else + return new_datetime(year, month, day, + hour, minute, second, microsecond); + } + + static PyObject * + sub_datetime_datetime(PyDateTime_DateTime *left, PyDateTime_DateTime *right) + { + long days1 = ymd_to_ord(GET_YEAR(left), + GET_MONTH(left), + GET_DAY(left)); + long days2 = ymd_to_ord(GET_YEAR(right), + GET_MONTH(right), + GET_DAY(right)); + + /* These can't overflow, since the values are normalized. At most + * this gives the number of seconds in one day. + */ + long seconds1 = (GET_HOUR(left) * 60 + GET_MINUTE(left)) * 60 + + GET_SECOND(left); + long seconds2 = (GET_HOUR(right) * 60 + GET_MINUTE(right)) * 60 + + GET_SECOND(right); + + long delta_us = GET_MICROSECOND(left) - GET_MICROSECOND(right); + + return new_delta(days1 - days2, seconds1 - seconds2, delta_us); } *************** *** 72,75 **** --- 98,129 ---- } + static PyObject * + datetime_subtract(PyObject *left, PyObject *right) + { + PyTypeObject *left_type = left->ob_type; + PyTypeObject *right_type = right->ob_type; + PyObject *result = Py_NotImplemented; + + if (PyType_IsSubtype(left_type, &PyDateTime_DateTimeType)) { + /* datetime - ??? */ + if (PyType_IsSubtype(right_type, &PyDateTime_DateTimeType)) { + /* datetime - datetime */ + result = sub_datetime_datetime( + (PyDateTime_DateTime *)left, + (PyDateTime_DateTime *)right); + } + else if (PyType_IsSubtype(right_type, &PyDateTime_DeltaType)) { + /* datetime - timedelta */ + result = sub_datetime_timedelta( + (PyDateTime_DateTime *)left, + (PyDateTime_Delta *)right); + } + } + + if (result == Py_NotImplemented) + Py_INCREF(result); + return result; + } + static int datetime_compare(PyDateTime_DateTime *self, PyObject *other) *************** *** 91,120 **** } ! static int datetime_hash(PyDateTime_DateTime *self) { if (self->hashcode == -1) { PyObject *temp; ! if (GET_MICROSECOND(self) != 0) ! temp = Py_BuildValue("lllllll", GET_YEAR(self), ! GET_MONTH(self), GET_DAY(self), ! GET_HOUR(self), GET_MINUTE(self), ! GET_SECOND(self), GET_MICROSECOND(self)); ! else if (GET_SECOND(self) != 0) ! temp = Py_BuildValue("llllll", GET_YEAR(self), ! GET_MONTH(self), GET_DAY(self), ! GET_HOUR(self), GET_MINUTE(self), ! GET_SECOND(self)); ! else if (GET_MINUTE(self) != 0) ! temp = Py_BuildValue("lllll", GET_YEAR(self), ! GET_MONTH(self), GET_DAY(self), ! GET_HOUR(self), GET_MINUTE(self)); ! else if (GET_HOUR(self) != 0) ! temp = Py_BuildValue("llll", GET_YEAR(self), ! GET_MONTH(self), GET_DAY(self), ! GET_HOUR(self)); ! else ! temp = Py_BuildValue("lll", GET_YEAR(self), ! GET_MONTH(self), GET_DAY(self)); if (temp != NULL) { self->hashcode = PyObject_Hash(temp); --- 145,157 ---- } ! static long datetime_hash(PyDateTime_DateTime *self) { if (self->hashcode == -1) { PyObject *temp; ! temp = Py_BuildValue("lllllll", GET_YEAR(self), ! GET_MONTH(self), GET_DAY(self), ! GET_HOUR(self), GET_MINUTE(self), ! GET_SECOND(self), GET_MICROSECOND(self)); if (temp != NULL) { self->hashcode = PyObject_Hash(temp); *************** *** 213,224 **** return PyString_FromString(buffer); } - - static PyObject * - datetime_subtract(PyObject *left, PyObject *right) - { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - static PyObject * --- 250,253 ---- Index: obj_delta.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_delta.c,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** obj_delta.c 26 Nov 2002 05:37:09 -0000 1.7 --- obj_delta.c 1 Dec 2002 19:37:28 -0000 1.8 *************** *** 1,7 **** ! /* imp_delta.c * * PyDateTime_Delta implementation. */ static PyObject * --- 1,168 ---- ! /* obj_delta.c * * PyDateTime_Delta implementation. */ + /* Convert a timedelta to a number of us, + * (24*3600*self.days + self.seconds)*1000000 + self.microseconds + * as a Python int or long. + * Doing mixed-radix arithmetic by hand instead is excruciating in C, + * due to ubiquitous overflow possibilities. + */ + static PyObject * + delta_to_microseconds(PyDateTime_Delta *self) + { + PyObject *x1 = NULL; + PyObject *x2 = NULL; + PyObject *x3 = NULL; + PyObject *result = NULL; + + x1 = PyInt_FromLong(GET_TD_DAYS(self)); + if (x1 == NULL) + goto Done; + x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */ + if (x2 == NULL) + goto Done; + Py_DECREF(x1); + x1 = NULL; + + /* x2 has days in seconds */ + x1 = PyInt_FromLong(GET_TD_SECONDS(self)); /* seconds */ + if (x1 == NULL) + goto Done; + x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */ + if (x3 == NULL) + goto Done; + Py_DECREF(x1); + Py_DECREF(x2); + x1 = x2 = NULL; + + /* x3 has days+seconds in seconds */ + x1 = PyNumber_Multiply(x3, us_per_second); /* us */ + if (x1 == NULL) + goto Done; + Py_DECREF(x3); + x3 = NULL; + + /* x1 has days+seconds in us */ + x2 = PyInt_FromLong(GET_TD_MICROSECONDS(self)); + if (x2 == NULL) + goto Done; + result = PyNumber_Add(x1, x2); + + Done: + Py_XDECREF(x1); + Py_XDECREF(x2); + Py_XDECREF(x3); + return result; + } + + /* Convert a number of us (as a Python int or long) to a timedelta. + */ + static PyObject * + microseconds_to_delta(PyObject *pyus) + { + long us; + long s; + long d; + + PyObject *tuple = NULL; + PyObject *num = NULL; + PyObject *result = NULL; + + tuple = PyNumber_Divmod(pyus, us_per_second); + if (tuple == NULL) + goto Done; + + num = PyTuple_GetItem(tuple, 1); /* us */ + if (num == NULL) + goto Done; + us = PyLong_AsLong(num); + num = NULL; + if (us < 0) { + /* The divisor was positive, so this must be an error. */ + assert(PyErr_Occurred()); + goto Done; + } + + num = PyTuple_GetItem(tuple, 0); /* leftover seconds */ + if (num == NULL) + goto Done; + Py_INCREF(num); + Py_DECREF(tuple); + + tuple = PyNumber_Divmod(num, seconds_per_day); + if (tuple == NULL) + goto Done; + Py_DECREF(num); + + num = PyTuple_GetItem(tuple, 1); /* seconds */ + if (num == NULL) + goto Done; + s = PyLong_AsLong(num); + num = NULL; + if (s < 0) { + /* The divisor was positive, so this must be an error. */ + assert(PyErr_Occurred()); + goto Done; + } + + num = PyTuple_GetItem(tuple, 0); /* leftover days */ + if (num == NULL) + goto Done; + Py_INCREF(num); + + d = PyLong_AsLong(num); + if (d == -1 && PyErr_Occurred()) + goto Done; + result = new_delta(d, s, us); + + Done: + Py_XDECREF(tuple); + Py_XDECREF(num); + return result; + } + + static PyObject * + multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta) + { + PyObject *pyus_in; + PyObject *pyus_out; + PyObject *result; + + pyus_in = delta_to_microseconds(delta); + if (pyus_in == NULL) + return NULL; + + pyus_out = PyNumber_Multiply(pyus_in, intobj); + Py_DECREF(pyus_in); + if (pyus_out == NULL) + return NULL; + + result = microseconds_to_delta(pyus_out); + Py_DECREF(pyus_out); + return result; + } + + static PyObject * + divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj) + { + PyObject *pyus_in; + PyObject *pyus_out; + PyObject *result; + + pyus_in = delta_to_microseconds(delta); + if (pyus_in == NULL) + return NULL; + + pyus_out = PyNumber_FloorDivide(pyus_in, intobj); + Py_DECREF(pyus_in); + if (pyus_out == NULL) + return NULL; + + result = microseconds_to_delta(pyus_out); + Py_DECREF(pyus_out); + return result; + } static PyObject * *************** *** 10,50 **** PyTypeObject *left_type = left->ob_type; PyTypeObject *right_type = right->ob_type; - PyDateTime_Delta *delta; - PyObject *other; - PyTypeObject *other_type; ! if (PyType_IsSubtype(left_type, &PyDateTime_DeltaType)) { ! /* delta + ??? */ ! delta = (PyDateTime_Delta *) left; ! if (PyType_IsSubtype(right_type, &PyDateTime_DeltaType)) { ! /* delta + delta */ ! /* seconds and microseconds can't overflow, due to ! * the invariant bounds on them. ! */ ! const long seconds = GET_TD_SECONDS(delta) + ! GET_TD_SECONDS(right); ! const long microseconds = GET_TD_MICROSECONDS(delta) + ! GET_TD_MICROSECONDS(right); ! /* But days can overflow. */ ! const long days1 = GET_TD_DAYS(delta); ! const long days2 = GET_TD_DAYS(right); ! const long days = days1 + days2; ! if (SIGNED_ADD_OVERFLOWED(days, days1, days2)) { ! PyErr_SetString(PyExc_OverflowError, ! "timedelta addition"); ! return NULL; ! } ! return new_delta(days, seconds, microseconds); ! } ! /* XXX This code is unused. */ ! other = right; ! other_type = right_type; ! } ! else { ! /* !delta + delta */ ! /* XXX This code is unused. */ ! delta = (PyDateTime_Delta *) right; ! other = left; ! other_type = left_type; } Py_INCREF(Py_NotImplemented); --- 171,186 ---- PyTypeObject *left_type = left->ob_type; PyTypeObject *right_type = right->ob_type; ! if (PyType_IsSubtype(left_type, &PyDateTime_DeltaType) && ! PyType_IsSubtype(right_type, &PyDateTime_DeltaType)) { ! /* delta + delta */ ! /* The C-level additions can't overflow because of the ! * invariant bounds. ! */ ! long days = GET_TD_DAYS(left) + GET_TD_DAYS(right); ! long seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right); ! long microseconds = GET_TD_MICROSECONDS(left) + ! GET_TD_MICROSECONDS(right); ! return new_delta(days, seconds, microseconds); } Py_INCREF(Py_NotImplemented); *************** *** 113,116 **** --- 249,253 ---- { int result = -1; + if (!PyObject_TypeCheck(other, &PyDateTime_DeltaType)) PyErr_Format(PyExc_TypeError, *************** *** 133,149 **** } ! static int delta_hash(PyDateTime_Delta *self) { ! return -2; ! } ! ! static PyObject * ! multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta) ! { ! long i = PyInt_AS_LONG(intobj); ! return new_delta(GET_TD_DAYS(delta) * i, ! GET_TD_SECONDS(delta) * i, ! GET_TD_MICROSECONDS(delta) * i); } --- 270,287 ---- } ! static long delta_hash(PyDateTime_Delta *self) { ! if (self->hashcode == -1) { ! PyObject *temp = Py_BuildValue("lll", ! self->days, ! self->seconds, ! self->microseconds); ! if (temp != NULL) { ! self->hashcode = PyObject_Hash(temp); ! Py_DECREF(temp); ! } ! } ! return self->hashcode; } *************** *** 151,192 **** delta_multiply(PyObject *left, PyObject *right) { ! PyObject *result = NULL; if (PyType_IsSubtype(left->ob_type, &PyDateTime_DeltaType)) { /* delta * ??? */ ! if (PyInt_Check(right)) result = multiply_int_timedelta(right, (PyDateTime_Delta *) left); - else { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } } ! else if (PyInt_Check(left)) result = multiply_int_timedelta(left, (PyDateTime_Delta *) right); ! else { ! /* !(delta | int) * delta */ ! Py_INCREF(Py_NotImplemented); ! return Py_NotImplemented; } return result; } static PyObject * delta_new(PyTypeObject *type, PyObject *args, PyObject *kw) { PyObject *self = NULL; - long int days, seconds = 0, microseconds = 0; ! /* XXX We're missing 4 keyword args from the Python version. */ ! /* XXX The Python version doesn't require a days argument. */ static char *keywords[] = { ! "days", "seconds", "microseconds", NULL }; ! if (PyArg_ParseTupleAndKeywords(args, kw, "l|ll:__new__", keywords, ! &days, &seconds, µseconds)) { ! self = new_delta(days, seconds, microseconds); } return self; } --- 289,526 ---- delta_multiply(PyObject *left, PyObject *right) { ! PyObject *result = Py_NotImplemented; ! if (PyType_IsSubtype(left->ob_type, &PyDateTime_DeltaType)) { /* delta * ??? */ ! if (PyInt_Check(right) || PyLong_Check(right)) result = multiply_int_timedelta(right, (PyDateTime_Delta *) left); } ! else if (PyInt_Check(left) || PyLong_Check(left)) result = multiply_int_timedelta(left, (PyDateTime_Delta *) right); ! ! if (result == Py_NotImplemented) ! Py_INCREF(result); ! return result; ! } ! ! static PyObject * ! delta_divide(PyObject *left, PyObject *right) ! { ! PyObject *result = Py_NotImplemented; ! ! if (PyType_IsSubtype(left->ob_type, &PyDateTime_DeltaType)) { ! /* delta * ??? */ ! if (PyInt_Check(right) || PyLong_Check(right)) ! result = divide_timedelta_int( ! (PyDateTime_Delta *)left, ! right); } + + if (result == Py_NotImplemented) + Py_INCREF(result); return result; } + /* Fold in the value of the tag ("seconds", "weeks", etc) component of a + * a timedelta constructor. sofar is the # of microseconds accounted for + * so far, and there are factor microseconds per current unit, the number + * of which is given by num. num * factor is added to sofar in a + * numerically careful way, and that's the result. Any fractional + * microseconds left over (this can happen if num is a float type) are + * added into *leftover. + * If num is NULL, no computation is done, and sofar is returned (after + * incremented its refcount). + * Note that there are many ways this can give an error (NULL) return. + */ + static PyObject * + accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor, + double *leftover) + { + PyObject *prod; + PyObject *sum; + + if (num == NULL) { + Py_INCREF(sofar); + return sofar; + } + + if (PyInt_Check(num) || PyLong_Check(num)) { + prod = PyNumber_Multiply(num, factor); + if (prod == NULL) + return NULL; + sum = PyNumber_Add(sofar, prod); + Py_DECREF(prod); + return sum; + } + + if (PyFloat_Check(num)) { + double dnum; + double fracpart; + double intpart; + PyObject *x; + PyObject *y; + + /* The Plan: decompose num into an integer part and a + * fractional part, num = intpart + fracpart. + * Then num * factor == + * intpart * factor + fracpart * factor + * and the LHS can be computed exactly in long arithmetic. + * The RHS is again broken into an int part and frac part. + * and the frac part is added into *leftover. + */ + dnum = PyFloat_AsDouble(num); + if (dnum == -1.0 && PyErr_Occurred()) + return NULL; + fracpart = modf(dnum, &intpart); + x = PyLong_FromDouble(intpart); + if (x == NULL) + return NULL; + + prod = PyNumber_Multiply(x, factor); + Py_DECREF(x); + if (prod == NULL) + return NULL; + + sum = PyNumber_Add(sofar, prod); + Py_DECREF(prod); + if (sum == NULL) + return NULL; + + /* So far we've lost no information. Dealing with the + * fractional part requires float arithmetic, and may + * lose a little info. + */ + assert(PyInt_Check(factor) || PyLong_Check(factor)); + if (PyInt_Check(factor)) + dnum = (double)PyInt_AsLong(factor); + else + dnum = PyLong_AsDouble(factor); + + dnum *= fracpart; + fracpart = modf(dnum, &intpart); + x = PyLong_FromDouble(intpart); + if (x == NULL) { + Py_DECREF(sum); + return NULL; + } + + y = PyNumber_Add(sum, x); + Py_DECREF(sum); + Py_DECREF(x); + *leftover += fracpart; + return y; + } + + PyErr_Format(PyExc_TypeError, + "unsupported type for timedelta %s component: %s", + tag, num->ob_type->tp_name); + return NULL; + } + static PyObject * delta_new(PyTypeObject *type, PyObject *args, PyObject *kw) { PyObject *self = NULL; ! /* Argument objects. */ ! PyObject *day = NULL; ! PyObject *second = NULL; ! PyObject *us = NULL; ! PyObject *ms = NULL; ! PyObject *minute = NULL; ! PyObject *hour = NULL; ! PyObject *week = NULL; ! ! PyObject *x = NULL; ! PyObject *y = NULL; ! double leftover_us = 0.0; ! ! PyObject *one; ! static char *keywords[] = { ! "days", "seconds", "microseconds", "milliseconds", ! "minutes", "hours", "weeks", NULL }; ! if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__", ! keywords, ! &day, &second, &us, ! &ms, &minute, &hour, &week) == 0) ! goto Done; ! ! x = PyInt_FromLong(0); ! if (x == NULL) ! goto Done; ! ! one = PyInt_FromLong(1); ! if (one == NULL) ! goto Done; ! y = accum("microseconds", x, us, one, &leftover_us); ! Py_DECREF(one); ! Py_DECREF(x); ! x = y; ! if (x == NULL) ! goto Done; ! ! y = accum("milliseconds", x, ms, us_per_ms, &leftover_us); ! Py_DECREF(x); ! x = y; ! if (x == NULL) ! goto Done; ! ! y = accum("seconds", x, second, us_per_second, &leftover_us); ! Py_DECREF(x); ! x = y; ! if (x == NULL) ! goto Done; ! ! y = accum("minutes", x, minute, us_per_minute, &leftover_us); ! Py_DECREF(x); ! x = y; ! if (x == NULL) ! goto Done; ! ! y = accum("hours", x, hour, us_per_hour, &leftover_us); ! Py_DECREF(x); ! x = y; ! if (x == NULL) ! goto Done; ! ! y = accum("days", x, day, us_per_day, &leftover_us); ! Py_DECREF(x); ! x = y; ! if (x == NULL) ! goto Done; ! ! y = accum("weeks", x, week, us_per_week, &leftover_us); ! Py_DECREF(x); ! x = y; ! if (x == NULL) ! goto Done; ! ! if (leftover_us) { ! PyObject *temp; ! if (leftover_us >= 0.0) ! leftover_us = floor(leftover_us + 0.5); ! else ! leftover_us = ceil(leftover_us - 0.5); ! temp = PyLong_FromDouble(leftover_us); ! if (temp == NULL) { ! Py_DECREF(x); ! goto Done; ! } ! y = PyNumber_Add(x, temp); ! Py_DECREF(temp); ! Py_DECREF(x); ! x = y; ! if (x == NULL) ! goto Done; } + + self = microseconds_to_delta(x); + Py_DECREF(x); + Done: return self; } *************** *** 236,252 **** static PyNumberMethods delta_as_number = { ! delta_add, /* nb_add */ ! delta_subtract, /* nb_subtract */ ! delta_multiply, /* nb_multiply */ ! 0, /* nb_divide */ ! 0, /* nb_remainder */ ! 0, /* nb_divmod */ ! 0, /* nb_power */ ! (unaryfunc)delta_negative, /* nb_negative */ ! (unaryfunc)delta_positive, /* nb_positive */ ! (unaryfunc)delta_abs, /* nb_absolute */ ! (inquiry)delta_nonzero, /* nb_nonzero */ }; - static PyTypeObject PyDateTime_DeltaType = { PyObject_HEAD_INIT(NULL) --- 570,612 ---- static PyNumberMethods delta_as_number = { ! delta_add, /* nb_add */ ! delta_subtract, /* nb_subtract */ ! delta_multiply, /* nb_multiply */ ! delta_divide, /* nb_divide */ ! 0, /* nb_remainder */ ! 0, /* nb_divmod */ ! 0, /* nb_power */ ! (unaryfunc)delta_negative, /* nb_negative */ ! (unaryfunc)delta_positive, /* nb_positive */ ! (unaryfunc)delta_abs, /* nb_absolute */ ! (inquiry)delta_nonzero, /* nb_nonzero */ ! 0, /*nb_invert*/ ! 0, /*nb_lshift*/ ! 0, /*nb_rshift*/ ! 0, /*nb_and*/ ! 0, /*nb_xor*/ ! 0, /*nb_or*/ ! 0, /*nb_coerce*/ ! 0, /*nb_int*/ ! 0, /*nb_long*/ ! 0, /*nb_float*/ ! 0, /*nb_oct*/ ! 0, /*nb_hex*/ ! 0, /*nb_inplace_add*/ ! 0, /*nb_inplace_subtract*/ ! 0, /*nb_inplace_multiply*/ ! 0, /*nb_inplace_divide*/ ! 0, /*nb_inplace_remainder*/ ! 0, /*nb_inplace_power*/ ! 0, /*nb_inplace_lshift*/ ! 0, /*nb_inplace_rshift*/ ! 0, /*nb_inplace_and*/ ! 0, /*nb_inplace_xor*/ ! 0, /*nb_inplace_or*/ ! delta_divide, /* nb_floor_divide */ ! 0, /* nb_true_divide */ ! 0, /* nb_inplace_floor_divide */ ! 0, /* nb_inplace_true_divide */ }; static PyTypeObject PyDateTime_DeltaType = { PyObject_HEAD_INIT(NULL) Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** test_both.py 26 Nov 2002 21:22:38 -0000 1.10 --- test_both.py 1 Dec 2002 19:37:28 -0000 1.11 *************** *** 55,59 **** self.assertEqual(a*10, timedelta(70)) self.assertEqual(a*10, 10*a) - # XXX Next one fails in the C implementation. self.assertEqual(a*10L, 10*a) self.assertEqual(b*10, timedelta(0, 600)) --- 55,58 ---- *************** *** 101,104 **** --- 100,132 ---- eq(td(milliseconds=0.001), td(microseconds=1)) + def test_carries(self): + t1 = timedelta(days=100, + weeks=-7, + hours=-24*(100-49), + minutes=-3, + seconds=12, + microseconds=(3*60 - 12) * 1000000) + t2 = timedelta() + self.assertEqual(t1, t2) + + def test_hash_equality(self): + t1 = timedelta(days=100, + weeks=-7, + hours=-24*(100-49), + minutes=-3, + seconds=12, + microseconds=(3*60 - 12) * 1000000) + t2 = timedelta() + self.assertEqual(hash(t1), hash(t2)) + + t1 += timedelta(weeks=7) + t2 += timedelta(days=7*7) + self.assertEqual(t1, t2) + self.assertEqual(hash(t1), hash(t2)) + + d = {t1: 1} + d[t2] = 2 + self.assertEqual(len(d), 1) + ############################################################################# # date tests *************** *** 334,338 **** n = (big.days*24*3600 + big.seconds)*1000000 + big.microseconds # n == 315537897599999999 ~= 2**58.13 - # XXX Next line fails in the C implementation. justasbig = timedelta(0, 0, n) self.assertEqual(big, justasbig) --- 362,365 ---- *************** *** 359,367 **** # datetime tests ! # XXX The Python version of this test class inherits from TestDate. And ! # XXX it should. Trying it here, though, causes 4 new errors when the ! # XXX C implementation is getting tested. ! ! class TestDateTime(unittest.TestCase): theclass = datetime.datetime --- 386,390 ---- # datetime tests ! class TestDateTime(TestDate): theclass = datetime.datetime *************** *** 415,419 **** --- 438,580 ---- self.assertEqual(t.ctime(), "Sat Mar 2 18:03:05 2002") + def test_tz_independent_comparing(self): + dt1 = self.theclass(2002, 3, 1, 9, 0, 0) + dt2 = self.theclass(2002, 3, 1, 10, 0, 0) + dt3 = self.theclass(2002, 3, 1, 9, 0, 0) + self.assertEqual(dt1, dt3) + self.assert_(dt2 > dt3) + + # Make sure comparison doesn't forget microseconds, and isn't done + # via comparing a float timestamp (an IEEE double doesn't have enough + # precision to span microsecond resolution across years 1 thru 9999, + # so comparing via timestamp necessarily calls some distinct values + # equal). + dt1 = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999998) + us = timedelta(microseconds=1) + dt2 = dt1 + us + self.assertEqual(dt2 - dt1, us) + self.assert_(dt1 < dt2) + def test_bad_constructor_arguments(self): + # bad years + self.theclass(MINYEAR, 1, 1) # no exception + self.theclass(MAXYEAR, 1, 1) # no exception + self.assertRaises(ValueError, self.theclass, MINYEAR-1, 1, 1) + self.assertRaises(ValueError, self.theclass, MAXYEAR+1, 1, 1) + # bad months + self.theclass(2000, 1, 1) # no exception + self.theclass(2000, 12, 1) # no exception + self.assertRaises(ValueError, self.theclass, 2000, 0, 1) + self.assertRaises(ValueError, self.theclass, 2000, 13, 1) + # bad days + self.theclass(2000, 2, 29) # no exception + self.theclass(2004, 2, 29) # no exception + self.theclass(2400, 2, 29) # no exception + self.assertRaises(ValueError, self.theclass, 2000, 2, 30) + self.assertRaises(ValueError, self.theclass, 2001, 2, 29) + self.assertRaises(ValueError, self.theclass, 2100, 2, 29) + self.assertRaises(ValueError, self.theclass, 1900, 2, 29) + self.assertRaises(ValueError, self.theclass, 2000, 1, 0) + self.assertRaises(ValueError, self.theclass, 2000, 1, 32) + # bad hours + self.theclass(2000, 1, 31, 0) # no exception + self.theclass(2000, 1, 31, 23) # no exception + self.assertRaises(ValueError, self.theclass, 2000, 1, 31, -1) + self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 24) + # bad minutes + self.theclass(2000, 1, 31, 23, 0) # no exception + self.theclass(2000, 1, 31, 23, 59) # no exception + self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, -1) + self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, 60) + # bad seconds + self.theclass(2000, 1, 31, 23, 59, 0) # no exception + self.theclass(2000, 1, 31, 23, 59, 59) # no exception + self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, 59, -1) + self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, 59, 60) + # bad microseconds + self.theclass(2000, 1, 31, 23, 59, 59, 0) # no exception + self.theclass(2000, 1, 31, 23, 59, 59, 999999) # no exception + self.assertRaises(ValueError, self.theclass, + 2000, 1, 31, 23, 59, 59, -1) + self.assertRaises(ValueError, self.theclass, + 2000, 1, 31, 23, 59, 59, + 1000000) + + def test_hash_equality(self): + d = self.theclass(2000, 12, 31, 23, 30, 17) + e = self.theclass(2000, 12, 31, 23, 30, 17) + self.assertEqual(d, e) + self.assertEqual(hash(d), hash(e)) + + dic = {d: 1} + dic[e] = 2 + self.assertEqual(len(dic), 1) + self.assertEqual(dic[d], 2) + self.assertEqual(dic[e], 2) + + d = self.theclass(2001, 1, 1, 0, 5, 17) + e = self.theclass(2001, 1, 1, 0, 5, 17) + self.assertEqual(d, e) + self.assertEqual(hash(d), hash(e)) + + dic = {d: 1} + dic[e] = 2 + self.assertEqual(len(dic), 1) + self.assertEqual(dic[d], 2) + self.assertEqual(dic[e], 2) + + def test_computations(self): + a = self.theclass(2002, 1, 31) + b = self.theclass(1956, 1, 31) + diff = a-b + self.assertEqual(diff.days, 46*365 + len(range(1956, 2002, 4))) + self.assertEqual(diff.seconds, 0) + self.assertEqual(diff.microseconds, 0) + a = self.theclass(2002, 3, 2, 17, 6) + millisec = timedelta(0, 0, 1000) + hour = timedelta(0, 3600) + day = timedelta(1) + week = timedelta(7) + self.assertEqual(a + hour, self.theclass(2002, 3, 2, 18, 6)) + self.assertEqual(a + 10*hour, self.theclass(2002, 3, 3, 3, 6)) + self.assertEqual(a - hour, self.theclass(2002, 3, 2, 16, 6)) + self.assertEqual(a - hour, a + -hour) + self.assertEqual(a - 20*hour, self.theclass(2002, 3, 1, 21, 6)) + self.assertEqual(a + day, self.theclass(2002, 3, 3, 17, 6)) + self.assertEqual(a - day, self.theclass(2002, 3, 1, 17, 6)) + self.assertEqual(a + week, self.theclass(2002, 3, 9, 17, 6)) + self.assertEqual(a - week, self.theclass(2002, 2, 23, 17, 6)) + self.assertEqual(a + 52*week, self.theclass(2003, 3, 1, 17, 6)) + self.assertEqual(a - 52*week, self.theclass(2001, 3, 3, 17, 6)) + self.assertEqual((a + week) - a, week) + self.assertEqual((a + day) - a, day) + self.assertEqual((a + hour) - a, hour) + self.assertEqual((a + millisec) - a, millisec) + self.assertEqual((a - week) - a, -week) + self.assertEqual((a - day) - a, -day) + self.assertEqual((a - hour) - a, -hour) + self.assertEqual((a - millisec) - a, -millisec) + self.assertEqual(a - (a + week), -week) + self.assertEqual(a - (a + day), -day) + self.assertEqual(a - (a + hour), -hour) + self.assertEqual(a - (a + millisec), -millisec) + self.assertEqual(a - (a - week), week) + self.assertEqual(a - (a - day), day) + self.assertEqual(a - (a - hour), hour) + self.assertEqual(a - (a - millisec), millisec) + self.assertEqual(a + (week + day + hour + millisec), + self.theclass(2002, 3, 10, 18, 6, 0, 1000)) + self.assertEqual(a + (week + day + hour + millisec), + (((a + week) + day) + hour) + millisec) + self.assertEqual(a - (week + day + hour + millisec), + self.theclass(2002, 2, 22, 16, 5, 59, 999000)) + self.assertEqual(a - (week + day + hour + millisec), + (((a - week) - day) - hour) - millisec) + # Add/sub ints, longs, floats should be illegal + for i in 1, 1L, 1.0: + self.assertRaises(TypeError, lambda: a+i) + self.assertRaises(TypeError, lambda: a-i) + self.assertRaises(TypeError, lambda: i+a) + self.assertRaises(TypeError, lambda: i-a) def test_suite(): Index: test_datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_datetime.py,v retrieving revision 1.52 retrieving revision 1.53 diff -C2 -d -r1.52 -r1.53 *** test_datetime.py 26 Nov 2002 21:22:38 -0000 1.52 --- test_datetime.py 1 Dec 2002 19:37:28 -0000 1.53 *************** *** 215,358 **** theclass = datetime - def test_tz_independent_comparing(self): - dt1 = self.theclass(2002, 3, 1, 9, 0, 0) - dt2 = self.theclass(2002, 3, 1, 10, 0, 0) - dt3 = self.theclass(2002, 3, 1, 9, 0, 0) - self.assertEqual(dt1, dt3) - self.assert_(dt2 > dt3) - - # Make sure comparison doesn't forget microseconds, and isn't done - # via comparing a float timestamp (an IEEE double doesn't have enough - # precision to span microsecond resolution across years 1 thru 9999, - # so comparing via timestamp necessarily calls some distinct values - # equal). - dt1 = self.theclass(MAXYEAR, 12, 31, 23, 59, 59, 999998) - us = timedelta(microseconds=1) - dt2 = dt1 + us - self.assertEqual(dt2 - dt1, us) - self.assert_(dt1 < dt2) - - def test_bad_constructor_arguments(self): - # bad years - self.theclass(MINYEAR, 1, 1) # no exception - self.theclass(MAXYEAR, 1, 1) # no exception - self.assertRaises(ValueError, self.theclass, MINYEAR-1, 1, 1) - self.assertRaises(ValueError, self.theclass, MAXYEAR+1, 1, 1) - # bad months - self.theclass(2000, 1, 1) # no exception - self.theclass(2000, 12, 1) # no exception - self.assertRaises(ValueError, self.theclass, 2000, 0, 1) - self.assertRaises(ValueError, self.theclass, 2000, 13, 1) - # bad days - self.theclass(2000, 2, 29) # no exception - self.theclass(2004, 2, 29) # no exception - self.theclass(2400, 2, 29) # no exception - self.assertRaises(ValueError, self.theclass, 2000, 2, 30) - self.assertRaises(ValueError, self.theclass, 2001, 2, 29) - self.assertRaises(ValueError, self.theclass, 2100, 2, 29) - self.assertRaises(ValueError, self.theclass, 1900, 2, 29) - self.assertRaises(ValueError, self.theclass, 2000, 1, 0) - self.assertRaises(ValueError, self.theclass, 2000, 1, 32) - # bad hours - self.theclass(2000, 1, 31, 0) # no exception - self.theclass(2000, 1, 31, 23) # no exception - self.assertRaises(ValueError, self.theclass, 2000, 1, 31, -1) - self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 24) - # bad minutes - self.theclass(2000, 1, 31, 23, 0) # no exception - self.theclass(2000, 1, 31, 23, 59) # no exception - self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, -1) - self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, 60) - # bad seconds - self.theclass(2000, 1, 31, 23, 59, 0) # no exception - self.theclass(2000, 1, 31, 23, 59, 59) # no exception - self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, 59, -1) - self.assertRaises(ValueError, self.theclass, 2000, 1, 31, 23, 59, 60) - # bad microseconds - self.theclass(2000, 1, 31, 23, 59, 59, 0) # no exception - self.theclass(2000, 1, 31, 23, 59, 59, 999999) # no exception - self.assertRaises(ValueError, self.theclass, - 2000, 1, 31, 23, 59, 59, -1) - self.assertRaises(ValueError, self.theclass, - 2000, 1, 31, 23, 59, 59, - 1000000) - - def test_hash_equality(self): - d = self.theclass(2000, 12, 31, 23, 30, 17) - e = self.theclass(2000, 12, 31, 23, 30, 17) - self.assertEqual(d, e) - self.assertEqual(hash(d), hash(e)) - - dic = {d: 1} - dic[e] = 2 - self.assertEqual(len(dic), 1) - self.assertEqual(dic[d], 2) - self.assertEqual(dic[e], 2) - - d = self.theclass(2001, 1, 1, 0, 5, 17) - e = self.theclass(2001, 1, 1, 0, 5, 17) - self.assertEqual(d, e) - self.assertEqual(hash(d), hash(e)) - - dic = {d: 1} - dic[e] = 2 - self.assertEqual(len(dic), 1) - self.assertEqual(dic[d], 2) - self.assertEqual(dic[e], 2) - - def test_computations(self): - a = self.theclass(2002, 1, 31) - b = self.theclass(1956, 1, 31) - diff = a-b - self.assertEqual(diff.days, 46*365 + len(range(1956, 2002, 4))) - self.assertEqual(diff.seconds, 0) - self.assertEqual(diff.microseconds, 0) - a = self.theclass(2002, 3, 2, 17, 6) - millisec = timedelta(0, 0, 1000) - hour = timedelta(0, 3600) - day = timedelta(1) - week = timedelta(7) - self.assertEqual(a + hour, self.theclass(2002, 3, 2, 18, 6)) - self.assertEqual(a + 10*hour, self.theclass(2002, 3, 3, 3, 6)) - self.assertEqual(a - hour, self.theclass(2002, 3, 2, 16, 6)) - self.assertEqual(a - hour, a + -hour) - self.assertEqual(a - 20*hour, self.theclass(2002, 3, 1, 21, 6)) - self.assertEqual(a + day, self.theclass(2002, 3, 3, 17, 6)) - self.assertEqual(a - day, self.theclass(2002, 3, 1, 17, 6)) - self.assertEqual(a + week, self.theclass(2002, 3, 9, 17, 6)) - self.assertEqual(a - week, self.theclass(2002, 2, 23, 17, 6)) - self.assertEqual(a + 52*week, self.theclass(2003, 3, 1, 17, 6)) - self.assertEqual(a - 52*week, self.theclass(2001, 3, 3, 17, 6)) - self.assertEqual((a + week) - a, week) - self.assertEqual((a + day) - a, day) - self.assertEqual((a + hour) - a, hour) - self.assertEqual((a + millisec) - a, millisec) - self.assertEqual((a - week) - a, -week) - self.assertEqual((a - day) - a, -day) - self.assertEqual((a - hour) - a, -hour) - self.assertEqual((a - millisec) - a, -millisec) - self.assertEqual(a - (a + week), -week) - self.assertEqual(a - (a + day), -day) - self.assertEqual(a - (a + hour), -hour) - self.assertEqual(a - (a + millisec), -millisec) - self.assertEqual(a - (a - week), week) - self.assertEqual(a - (a - day), day) - self.assertEqual(a - (a - hour), hour) - self.assertEqual(a - (a - millisec), millisec) - self.assertEqual(a + (week + day + hour + millisec), - self.theclass(2002, 3, 10, 18, 6, 0, 1000)) - self.assertEqual(a + (week + day + hour + millisec), - (((a + week) + day) + hour) + millisec) - self.assertEqual(a - (week + day + hour + millisec), - self.theclass(2002, 2, 22, 16, 5, 59, 999000)) - self.assertEqual(a - (week + day + hour + millisec), - (((a - week) - day) - hour) - millisec) - # Add/sub ints, longs, floats should be illegal - for i in 1, 1L, 1.0: - self.assertRaises(TypeError, lambda: a+i) - self.assertRaises(TypeError, lambda: a-i) - self.assertRaises(TypeError, lambda: i+a) - self.assertRaises(TypeError, lambda: i-a) - def test_tmxxx(self): from datetime import tmxxx --- 215,218 ---- --- test_cdatetime.py DELETED --- From jvr@users.sourceforge.net Sun Dec 1 21:43:15 2002 From: jvr@users.sourceforge.net (jvr@users.sourceforge.net) Date: Sun, 01 Dec 2002 13:43:15 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.550,1.551 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv6682 Modified Files: NEWS Log Message: The new imp.[gs]et_frozenmodules() will be utterly redundant if the zipfile import stuff get in. I'll probably back it out again. Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.550 retrieving revision 1.551 diff -C2 -d -r1.550 -r1.551 *** NEWS 29 Nov 2002 20:47:39 -0000 1.550 --- NEWS 1 Dec 2002 21:43:13 -0000 1.551 *************** *** 16,20 **** imp.get_frozenmodules() and imp.set_frozenmodules(). This is useful for freezing tools written in Python that use Python for ! bootstrapping the frozen application. - One can now assign to __bases__ and __name__ of new-style classes. --- 16,21 ---- imp.get_frozenmodules() and imp.set_frozenmodules(). This is useful for freezing tools written in Python that use Python for ! bootstrapping the frozen application. (XXX: this feature will be ! backed out if the zipfile import mechanism gets in before 2.3.a1.) - One can now assign to __bases__ and __name__ of new-style classes. From jvr@users.sourceforge.net Sun Dec 1 22:10:39 2002 From: jvr@users.sourceforge.net (jvr@users.sourceforge.net) Date: Sun, 01 Dec 2002 14:10:39 -0800 Subject: [Python-checkins] python/dist/src/Mac/Tools/IDE PyBrowser.py,1.17,1.18 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Tools/IDE In directory sc8-pr-cvs1:/tmp/cvs-serv18532 Modified Files: PyBrowser.py Log Message: - reworked the object unpacking code, now supports new-style objects more or less decently/completely. - cleaned up a little. Index: PyBrowser.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Tools/IDE/PyBrowser.py,v retrieving revision 1.17 retrieving revision 1.18 diff -C2 -d -r1.17 -r1.18 *** PyBrowser.py 30 Nov 2002 00:01:25 -0000 1.17 --- PyBrowser.py 1 Dec 2002 22:10:36 -0000 1.18 *************** *** 503,533 **** SIMPLE_TYPES = ( ! types.NoneType, ! types.IntType, ! types.LongType, ! types.FloatType, ! types.ComplexType, ! types.StringType ) ! INDEXING_TYPES = ( ! types.TupleType, ! types.ListType, ! types.DictionaryType ! ) def unpack_object(object, indent = 0): tp = type(object) ! if tp in SIMPLE_TYPES and tp is not types.NoneType: raise TypeError, "can't browse simple type: %s" % tp.__name__ ! elif tp == types.DictionaryType: return unpack_dict(object, indent) ! elif tp in (types.TupleType, types.ListType): return unpack_sequence(object, indent) ! elif tp == types.InstanceType: ! return unpack_instance(object, indent) ! elif tp == types.ClassType: ! return unpack_class(object, indent) ! elif tp == types.ModuleType: return unpack_dict(object.__dict__, indent) else: --- 503,553 ---- SIMPLE_TYPES = ( ! type(None), ! int, ! long, ! float, ! complex, ! str, ! unicode, ) ! def get_ivars(obj): ! """Return a list the names of all (potential) instance variables.""" ! # __mro__ recipe from Guido ! slots = {} ! # old-style C objects ! if hasattr(obj, "__members__"): ! for name in obj.__members__: ! slots[name] = None ! if hasattr(obj, "__methods__"): ! for name in obj.__methods__: ! slots[name] = None ! # generic type ! if hasattr(obj, "__dict__"): ! slots.update(obj.__dict__) ! cls = type(obj) ! if hasattr(cls, "__mro__"): ! # new-style class, use descriptors ! for base in cls.__mro__: ! for name, value in base.__dict__.items(): ! # XXX using callable() is a heuristic which isn't 100% ! # foolproof. ! if hasattr(value, "__get__") and not callable(value): ! slots[name] = None ! if "__dict__" in slots: ! del slots["__dict__"] ! slots = slots.keys() ! slots.sort() ! return slots def unpack_object(object, indent = 0): tp = type(object) ! if isinstance(object, SIMPLE_TYPES) and object is not None: raise TypeError, "can't browse simple type: %s" % tp.__name__ ! elif isinstance(object, dict): return unpack_dict(object, indent) ! elif isinstance(object, (tuple, list)): return unpack_sequence(object, indent) ! elif isinstance(object, types.ModuleType): return unpack_dict(object.__dict__, indent) else: *************** *** 556,576 **** def unpack_other(object, indent = 0): ! attrs = [] ! if hasattr(object, '__members__'): ! attrs = attrs + object.__members__ ! if hasattr(object, '__methods__'): ! attrs = attrs + object.__methods__ ! if hasattr(object, '__dict__'): ! attrs = attrs + object.__dict__.keys() ! if hasattr(object, '__slots__'): ! # XXX?? ! attrs = attrs + object.__slots__ ! if hasattr(object, "__class__") and "__class__" not in attrs: ! attrs.append("__class__") ! if hasattr(object, "__doc__") and "__doc__" not in attrs: ! attrs.append("__doc__") items = [] for attr in attrs: ! items.append((attr, getattr(object, attr))) return pack_items(items, indent) --- 576,588 ---- def unpack_other(object, indent = 0): ! attrs = get_ivars(object) items = [] for attr in attrs: ! try: ! value = getattr(object, attr) ! except: ! pass ! else: ! items.append((attr, value)) return pack_items(items, indent) From tim_one@users.sourceforge.net Sun Dec 1 23:49:59 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sun, 01 Dec 2002 15:49:59 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.c,1.29,1.30 obj_delta.c,1.8,1.9 test_both.py,1.11,1.12 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv1725 Modified Files: datetime.c obj_delta.c test_both.py Log Message: Purged some now-unused code and fixed some comments. PROBLEM: Noted that timedelta comparison doesn't work as intended. I assume the same is true for all comparisons defined here. I don't know whether this is a bug in Python (current CVS), or a bug here, so don't know how to fix it. For example, cmp(timedelta(whatever), 42) ends up comparing the type names of the objects, despite that timedelta's tp_compare function is trying its darnedest to raise TypeError then. Turns out the tp_compare function isn't called unless both objects are timedeltas. Index: datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.c,v retrieving revision 1.29 retrieving revision 1.30 diff -C2 -d -r1.29 -r1.30 *** datetime.c 1 Dec 2002 19:37:28 -0000 1.29 --- datetime.c 1 Dec 2002 23:49:56 -0000 1.30 *************** *** 374,404 **** } - /* Fiddle days (d), hours (h), and minutes (m) so that - * 0 <= *h < 24 - * 0 <= *m < 60 - * The input values must be such that the internals don't overflow. - * The way this routine is used, we don't get close. - */ - static void - normalize_d_h_m(long *d, long *h, long *m) - { - if (*m < 0 || *m >= 60) { - normalize_pair(h, m, 60); - /* |h| can't be bigger than about - * |original h| + |original m|/60 now. - */ - - } - if (*h < 0 || *h >= 24) { - normalize_pair(d, h, 24); - /* |d| can't be bigger than about - * |original d| + - * (|original h| + |original m|/60) / 24 now. - */ - } - assert(0 <= *h && *h < 24); - assert(0 <= *m && *m < 60); - } - /* Fiddle days (d), seconds (s), and microseconds (us) so that * 0 <= *s < 24*3600 --- 374,377 ---- *************** *** 426,489 **** assert(0 <= *s && *s < 24*3600); assert(0 <= *us && *us < 1000000); - } - - /* Fiddle days (d), seconds (s), and microseconds (us) so that the output - * duration is the same as the input duration, but with hours (h), - * minutes (m), and milliseconds (ms) all 0. - * The input values must be such that the internals don't overflow. The - * way this routine is used, we don't get close. - * The output d, s, and us are intended to be passed to normalize_d_s_us - * to get them into their proper ranges. - */ - static void - squash_h_m_ms_out_of_d_h_m_s_ms_us(long *d, long h, long m, - long *s, long ms, long *us) - { - if (h) { - long new_minutes; - - normalize_pair(d, &h, 24); - /* |d| can't be bigger than about - * |original d| + |original h|/24 now. - * h can't bigger than 23. - */ - new_minutes = m + h*60; - assert(! SIGNED_ADD_OVERFLOWED(new_minutes, m, h*60)); - m = new_minutes; - /* |m| can't be bigger than about - * |original m| + 23*60 now. - */ - } - if (m) { - long new_seconds; - - normalize_pair(d, &m, 24*60); - /* |d| can't be bigger than about - * |original d| + |original h|/24 + - * (|original m| + 23*60)/(24*60) now. - * m can't bigger than 24*60-1. - */ - new_seconds = *s + m*60; - assert(! SIGNED_ADD_OVERFLOWED(new_seconds, *s, m*60)); - *s = new_seconds; - /* |s| can't be bigger than about - * |original s| + (24*60-1) * 60 now. - */ - } - if (ms) { - long new_us; - - normalize_pair(s, &ms, 1000); - /* |s| can't be bigger than about - * |original s| + (24*60-1) * 60 + |original ms|/1000 now. - * ms can't be bigger than 999. - */ - new_us = *us + ms * 1000; - assert(! SIGNED_ADD_OVERFLOWED(new_us, *us, ms*1000)); - *us = new_us; - /* |us| can't be bigger than about - * |original us| + 999 * 1000. - */ - } } --- 399,402 ---- Index: obj_delta.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_delta.c,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** obj_delta.c 1 Dec 2002 19:37:28 -0000 1.8 --- obj_delta.c 1 Dec 2002 23:49:56 -0000 1.9 *************** *** 169,177 **** delta_add(PyObject *left, PyObject *right) { ! PyTypeObject *left_type = left->ob_type; ! PyTypeObject *right_type = right->ob_type; ! if (PyType_IsSubtype(left_type, &PyDateTime_DeltaType) && ! PyType_IsSubtype(right_type, &PyDateTime_DeltaType)) { /* delta + delta */ /* The C-level additions can't overflow because of the --- 169,176 ---- delta_add(PyObject *left, PyObject *right) { ! PyObject *result = Py_NotImplemented; ! if (PyType_IsSubtype(left->ob_type, &PyDateTime_DeltaType) && ! PyType_IsSubtype(right->ob_type, &PyDateTime_DeltaType)) { /* delta + delta */ /* The C-level additions can't overflow because of the *************** *** 182,189 **** long microseconds = GET_TD_MICROSECONDS(left) + GET_TD_MICROSECONDS(right); ! return new_delta(days, seconds, microseconds); } ! Py_INCREF(Py_NotImplemented); ! return Py_NotImplemented; } --- 181,190 ---- long microseconds = GET_TD_MICROSECONDS(left) + GET_TD_MICROSECONDS(right); ! result = new_delta(days, seconds, microseconds); } ! ! if (result == Py_NotImplemented) ! Py_INCREF(result); ! return result; } *************** *** 226,232 **** delta_subtract(PyObject *left, PyObject *right) { ! PyObject *result = NULL; - /* XXX It's unclear to me exactly which rules we intend here. */ if (PyType_IsSubtype(left->ob_type, &PyDateTime_DeltaType) && PyType_IsSubtype(right->ob_type, &PyDateTime_DeltaType)) { --- 227,232 ---- delta_subtract(PyObject *left, PyObject *right) { ! PyObject *result = Py_NotImplemented; if (PyType_IsSubtype(left->ob_type, &PyDateTime_DeltaType) && PyType_IsSubtype(right->ob_type, &PyDateTime_DeltaType)) { *************** *** 237,248 **** Py_DECREF(minus_right); } } - else - result = Py_NotImplemented; ! Py_XINCREF(result); return result; } static int delta_compare(PyDateTime_Delta *self, PyObject *other) --- 237,254 ---- Py_DECREF(minus_right); } + else + result = NULL; } ! if (result == Py_NotImplemented) ! Py_INCREF(result); return result; } + /* XXX This routine is never entered unless self and other are both + * XXX PyDateTime_Delta. For whatever reason, Python's try_3way_compare + * XXX ignores tp_compare unless PyInstance_Check returns true, but + * XXX these aren't old-style classes. + */ static int delta_compare(PyDateTime_Delta *self, PyObject *other) *************** *** 250,257 **** int result = -1; ! if (!PyObject_TypeCheck(other, &PyDateTime_DeltaType)) PyErr_Format(PyExc_TypeError, "can't compare %s to %s instance", self->ob_type->tp_name, other->ob_type->tp_name); else { long diff = GET_TD_DAYS(self) - GET_TD_DAYS(other); --- 256,265 ---- int result = -1; ! if (! PyObject_TypeCheck(other, &PyDateTime_DeltaType)) { ! /* XXX Dead code! See note above. */ PyErr_Format(PyExc_TypeError, "can't compare %s to %s instance", self->ob_type->tp_name, other->ob_type->tp_name); + } else { long diff = GET_TD_DAYS(self) - GET_TD_DAYS(other); *************** *** 325,329 **** /* Fold in the value of the tag ("seconds", "weeks", etc) component of a ! * a timedelta constructor. sofar is the # of microseconds accounted for * so far, and there are factor microseconds per current unit, the number * of which is given by num. num * factor is added to sofar in a --- 333,337 ---- /* Fold in the value of the tag ("seconds", "weeks", etc) component of a ! * timedelta constructor. sofar is the # of microseconds accounted for * so far, and there are factor microseconds per current unit, the number * of which is given by num. num * factor is added to sofar in a *************** *** 332,336 **** * added into *leftover. * If num is NULL, no computation is done, and sofar is returned (after ! * incremented its refcount). * Note that there are many ways this can give an error (NULL) return. */ --- 340,344 ---- * added into *leftover. * If num is NULL, no computation is done, and sofar is returned (after ! * incrementing its refcount). * Note that there are many ways this can give an error (NULL) return. */ *************** *** 502,505 **** --- 510,514 ---- if (leftover_us) { + /* Round to nearest whole # of us, and add into x. */ PyObject *temp; if (leftover_us >= 0.0) Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** test_both.py 1 Dec 2002 19:37:28 -0000 1.11 --- test_both.py 1 Dec 2002 23:49:56 -0000 1.12 *************** *** 112,120 **** def test_hash_equality(self): t1 = timedelta(days=100, ! weeks=-7, ! hours=-24*(100-49), ! minutes=-3, ! seconds=12, ! microseconds=(3*60 - 12) * 1000000) t2 = timedelta() self.assertEqual(hash(t1), hash(t2)) --- 112,120 ---- def test_hash_equality(self): t1 = timedelta(days=100, ! weeks=-7, ! hours=-24*(100-49), ! minutes=-3, ! seconds=12, ! microseconds=(3*60 - 12) * 1000000) t2 = timedelta() self.assertEqual(hash(t1), hash(t2)) From montanaro@users.sourceforge.net Mon Dec 2 00:27:12 2002 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Sun, 01 Dec 2002 16:27:12 -0800 Subject: [Python-checkins] python/dist/src/Modules Setup.dist,1.32,1.33 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv25902 Modified Files: Setup.dist Log Message: correct wording of comments about old bsddb (now bsddb185) module Index: Setup.dist =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/Setup.dist,v retrieving revision 1.32 retrieving revision 1.33 diff -C2 -d -r1.32 -r1.33 *** Setup.dist 19 Nov 2002 08:30:08 -0000 1.32 --- Setup.dist 2 Dec 2002 00:27:10 -0000 1.33 *************** *** 414,423 **** # Historical Berkeley DB 1.85 # ! # This requires the Berkeley DB code, see ! # ftp://ftp.cs.berkeley.edu/pub/4bsd/db.1.85.tar.gz ! # ! # This module is deprecated; the historical BSDDB library has bugs ! # that can cause data corruption. If you can, use the Sleepycat library ! # instead. #DB=/depot/sundry/src/berkeley-db/db.1.85 #DBPORT=$(DB)/PORT/irix.5.3 --- 414,421 ---- # Historical Berkeley DB 1.85 # ! # This module is deprecated; the 1.85 version of the Berkeley DB library has ! # bugs that can cause data corruption. If you can, use later versions of the ! # library instead, available from . ! #DB=/depot/sundry/src/berkeley-db/db.1.85 #DBPORT=$(DB)/PORT/irix.5.3 From tim_one@users.sourceforge.net Mon Dec 2 00:32:24 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sun, 01 Dec 2002 16:32:24 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_delta.c,1.9,1.10 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv27769 Modified Files: obj_delta.c Log Message: Implemented __getstate__ and __setstate__ for timedelta. PROBLEM: This was intended to support pickling, but doesn't work for that purpose (see the XXX comments). Turns out I have no idea how to pickle a new-style instance of a type coded in C (it's easy if coded in Python). Index: obj_delta.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_delta.c,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** obj_delta.c 1 Dec 2002 23:49:56 -0000 1.9 --- obj_delta.c 2 Dec 2002 00:32:22 -0000 1.10 *************** *** 563,578 **** } #define OFFSET(field) offsetof(PyDateTime_Delta, field) static PyMemberDef delta_members[] = { {"days", T_LONG, OFFSET(days), READONLY, ! "Number os days."}, {"seconds", T_LONG, OFFSET(seconds), READONLY, ! "Number of seconds (less than 1 day)."}, {"microseconds", T_LONG, OFFSET(microseconds), READONLY, ! "Number of microseconds (less than 1 second)."}, {NULL} }; static char delta_doc[] = "Difference between two datetime values."; --- 563,623 ---- } + /* XXX Broken attempt to get pickles working. An attempt to pickle + * XXX craps out in + * XXX + * XXX if base is self.__class__: + * XXX raise TypeError, "can't pickle %s objects" % base.__name__ + * XXX + * XXX in Python's copy_reg.py. How to fix? + */ + static PyObject * + delta_getstate(PyDateTime_Delta *self, PyObject *args) + { + if (!PyArg_ParseTuple(args, ":getstate")) + return NULL; + return Py_BuildValue("lll", GET_TD_DAYS(self), + GET_TD_SECONDS(self), + GET_TD_MICROSECONDS(self)); + } + + static PyObject * + delta_setstate(PyDateTime_Delta *self, PyObject *args) + { + long day; + long second; + long us; + + if (!PyArg_ParseTuple(args, "lll", &day, &second, &us)) + return NULL; + + self->hashcode = -1; + SET_TD_DAYS(self, day); + SET_TD_SECONDS(self, second); + SET_TD_MICROSECONDS(self, us); + + Py_INCREF(Py_None); + return Py_None; + } + #define OFFSET(field) offsetof(PyDateTime_Delta, field) static PyMemberDef delta_members[] = { {"days", T_LONG, OFFSET(days), READONLY, ! PyDoc_STR("Number of days.")}, {"seconds", T_LONG, OFFSET(seconds), READONLY, ! PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")}, {"microseconds", T_LONG, OFFSET(microseconds), READONLY, ! PyDoc_STR("Number of microseconds (>= and less than 1 second).")}, {NULL} }; + static PyMethodDef delta_methods[] = { + {"__getstate__", (PyCFunction)delta_getstate, METH_VARARGS, + PyDoc_STR("__getstate__() -> state")}, + {"__setstate__", (PyCFunction)delta_setstate, METH_VARARGS, + PyDoc_STR("__setstate__(state)")}, + {NULL, NULL}, + }; + static char delta_doc[] = "Difference between two datetime values."; *************** *** 647,651 **** 0, /* tp_iter */ 0, /* tp_iternext */ ! 0, /* tp_methods */ delta_members, /* tp_members */ 0, /* tp_getset */ --- 692,696 ---- 0, /* tp_iter */ 0, /* tp_iternext */ ! delta_methods, /* tp_methods */ delta_members, /* tp_members */ 0, /* tp_getset */ From tim_one@users.sourceforge.net Mon Dec 2 00:41:35 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sun, 01 Dec 2002 16:41:35 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_delta.c,1.10,1.11 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv1720 Modified Files: obj_delta.c Log Message: accum(): skip some of the expensive stuff when a keyword arg is a float, but is really just an integer in float format. Index: obj_delta.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_delta.c,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** obj_delta.c 2 Dec 2002 00:32:22 -0000 1.10 --- obj_delta.c 2 Dec 2002 00:41:33 -0000 1.11 *************** *** 397,400 **** --- 397,402 ---- return NULL; + if (fracpart == 0.0) + return sum; /* So far we've lost no information. Dealing with the * fractional part requires float arithmetic, and may From tim_one@users.sourceforge.net Mon Dec 2 00:49:52 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sun, 01 Dec 2002 16:49:52 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_delta.c,1.11,1.12 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv6470 Modified Files: obj_delta.c Log Message: accum() and delta_new(): just skip over keyword args that weren't given. This is quicker in almost all cases, and gets rid of a wart in accum(). Index: obj_delta.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_delta.c,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** obj_delta.c 2 Dec 2002 00:41:33 -0000 1.11 --- obj_delta.c 2 Dec 2002 00:49:50 -0000 1.12 *************** *** 339,344 **** * microseconds left over (this can happen if num is a float type) are * added into *leftover. - * If num is NULL, no computation is done, and sofar is returned (after - * incrementing its refcount). * Note that there are many ways this can give an error (NULL) return. */ --- 339,342 ---- *************** *** 350,357 **** PyObject *sum; ! if (num == NULL) { ! Py_INCREF(sofar); ! return sofar; ! } if (PyInt_Check(num) || PyLong_Check(num)) { --- 348,352 ---- PyObject *sum; ! assert(num != NULL); if (PyInt_Check(num) || PyLong_Check(num)) { *************** *** 444,453 **** PyObject *week = NULL; ! PyObject *x = NULL; ! PyObject *y = NULL; double leftover_us = 0.0; - PyObject *one; - static char *keywords[] = { "days", "seconds", "microseconds", "milliseconds", --- 439,446 ---- PyObject *week = NULL; ! PyObject *x = NULL; /* running sum of microseconds */ ! PyObject *y = NULL; /* temp sum of microseconds */ double leftover_us = 0.0; static char *keywords[] = { "days", "seconds", "microseconds", "milliseconds", *************** *** 465,514 **** goto Done; ! one = PyInt_FromLong(1); ! if (one == NULL) ! goto Done; ! y = accum("microseconds", x, us, one, &leftover_us); ! Py_DECREF(one); ! Py_DECREF(x); ! x = y; ! if (x == NULL) ! goto Done; ! ! y = accum("milliseconds", x, ms, us_per_ms, &leftover_us); ! Py_DECREF(x); ! x = y; ! if (x == NULL) ! goto Done; ! ! y = accum("seconds", x, second, us_per_second, &leftover_us); ! Py_DECREF(x); ! x = y; ! if (x == NULL) ! goto Done; ! ! y = accum("minutes", x, minute, us_per_minute, &leftover_us); ! Py_DECREF(x); ! x = y; ! if (x == NULL) ! goto Done; ! ! y = accum("hours", x, hour, us_per_hour, &leftover_us); ! Py_DECREF(x); ! x = y; ! if (x == NULL) ! goto Done; ! ! y = accum("days", x, day, us_per_day, &leftover_us); ! Py_DECREF(x); ! x = y; ! if (x == NULL) ! goto Done; ! ! y = accum("weeks", x, week, us_per_week, &leftover_us); ! Py_DECREF(x); ! x = y; ! if (x == NULL) ! goto Done; ! if (leftover_us) { /* Round to nearest whole # of us, and add into x. */ --- 458,514 ---- goto Done; ! if (us) { ! PyObject *one = PyInt_FromLong(1); ! if (one == NULL) ! goto Done; ! y = accum("microseconds", x, us, one, &leftover_us); ! Py_DECREF(one); ! Py_DECREF(x); ! x = y; ! if (x == NULL) ! goto Done; ! } ! if (ms) { ! y = accum("milliseconds", x, ms, us_per_ms, &leftover_us); ! Py_DECREF(x); ! x = y; ! if (x == NULL) ! goto Done; ! } ! if (second) { ! y = accum("seconds", x, second, us_per_second, &leftover_us); ! Py_DECREF(x); ! x = y; ! if (x == NULL) ! goto Done; ! } ! if (minute) { ! y = accum("minutes", x, minute, us_per_minute, &leftover_us); ! Py_DECREF(x); ! x = y; ! if (x == NULL) ! goto Done; ! } ! if (hour) { ! y = accum("hours", x, hour, us_per_hour, &leftover_us); ! Py_DECREF(x); ! x = y; ! if (x == NULL) ! goto Done; ! } ! if (day) { ! y = accum("days", x, day, us_per_day, &leftover_us); ! Py_DECREF(x); ! x = y; ! if (x == NULL) ! goto Done; ! } ! if (week) { ! y = accum("weeks", x, week, us_per_week, &leftover_us); ! Py_DECREF(x); ! x = y; ! if (x == NULL) ! goto Done; ! } if (leftover_us) { /* Round to nearest whole # of us, and add into x. */ From tim_one@users.sourceforge.net Mon Dec 2 00:57:06 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sun, 01 Dec 2002 16:57:06 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.c,1.30,1.31 obj_delta.c,1.12,1.13 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv11595 Modified Files: datetime.c obj_delta.c Log Message: delta_new(): Don't make a special case out of 1 anymore, and introduced a trivial local macro to reduce the mind-numbing repetition. Index: datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.c,v retrieving revision 1.30 retrieving revision 1.31 diff -C2 -d -r1.30 -r1.31 *** datetime.c 1 Dec 2002 23:49:56 -0000 1.30 --- datetime.c 2 Dec 2002 00:57:04 -0000 1.31 *************** *** 469,480 **** } ! static PyObject *us_per_ms = NULL; ! static PyObject *us_per_second = NULL; ! static PyObject *us_per_minute = NULL; ! static PyObject *us_per_hour = NULL; ! static PyObject *us_per_day = NULL; ! static PyObject *us_per_week = NULL; ! static PyObject *seconds_per_day = NULL; /* Create a date instance with no range checking. */ --- 469,481 ---- } ! static PyObject *us_per_us = NULL; /* 1 */ ! static PyObject *us_per_ms = NULL; /* 1000 */ ! static PyObject *us_per_second = NULL; /* 1000000 */ ! static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */ ! static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */ ! static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */ ! static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */ ! static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */ /* Create a date instance with no range checking. */ *************** *** 616,619 **** --- 617,621 ---- assert(DI100Y == days_before_year(100+1)); + us_per_us = PyInt_FromLong(1); us_per_ms = PyInt_FromLong(1000); us_per_second = PyInt_FromLong(1000000); Index: obj_delta.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_delta.c,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** obj_delta.c 2 Dec 2002 00:49:50 -0000 1.12 --- obj_delta.c 2 Dec 2002 00:57:04 -0000 1.13 *************** *** 458,513 **** goto Done; if (us) { ! PyObject *one = PyInt_FromLong(1); ! if (one == NULL) ! goto Done; ! y = accum("microseconds", x, us, one, &leftover_us); ! Py_DECREF(one); ! Py_DECREF(x); ! x = y; ! if (x == NULL) ! goto Done; } if (ms) { y = accum("milliseconds", x, ms, us_per_ms, &leftover_us); ! Py_DECREF(x); ! x = y; ! if (x == NULL) ! goto Done; } if (second) { y = accum("seconds", x, second, us_per_second, &leftover_us); ! Py_DECREF(x); ! x = y; ! if (x == NULL) ! goto Done; } if (minute) { y = accum("minutes", x, minute, us_per_minute, &leftover_us); ! Py_DECREF(x); ! x = y; ! if (x == NULL) ! goto Done; } if (hour) { y = accum("hours", x, hour, us_per_hour, &leftover_us); ! Py_DECREF(x); ! x = y; ! if (x == NULL) ! goto Done; } if (day) { y = accum("days", x, day, us_per_day, &leftover_us); ! Py_DECREF(x); ! x = y; ! if (x == NULL) ! goto Done; } if (week) { y = accum("weeks", x, week, us_per_week, &leftover_us); ! Py_DECREF(x); ! x = y; ! if (x == NULL) ! goto Done; } if (leftover_us) { --- 458,494 ---- goto Done; + #define CLEANUP \ + Py_DECREF(x); \ + x = y; \ + if (x == NULL) \ + goto Done + if (us) { ! y = accum("microseconds", x, us, us_per_us, &leftover_us); ! CLEANUP; } if (ms) { y = accum("milliseconds", x, ms, us_per_ms, &leftover_us); ! CLEANUP; } if (second) { y = accum("seconds", x, second, us_per_second, &leftover_us); ! CLEANUP; } if (minute) { y = accum("minutes", x, minute, us_per_minute, &leftover_us); ! CLEANUP; } if (hour) { y = accum("hours", x, hour, us_per_hour, &leftover_us); ! CLEANUP; } if (day) { y = accum("days", x, day, us_per_day, &leftover_us); ! CLEANUP; } if (week) { y = accum("weeks", x, week, us_per_week, &leftover_us); ! CLEANUP; } if (leftover_us) { *************** *** 525,532 **** y = PyNumber_Add(x, temp); Py_DECREF(temp); ! Py_DECREF(x); ! x = y; ! if (x == NULL) ! goto Done; } --- 506,510 ---- y = PyNumber_Add(x, temp); Py_DECREF(temp); ! CLEANUP; } *************** *** 535,538 **** --- 513,518 ---- Done: return self; + + #undef CLEANUP } From nnorwitz@users.sourceforge.net Mon Dec 2 04:40:23 2002 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 01 Dec 2002 20:40:23 -0800 Subject: [Python-checkins] python/dist/src/Doc/ext run-func.c,1.2,1.3 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/ext In directory sc8-pr-cvs1:/tmp/cvs-serv23948/Doc/ext Modified Files: run-func.c Log Message: Remove unused variable Index: run-func.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/ext/run-func.c,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** run-func.c 6 Sep 2001 16:20:33 -0000 1.2 --- run-func.c 2 Dec 2002 04:40:21 -0000 1.3 *************** *** 6,10 **** PyObject *pName, *pModule, *pDict, *pFunc; PyObject *pArgs, *pValue; ! int i, result; if (argc < 3) { --- 6,10 ---- PyObject *pName, *pModule, *pDict, *pFunc; PyObject *pArgs, *pValue; ! int i; if (argc < 3) { From nnorwitz@users.sourceforge.net Mon Dec 2 04:43:00 2002 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 01 Dec 2002 20:43:00 -0800 Subject: [Python-checkins] python/dist/src/Doc/ext embedding.tex,1.7,1.8 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/ext In directory sc8-pr-cvs1:/tmp/cvs-serv24771/Doc/ext Modified Files: embedding.tex Log Message: Fix SF # 646578, Documentation Typo Index: embedding.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/ext/embedding.tex,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** embedding.tex 22 Aug 2002 19:15:35 -0000 1.7 --- embedding.tex 2 Dec 2002 04:42:58 -0000 1.8 *************** *** 156,160 **** \begin{verbatim} ! $ call multiply 3 2 Will compute 3 times 2 Result of call: 6 --- 156,160 ---- \begin{verbatim} ! $ call multiply multiply 3 2 Will compute 3 times 2 Result of call: 6 From nnorwitz@users.sourceforge.net Mon Dec 2 04:44:35 2002 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 01 Dec 2002 20:44:35 -0800 Subject: [Python-checkins] python/dist/src/Doc/ext run-func.c,1.2,1.2.14.1 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/ext In directory sc8-pr-cvs1:/tmp/cvs-serv25437/Doc/ext Modified Files: Tag: release22-maint run-func.c Log Message: Remove unused variable Index: run-func.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/ext/run-func.c,v retrieving revision 1.2 retrieving revision 1.2.14.1 diff -C2 -d -r1.2 -r1.2.14.1 *** run-func.c 6 Sep 2001 16:20:33 -0000 1.2 --- run-func.c 2 Dec 2002 04:44:33 -0000 1.2.14.1 *************** *** 6,10 **** PyObject *pName, *pModule, *pDict, *pFunc; PyObject *pArgs, *pValue; ! int i, result; if (argc < 3) { --- 6,10 ---- PyObject *pName, *pModule, *pDict, *pFunc; PyObject *pArgs, *pValue; ! int i; if (argc < 3) { From nnorwitz@users.sourceforge.net Mon Dec 2 04:47:12 2002 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Sun, 01 Dec 2002 20:47:12 -0800 Subject: [Python-checkins] python/dist/src/Doc/ext embedding.tex,1.4.6.1,1.4.6.2 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/ext In directory sc8-pr-cvs1:/tmp/cvs-serv26647/Doc/ext Modified Files: Tag: release22-maint embedding.tex Log Message: Fix SF # 646578, Documentation Typo Index: embedding.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/ext/embedding.tex,v retrieving revision 1.4.6.1 retrieving revision 1.4.6.2 diff -C2 -d -r1.4.6.1 -r1.4.6.2 *** embedding.tex 21 Jun 2002 13:11:12 -0000 1.4.6.1 --- embedding.tex 2 Dec 2002 04:47:10 -0000 1.4.6.2 *************** *** 156,160 **** \begin{verbatim} ! $ call multiply 3 2 Thy shall add 3 times 2 Result of call: 6 --- 156,160 ---- \begin{verbatim} ! $ call multiply multiply 3 2 Thy shall add 3 times 2 Result of call: 6 From tim_one@users.sourceforge.net Mon Dec 2 06:06:51 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sun, 01 Dec 2002 22:06:51 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.py,1.67,1.68 obj_delta.c,1.13,1.14 test_both.py,1.12,1.13 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv21853 Modified Files: datetime.py obj_delta.c test_both.py Log Message: timedelta pickling: cleaned up the C implementation, added a Python implementation, added a shared test case. Problem: pickling still can't be done via the C implementation, and I still don't understand why not. __getstate__ and __setstate__ are functioning fine (as the new test verifies before it blows up trying to pickle). Index: datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.py,v retrieving revision 1.67 retrieving revision 1.68 diff -C2 -d -r1.67 -r1.68 *** datetime.py 1 Dec 2002 19:37:28 -0000 1.67 --- datetime.py 2 Dec 2002 06:06:48 -0000 1.68 *************** *** 248,252 **** self.year) - class timedelta(object): """Represent the difference between two datetime objects. --- 248,251 ---- *************** *** 468,471 **** --- 467,476 ---- def __hash__(self): return hash((self.__days, self.__seconds, self.__microseconds)) + + def __getstate__(self): + return (self.__days, self.__seconds, self.__microseconds) + + def __setstate__(self, tup): + self.__days, self.__seconds, self.__microseconds = tup class date(object): Index: obj_delta.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_delta.c,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** obj_delta.c 2 Dec 2002 00:57:04 -0000 1.13 --- obj_delta.c 2 Dec 2002 06:06:48 -0000 1.14 *************** *** 554,561 **** */ static PyObject * ! delta_getstate(PyDateTime_Delta *self, PyObject *args) { - if (!PyArg_ParseTuple(args, ":getstate")) - return NULL; return Py_BuildValue("lll", GET_TD_DAYS(self), GET_TD_SECONDS(self), --- 554,559 ---- */ static PyObject * ! delta_getstate(PyDateTime_Delta *self) { return Py_BuildValue("lll", GET_TD_DAYS(self), GET_TD_SECONDS(self), *************** *** 564,568 **** static PyObject * ! delta_setstate(PyDateTime_Delta *self, PyObject *args) { long day; --- 562,566 ---- static PyObject * ! delta_setstate(PyDateTime_Delta *self, PyObject *state) { long day; *************** *** 570,574 **** long us; ! if (!PyArg_ParseTuple(args, "lll", &day, &second, &us)) return NULL; --- 568,572 ---- long us; ! if (!PyArg_ParseTuple(state, "lll:__setstate__", &day, &second, &us)) return NULL; *************** *** 595,601 **** static PyMethodDef delta_methods[] = { ! {"__getstate__", (PyCFunction)delta_getstate, METH_VARARGS, PyDoc_STR("__getstate__() -> state")}, ! {"__setstate__", (PyCFunction)delta_setstate, METH_VARARGS, PyDoc_STR("__setstate__(state)")}, {NULL, NULL}, --- 593,599 ---- static PyMethodDef delta_methods[] = { ! {"__getstate__", (PyCFunction)delta_getstate, METH_NOARGS, PyDoc_STR("__getstate__() -> state")}, ! {"__setstate__", (PyCFunction)delta_setstate, METH_O, PyDoc_STR("__setstate__(state)")}, {NULL, NULL}, Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** test_both.py 1 Dec 2002 23:49:56 -0000 1.12 --- test_both.py 2 Dec 2002 06:06:48 -0000 1.13 *************** *** 129,132 **** --- 129,151 ---- self.assertEqual(len(d), 1) + def test_pickling(self): + import pickle, cPickle + args = 12, 34, 56 + orig = timedelta(*args) + state = orig.__getstate__() + self.assertEqual(args, state) + derived = timedelta() + derived.__setstate__(state) + self.assertEqual(orig, derived) + for pickler in pickle, cPickle: + for binary in 0, 1: + # XXX Pickling fails in the C implementation. + # XXX __getstate__ and __setstate__ are there, but the + # XXX pickler refuses to use them. I suspect it doesn't + # XXX know how to create "an empty" base object. + green = pickler.dumps(orig, binary) + derived = pickler.loads(green) + self.assertEqual(orig, derived) + ############################################################################# # date tests From tim_one@users.sourceforge.net Mon Dec 2 06:31:01 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sun, 01 Dec 2002 22:31:01 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.py,1.68,1.69 obj_date.c,1.11,1.12 test_both.py,1.13,1.14 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv317 Modified Files: datetime.py obj_date.c test_both.py Log Message: Added pickle support to the C and Python date implementations, + a test case. PROBLEM: as with timedelta before it, __setstate__/__getstate__ do the same things in both implementations, but pickling doesn't work for the C implementation. Index: datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.py,v retrieving revision 1.68 retrieving revision 1.69 diff -C2 -d -r1.68 -r1.69 *** datetime.py 2 Dec 2002 06:06:48 -0000 1.68 --- datetime.py 2 Dec 2002 06:30:59 -0000 1.69 *************** *** 696,699 **** --- 696,710 ---- return "%04d-%02d-%02d" % (self.__year, self.__month, self.__day) + # Pickle support. + + def __getstate__(self): + yhi, ylo = divmod(self.__year, 256) + return "%c%c%c%c" % (yhi, ylo, self.__month, self.__day) + + def __setstate__(self, string): + assert len(string) == 4 + yhi, ylo, self.__month, self.__day = map(ord, string) + self.__year = yhi * 256 + ylo + date.min = date(1, 1, 1) date.max = date(9999, 12, 31) Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** obj_date.c 1 Dec 2002 19:37:28 -0000 1.11 --- obj_date.c 2 Dec 2002 06:30:59 -0000 1.12 *************** *** 371,374 **** --- 371,403 ---- return PyInt_FromLong(dow); } + /* XXX Broken attempt to get pickles working. An attempt to pickle + * XXX craps out in + * XXX + * XXX if base is self.__class__: + * XXX raise TypeError, "can't pickle %s objects" % base.__name__ + * XXX + * XXX in Python's copy_reg.py. How to fix? + */ + static PyObject * + date_getstate(PyDateTime_Date *self) + { + return PyString_FromStringAndSize(self->data, + _PyDateTime_DATE_DATA_SIZE); + } + + static PyObject * + date_setstate(PyDateTime_Date *self, PyObject *state) + { + const int len = PyString_Size(state); + unsigned char *pdata = (unsigned char*)PyString_AsString(state); + + assert(len == _PyDateTime_DATE_DATA_SIZE); + + memcpy(self->data, pdata, _PyDateTime_DATE_DATA_SIZE); + self->hashcode = -1; + + Py_INCREF(Py_None); + return Py_None; + } static PyMethodDef date_methods[] = { *************** *** 398,402 **** "Return the day of the week represented by the date.\n" "Monday == 0 ... Sunday == 6"}, ! {NULL} }; --- 427,435 ---- "Return the day of the week represented by the date.\n" "Monday == 0 ... Sunday == 6"}, ! {"__getstate__", (PyCFunction)date_getstate, METH_NOARGS, ! PyDoc_STR("__getstate__() -> state")}, ! {"__setstate__", (PyCFunction)date_setstate, METH_O, ! PyDoc_STR("__setstate__(state)")}, ! {NULL, NULL} }; Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** test_both.py 2 Dec 2002 06:06:48 -0000 1.13 --- test_both.py 2 Dec 2002 06:30:59 -0000 1.14 *************** *** 402,405 **** --- 402,424 ---- self.assertEqual(t, (1956, 3, 1+i, 0, 0, 0, (3+i)%7, 61+i, -1)) + def test_pickling(self): + import pickle, cPickle + args = 6, 7, 23 + orig = self.theclass(*args) + state = orig.__getstate__() + self.assertEqual(state, '\x00\x06\x07\x17') + derived = self.theclass(1, 1, 1) + derived.__setstate__(state) + self.assertEqual(orig, derived) + for pickler in pickle, cPickle: + for binary in 0, 1: + # XXX Pickling fails in the C implementation. + # XXX __getstate__ and __setstate__ are there, but the + # XXX pickler refuses to use them. I suspect it doesn't + # XXX know how to create "an empty" base object. + green = pickler.dumps(orig, binary) + derived = pickler.loads(green) + self.assertEqual(orig, derived) + ############################################################################# # datetime tests *************** *** 596,599 **** --- 615,622 ---- self.assertRaises(TypeError, lambda: i+a) self.assertRaises(TypeError, lambda: i-a) + + def test_pickling(self): + import pickle, cPickle + pass def test_suite(): From tim_one@users.sourceforge.net Mon Dec 2 06:42:30 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sun, 01 Dec 2002 22:42:30 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.py,1.69,1.70 obj_date.c,1.12,1.13 obj_datetime.c,1.6,1.7 test_both.py,1.14,1.15 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv4335 Modified Files: datetime.py obj_date.c obj_datetime.c test_both.py Log Message: Added pickling to datetime objects. Again the C implementation doesn't work. Index: datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.py,v retrieving revision 1.69 retrieving revision 1.70 diff -C2 -d -r1.69 -r1.70 *** datetime.py 2 Dec 2002 06:30:59 -0000 1.69 --- datetime.py 2 Dec 2002 06:42:28 -0000 1.70 *************** *** 1238,1241 **** --- 1238,1256 ---- self.__microsecond) + # Pickle support. + + def __getstate__(self): + yhi, ylo = divmod(self.__year, 256) + us2, us3 = divmod(self.__microsecond, 256) + us1, us2 = divmod(us2, 256) + return ("%c" * 10) % (yhi, ylo, self.__month, self.__day, self.__hour, + self.__minute, self.__second, us1, us2, us3) + + def __setstate__(self, string): + assert len(string) == 10 + (yhi, ylo, self.__month, self.__day, self.__hour, + self.__minute, self.__second, us1, us2, us3) = map(ord, string) + self.__year = yhi * 256 + ylo + self.__microsecond = (((us1 << 8) | us2) << 8) | us3 datetime.min = datetime(1, 1, 1) Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** obj_date.c 2 Dec 2002 06:30:59 -0000 1.12 --- obj_date.c 2 Dec 2002 06:42:28 -0000 1.13 *************** *** 371,374 **** --- 371,375 ---- return PyInt_FromLong(dow); } + /* XXX Broken attempt to get pickles working. An attempt to pickle * XXX craps out in Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** obj_datetime.c 1 Dec 2002 19:37:28 -0000 1.6 --- obj_datetime.c 2 Dec 2002 06:42:28 -0000 1.7 *************** *** 372,375 **** --- 372,405 ---- } + /* XXX Broken attempt to get pickles working. An attempt to pickle + * XXX craps out in + * XXX + * XXX if base is self.__class__: + * XXX raise TypeError, "can't pickle %s objects" % base.__name__ + * XXX + * XXX in Python's copy_reg.py. How to fix? + */ + static PyObject * + datetime_getstate(PyDateTime_DateTime *self) + { + return PyString_FromStringAndSize(self->data, + _PyDateTime_DATETIME_DATA_SIZE); + } + + static PyObject * + datetime_setstate(PyDateTime_DateTime *self, PyObject *state) + { + const int len = PyString_Size(state); + unsigned char *pdata = (unsigned char*)PyString_AsString(state); + + assert(len == _PyDateTime_DATETIME_DATA_SIZE); + + memcpy(self->data, pdata, _PyDateTime_DATETIME_DATA_SIZE); + self->hashcode = -1; + + Py_INCREF(Py_None); + return Py_None; + } + static PyMethodDef datetime_methods[] = { /* Class methods: */ *************** *** 385,389 **** "Return the day of the week represented by the datetime.\n" "Monday == 1 ... Sunday == 7"}, ! {NULL} }; --- 415,423 ---- "Return the day of the week represented by the datetime.\n" "Monday == 1 ... Sunday == 7"}, ! {"__getstate__", (PyCFunction)datetime_getstate, METH_NOARGS, ! PyDoc_STR("__getstate__() -> state")}, ! {"__setstate__", (PyCFunction)datetime_setstate, METH_O, ! PyDoc_STR("__setstate__(state)")}, ! {NULL, NULL} }; Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.14 retrieving revision 1.15 diff -C2 -d -r1.14 -r1.15 *** test_both.py 2 Dec 2002 06:30:59 -0000 1.14 --- test_both.py 2 Dec 2002 06:42:28 -0000 1.15 *************** *** 618,622 **** def test_pickling(self): import pickle, cPickle ! pass def test_suite(): --- 618,637 ---- def test_pickling(self): import pickle, cPickle ! args = 6, 7, 23, 20, 59, 1, 64**2 ! orig = self.theclass(*args) ! state = orig.__getstate__() ! self.assertEqual(state, '\x00\x06\x07\x17\x14\x3b\x01\x00\x10\x00') ! derived = self.theclass(1, 1, 1) ! derived.__setstate__(state) ! self.assertEqual(orig, derived) ! for pickler in pickle, cPickle: ! for binary in 0, 1: ! # XXX Pickling fails in the C implementation. ! # XXX __getstate__ and __setstate__ are there, but the ! # XXX pickler refuses to use them. I suspect it doesn't ! # XXX know how to create "an empty" base object. ! green = pickler.dumps(orig, binary) ! derived = pickler.loads(green) ! self.assertEqual(orig, derived) def test_suite(): From guido@python.org Mon Dec 2 09:18:54 2002 From: guido@python.org (Guido van Rossum) Date: Mon, 02 Dec 2002 04:18:54 -0500 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.c,1.29,1.30 obj_delta.c,1.8,1.9 test_both.py,1.11,1.12 In-Reply-To: Your message of "Sun, 01 Dec 2002 15:49:59 PST." References: Message-ID: <200212020918.gB29Isv24477@pcp02138704pcs.reston01.va.comcast.net> > PROBLEM: Noted that timedelta comparison doesn't work as intended. I > assume the same is true for all comparisons defined here. I don't know > whether this is a bug in Python (current CVS), or a bug here, so don't > know how to fix it. For example, cmp(timedelta(whatever), 42) ends up > comparing the type names of the objects, despite that timedelta's > tp_compare function is trying its darnedest to raise TypeError then. > Turns out the tp_compare function isn't called unless both objects are > timedeltas. I seem to recall that using tp_richcompare doesn't have this problem. --Guido van Rossum (home page: http://www.python.org/~guido/) From guido@python.org Mon Dec 2 09:20:53 2002 From: guido@python.org (Guido van Rossum) Date: Mon, 02 Dec 2002 04:20:53 -0500 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_delta.c,1.9,1.10 In-Reply-To: Your message of "Sun, 01 Dec 2002 16:32:24 PST." References: Message-ID: <200212020920.gB29Krw24489@pcp02138704pcs.reston01.va.comcast.net> > PROBLEM: This was intended to support pickling, but doesn't work for > that purpose (see the XXX comments). Turns out I have no idea how to > pickle a new-style instance of a type coded in C (it's easy if coded in > Python). Try defining __reduce__. --Guido van Rossum (home page: http://www.python.org/~guido/) From gvanrossum@users.sourceforge.net Mon Dec 2 09:56:23 2002 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Mon, 02 Dec 2002 01:56:23 -0800 Subject: [Python-checkins] python/dist/src/Lib/test regrtest.py,1.107,1.108 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv6867 Modified Files: regrtest.py Log Message: On Max OSX, try increasing the stack limit to 2048 so test_re and test_sre won't die with a SegFault. Index: regrtest.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/regrtest.py,v retrieving revision 1.107 retrieving revision 1.108 diff -C2 -d -r1.107 -r1.108 *** regrtest.py 26 Nov 2002 21:40:59 -0000 1.107 --- regrtest.py 2 Dec 2002 09:56:21 -0000 1.108 *************** *** 84,87 **** --- 84,103 ---- "") + # MacOSX (a.k.a. Darwin) has a default stack size that is too small + # for deeply recursive regular expressions. We see this as crashes in + # the Python test suite when running test_re.py and test_sre.py. The + # fix is to set the stack limit to 2048. + # This approach may also be useful for other Unixy platforms that + # suffer from small default stack limits. + if sys.platform == 'darwin': + try: + import resource + except ImportError: + pass + else: + soft, hard = resource.getrlimit(resource.RLIMIT_STACK) + newsoft = min(hard, max(soft, 1024*2048)) + resource.setrlimit(resource.RLIMIT_STACK, (newsoft, hard)) + from test import test_support From gvanrossum@users.sourceforge.net Mon Dec 2 10:42:33 2002 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Mon, 02 Dec 2002 02:42:33 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_largefile.py,1.15,1.16 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv28413 Modified Files: test_largefile.py Log Message: Require 'largefile' resource for Mac OSX as well. Index: test_largefile.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_largefile.py,v retrieving revision 1.15 retrieving revision 1.16 diff -C2 -d -r1.15 -r1.16 *** test_largefile.py 23 Jul 2002 19:03:55 -0000 1.15 --- test_largefile.py 2 Dec 2002 10:42:30 -0000 1.16 *************** *** 24,32 **** ! # On Windows this test comsumes large resources; It takes a long time to build ! # the >2GB file and takes >2GB of disk space therefore the resource must be ! # enabled to run this test. If not, nothing after this line stanza will be ! # executed. ! if sys.platform[:3] == 'win': test_support.requires( 'largefile', --- 24,32 ---- ! # On Windows and Mac OSX this test comsumes large resources; It takes ! # a long time to build the >2GB file and takes >2GB of disk space ! # therefore the resource must be enabled to run this test. If not, ! # nothing after this line stanza will be executed. ! if sys.platform[:3] == 'win' or sys.platform == 'darwin': test_support.requires( 'largefile', From gvanrossum@users.sourceforge.net Mon Dec 2 13:08:56 2002 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Mon, 02 Dec 2002 05:08:56 -0800 Subject: [Python-checkins] python/dist/src/Lib cmd.py,1.31,1.32 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv15033 Modified Files: cmd.py Log Message: Add a better columnizer to print_topics(). Index: cmd.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/cmd.py,v retrieving revision 1.31 retrieving revision 1.32 diff -C2 -d -r1.31 -r1.32 *** cmd.py 30 Jun 2002 03:39:14 -0000 1.31 --- cmd.py 2 Dec 2002 13:08:53 -0000 1.32 *************** *** 320,328 **** if self.ruler: print self.ruler * len(header) ! (cmds_per_line,junk)=divmod(maxcol,cmdlen) ! col=cmds_per_line ! for cmd in cmds: ! if col==0: print ! print (("%-"+`cmdlen`+"s") % cmd), ! col = (col+1) % cmds_per_line ! print "\n" --- 320,379 ---- if self.ruler: print self.ruler * len(header) ! self.columnize(cmds, maxcol-1) ! print ! ! def columnize(self, list, displaywidth=80): ! """Display a list of strings as a compact set of columns. ! ! Each column is only as wide as necessary. ! Columns are separated by two spaces (one was not legible enough). ! """ ! if not list: ! print "" ! return ! nonstrings = [i for i in range(len(list)) ! if not isinstance(list[i], str)] ! if nonstrings: ! raise TypeError, ("list[i] not a string for i in %s" % ! ", ".join(map(str, nonstrings))) ! size = len(list) ! if size == 1: ! print list[0] ! return ! # Try every row count from 1 upwards ! for nrows in range(1, len(list)): ! ncols = (size+nrows-1) // nrows ! colwidths = [] ! totwidth = -2 ! for col in range(ncols): ! colwidth = 0 ! for row in range(nrows): ! i = row + nrows*col ! if i >= size: ! break ! x = list[i] ! colwidth = max(colwidth, len(x)) ! colwidths.append(colwidth) ! totwidth += colwidth + 2 ! if totwidth > displaywidth: ! break ! if totwidth <= displaywidth: ! break ! else: ! nrows = len(list) ! ncols = 1 ! colwidths = [0] ! for row in range(nrows): ! texts = [] ! for col in range(ncols): ! i = row + nrows*col ! if i >= size: ! x = "" ! else: ! x = list[i] ! texts.append(x) ! while texts and not texts[-1]: ! del texts[-1] ! for col in range(len(texts)): ! texts[col] = texts[col].ljust(colwidths[col]) ! print " ".join(texts) From gvanrossum@users.sourceforge.net Mon Dec 2 14:54:22 2002 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Mon, 02 Dec 2002 06:54:22 -0800 Subject: [Python-checkins] python/dist/src/Lib pyclbr.py,1.28,1.29 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv3774 Modified Files: pyclbr.py Log Message: Moderately heavy reorganization of pyclbr to fix package-related bugs. - The _modules cache now uses the full module name. - The meaning of the (internal!!!) inpackage argument is changed: it now is the parent package name, or None. readmodule() doesn't support this argument any more. - The meaning of the path argument is changed: when inpackage is set, the module *must* be found in this path (as is the case for the real package search). - Miscellaneous cleanup, e.g. fixed __all__, changed some comments and doc strings, etc. - Adapted the unit tests to the new semantics (nothing much changed, really). Added some debugging code to the unit tests that print helpful extra info to stderr when a test fails (interpreting the test failures turned out to be hard without these). Index: pyclbr.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/pyclbr.py,v retrieving revision 1.28 retrieving revision 1.29 diff -C2 -d -r1.28 -r1.29 *** pyclbr.py 16 Sep 2002 16:36:02 -0000 1.28 --- pyclbr.py 2 Dec 2002 14:54:19 -0000 1.29 *************** *** 17,20 **** --- 17,21 ---- A class is described by the class Class in this module. Instances of this class have the following instance variables: + module -- the module name name -- the name of the class super -- a list of super classes (Class instances) *************** *** 30,51 **** shouldn't happen often. ! XXX describe the Function class. BUGS - Nested classes and functions can confuse it. ! PACKAGE RELATED BUGS ! - If you have a package and a module inside that or another package ! with the same name, module caching doesn't work properly since the ! key is the base name of the module/package. ! - The only entry that is returned when you readmodule a package is a ! __path__ whose value is a list which confuses certain class browsers. ! - When code does: ! from package import subpackage ! class MyClass(subpackage.SuperClass): ! ... ! It can't locate the parent. It probably needs to have the same ! hairy logic that the import locator already does. (This logic ! exists coded in Python in the freeze package.) """ --- 31,49 ---- shouldn't happen often. ! A function is described by the class Function in this module. ! Instances of this class have the following instance variables: ! module -- the module name ! name -- the name of the class ! file -- the file in which the class was defined ! lineno -- the line in the file on which the class statement occurred ! BUGS - Nested classes and functions can confuse it. ! PACKAGE CAVEAT ! - When you call readmodule_ex for a package, dict['__path__'] is a ! list, which may confuse older class browsers. (readmodule filters ! these out though.) """ *************** *** 55,59 **** from token import NAME ! __all__ = ["readmodule"] _modules = {} # cache of modules we've seen --- 53,57 ---- from token import NAME ! __all__ = ["readmodule", "readmodule_ex", "Class", "Function"] _modules = {} # cache of modules we've seen *************** *** 75,148 **** self.methods[name] = lineno ! class Function(Class): '''Class to represent a top-level Python function''' def __init__(self, module, name, file, lineno): ! Class.__init__(self, module, name, None, file, lineno) ! def _addmethod(self, name, lineno): ! assert 0, "Function._addmethod() shouldn't be called" ! def readmodule(module, path=[], inpackage=False): '''Backwards compatible interface. ! Like readmodule_ex() but strips Function objects from the resulting dictionary.''' ! dict = readmodule_ex(module, path, inpackage) res = {} for key, value in dict.items(): ! if not isinstance(value, Function): res[key] = value return res ! def readmodule_ex(module, path=[], inpackage=False): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class ! found in the module.''' dict = {} i = module.rfind('.') if i >= 0: ! # Dotted module name ! package = module[:i].strip() ! submodule = module[i+1:].strip() parent = readmodule_ex(package, path, inpackage) ! child = readmodule_ex(submodule, parent['__path__'], True) ! return child ! ! if module in _modules: ! # we've seen this module before... ! return _modules[module] ! if module in sys.builtin_module_names: ! # this is a built-in module ! _modules[module] = dict ! return dict ! # search the path for the module f = None if inpackage: ! try: ! f, file, (suff, mode, type) = \ ! imp.find_module(module, path) ! except ImportError: ! f = None ! if f is None: ! fullpath = list(path) + sys.path ! f, file, (suff, mode, type) = imp.find_module(module, fullpath) if type == imp.PKG_DIRECTORY: dict['__path__'] = [file] - _modules[module] = dict path = [file] + path ! f, file, (suff, mode, type) = \ ! imp.find_module('__init__', [file]) if type != imp.PY_SOURCE: # not Python source, can't do anything with this module f.close() - _modules[module] = dict return dict - _modules[module] = dict classstack = [] # stack of (class, indent) pairs --- 73,154 ---- self.methods[name] = lineno ! class Function: '''Class to represent a top-level Python function''' def __init__(self, module, name, file, lineno): ! self.module = module ! self.name = name ! self.file = file ! self.lineno = lineno ! def readmodule(module, path=[]): '''Backwards compatible interface. ! Call readmodule_ex() and then only keep Class objects from the resulting dictionary.''' ! dict = readmodule_ex(module, path) res = {} for key, value in dict.items(): ! if isinstance(value, Class): res[key] = value return res ! def readmodule_ex(module, path=[], inpackage=None): '''Read a module file and return a dictionary of classes. Search for MODULE in PATH and sys.path, read and parse the module and return a dictionary with one entry for each class ! found in the module. ! ! If INPACKAGE is true, it must be the dotted name of the package in ! which we are searching for a submodule, and then PATH must be the ! package search path; otherwise, we are searching for a top-level ! module, and PATH is combined with sys.path. ! ''' ! ! # Compute the full module name (prepending inpackage if set) ! if inpackage: ! fullmodule = "%s.%s" % (inpackage, module) ! else: ! fullmodule = module ! ! # Check in the cache ! if fullmodule in _modules: ! return _modules[fullmodule] + # Initialize the dict for this module's contents dict = {} + # Check if it is a built-in module; we don't do much for these + if module in sys.builtin_module_names and not inpackage: + _modules[module] = dict + return dict + + # Check for a dotted module name i = module.rfind('.') if i >= 0: ! package = module[:i] ! submodule = module[i+1:] parent = readmodule_ex(package, path, inpackage) ! if inpackage: ! package = "%s.%s" % (inpackage, package) ! return readmodule_ex(submodule, parent['__path__'], package) ! # Search the path for the module f = None if inpackage: ! f, file, (suff, mode, type) = imp.find_module(module, path) ! else: ! f, file, (suff, mode, type) = imp.find_module(module, path + sys.path) if type == imp.PKG_DIRECTORY: dict['__path__'] = [file] path = [file] + path ! f, file, (suff, mode, type) = imp.find_module('__init__', [file]) ! _modules[fullmodule] = dict if type != imp.PY_SOURCE: # not Python source, can't do anything with this module f.close() return dict classstack = [] # stack of (class, indent) pairs *************** *** 222,226 **** try: # Recursively read the imported module ! readmodule_ex(mod, path, inpackage) except: # If we can't find or parse the imported module, --- 228,238 ---- try: # Recursively read the imported module ! if not inpackage: ! readmodule_ex(mod, path) ! else: ! try: ! readmodule_ex(mod, path, inpackage) ! except ImportError: ! readmodule_ex(mod) except: # If we can't find or parse the imported module, From gvanrossum@users.sourceforge.net Mon Dec 2 14:54:23 2002 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Mon, 02 Dec 2002 06:54:23 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_pyclbr.py,1.12,1.13 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv3774/test Modified Files: test_pyclbr.py Log Message: Moderately heavy reorganization of pyclbr to fix package-related bugs. - The _modules cache now uses the full module name. - The meaning of the (internal!!!) inpackage argument is changed: it now is the parent package name, or None. readmodule() doesn't support this argument any more. - The meaning of the path argument is changed: when inpackage is set, the module *must* be found in this path (as is the case for the real package search). - Miscellaneous cleanup, e.g. fixed __all__, changed some comments and doc strings, etc. - Adapted the unit tests to the new semantics (nothing much changed, really). Added some debugging code to the unit tests that print helpful extra info to stderr when a test fails (interpreting the test failures turned out to be hard without these). Index: test_pyclbr.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_pyclbr.py,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** test_pyclbr.py 23 Jul 2002 19:03:59 -0000 1.12 --- test_pyclbr.py 2 Dec 2002 14:54:20 -0000 1.13 *************** *** 7,10 **** --- 7,11 ---- from types import ClassType, FunctionType, MethodType import pyclbr + from unittest import TestCase # This next line triggers an error on old versions of pyclbr. *************** *** 19,32 **** # members to ignore. ! class PyclbrTest(unittest.TestCase): def assertListEq(self, l1, l2, ignore): ''' succeed iff {l1} - {ignore} == {l2} - {ignore} ''' ! for p1, p2 in (l1, l2), (l2, l1): ! for item in p1: ! ok = (item in p2) or (item in ignore) ! if not ok: ! self.fail("%r missing" % item) ! def assertHasattr(self, obj, attr, ignore): --- 20,36 ---- # members to ignore. ! class PyclbrTest(TestCase): def assertListEq(self, l1, l2, ignore): ''' succeed iff {l1} - {ignore} == {l2} - {ignore} ''' ! try: ! for p1, p2 in (l1, l2), (l2, l1): ! for item in p1: ! ok = (item in p2) or (item in ignore) ! if not ok: ! self.fail("%r missing" % item) ! except: ! print >>sys.stderr, "l1=%r, l2=%r, ignore=%r" % (l1, l2, ignore) ! raise def assertHasattr(self, obj, attr, ignore): *************** *** 41,45 **** ''' succeed iff obj.has_key(key) or key in ignore. ''' if key in ignore: return ! if not obj.has_key(key): print "***",key self.failUnless(obj.has_key(key)) --- 45,50 ---- ''' succeed iff obj.has_key(key) or key in ignore. ''' if key in ignore: return ! if not obj.has_key(key): ! print >>sys.stderr, "***",key self.failUnless(obj.has_key(key)) *************** *** 57,61 **** if module == None: ! module = __import__(moduleName, globals(), {}, []) dict = pyclbr.readmodule_ex(moduleName) --- 62,68 ---- if module == None: ! # Import it. ! # ('' is to work around an API silliness in __import__) ! module = __import__(moduleName, globals(), {}, ['']) dict = pyclbr.readmodule_ex(moduleName) *************** *** 75,79 **** for base in value.super ] ! self.assertListEq(real_bases, pyclbr_bases, ignore) actualMethods = [] --- 82,90 ---- for base in value.super ] ! try: ! self.assertListEq(real_bases, pyclbr_bases, ignore) ! except: ! print >>sys.stderr, "class=%s" % py_item ! raise actualMethods = [] *************** *** 95,102 **** # Now check for missing stuff. for name in dir(module): item = getattr(module, name) ! if type(item) in (ClassType, FunctionType): ! self.assertHaskey(dict, name, ignore) def test_easy(self): --- 106,120 ---- # Now check for missing stuff. + def defined_in(item, module): + if isinstance(item, ClassType): + return item.__module__ == module.__name__ + if isinstance(item, FunctionType): + return item.func_globals is module.__dict__ + return False for name in dir(module): item = getattr(module, name) ! if isinstance(item, (ClassType, FunctionType)): ! if defined_in(item, module): ! self.assertHaskey(dict, name, ignore) def test_easy(self): *************** *** 137,142 **** )) ! cm('test.test_pyclbr', ! module=sys.modules[__name__]) # pydoc doesn't work because of string issues --- 155,162 ---- )) ! # Tests for modules inside packages ! cm('email.Parser') ! ! cm('test.test_pyclbr', ignore=('defined_in',)) # pydoc doesn't work because of string issues From gvanrossum@users.sourceforge.net Mon Dec 2 15:49:15 2002 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Mon, 02 Dec 2002 07:49:15 -0800 Subject: [Python-checkins] python/dist/src README,1.158,1.159 Message-ID: Update of /cvsroot/python/python/dist/src In directory sc8-pr-cvs1:/tmp/cvs-serv10910 Modified Files: README Log Message: Add XXX note about Sleepycat's BSDDB. Index: README =================================================================== RCS file: /cvsroot/python/python/dist/src/README,v retrieving revision 1.158 retrieving revision 1.159 diff -C2 -d -r1.158 -r1.159 *** README 15 Nov 2002 07:28:05 -0000 1.158 --- README 2 Dec 2002 15:49:13 -0000 1.159 *************** *** 571,574 **** --- 571,577 ---- ------------------------------------- + XXX Shouldn't this section be rewritten now that we use Sleepycat's + BSDDB 4.0? + Configuring the bsddb module can sometimes be a bit tricky. This module provides a Python interface to the Berkeley DB library. As of this writing From gvanrossum@users.sourceforge.net Mon Dec 2 16:08:57 2002 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Mon, 02 Dec 2002 08:08:57 -0800 Subject: [Python-checkins] python/dist/src/Lib/bsddb dbutils.py,1.3,1.4 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/bsddb In directory sc8-pr-cvs1:/tmp/cvs-serv27206 Modified Files: dbutils.py Log Message: Fix typo in except clause (_db should be _bsddb). Index: dbutils.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/bsddb/dbutils.py,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** dbutils.py 24 Nov 2002 02:35:34 -0000 1.3 --- dbutils.py 2 Dec 2002 16:08:54 -0000 1.4 *************** *** 59,63 **** try: return apply(function, _args, _kwargs) ! except _db.DBLockDeadlockError: if _deadlock_VerboseFile: _deadlock_VerboseFile.write('dbutils.DeadlockWrap: sleeping %1.3f\n' % sleeptime) --- 59,63 ---- try: return apply(function, _args, _kwargs) ! except _bsddb.DBLockDeadlockError: if _deadlock_VerboseFile: _deadlock_VerboseFile.write('dbutils.DeadlockWrap: sleeping %1.3f\n' % sleeptime) From gvanrossum@users.sourceforge.net Mon Dec 2 16:17:49 2002 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Mon, 02 Dec 2002 08:17:49 -0800 Subject: [Python-checkins] python/dist/src/Lib/bsddb dbtables.py,1.4,1.5 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/bsddb In directory sc8-pr-cvs1:/tmp/cvs-serv7202 Modified Files: dbtables.py Log Message: In class bsdTableDB, add class variables db and env (set to None) to prevent close() called from __del__ from bombing out when __init__() fails early. Index: dbtables.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/bsddb/dbtables.py,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** dbtables.py 24 Nov 2002 02:35:34 -0000 1.4 --- dbtables.py 2 Dec 2002 16:17:46 -0000 1.5 *************** *** 114,117 **** --- 114,122 ---- class bsdTableDB : + + # Save close() from bombing out if __init__() failed + db = None + env = None + def __init__(self, filename, dbhome, create=0, truncate=0, mode=0600, recover=0, dbflags=0) : """bsdTableDB.open(filename, dbhome, create=0, truncate=0, mode=0600) From tim_one@users.sourceforge.net Mon Dec 2 17:31:39 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 02 Dec 2002 09:31:39 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_delta.c,1.14,1.15 test_both.py,1.15,1.16 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv14756 Modified Files: obj_delta.c test_both.py Log Message: Another broken attempt to get pickling of timedelta objects to work. Index: obj_delta.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_delta.c,v retrieving revision 1.14 retrieving revision 1.15 diff -C2 -d -r1.14 -r1.15 *** obj_delta.c 2 Dec 2002 06:06:48 -0000 1.14 --- obj_delta.c 2 Dec 2002 17:31:21 -0000 1.15 *************** *** 580,583 **** --- 580,609 ---- } + /* XXX A further broken attempt to get pickling to work. + * XXX This avoids the problem above, but dies instead with + * XXX PicklingError: Can't pickle : it's not + * XXX found as __builtin__.tmedelta + */ + static PyObject * + delta_reduce(PyDateTime_Delta* self) + { + PyObject* result = NULL; + PyObject* state; + + state = delta_getstate(self); + if (state != NULL) { + PyObject *emptytuple = PyTuple_New(0); + if (emptytuple != NULL) { + result = Py_BuildValue("OOO", + self->ob_type, + emptytuple, + state); + Py_DECREF(emptytuple); + } + Py_DECREF(state); + } + return result; + } + #define OFFSET(field) offsetof(PyDateTime_Delta, field) *************** *** 588,600 **** PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")}, {"microseconds", T_LONG, OFFSET(microseconds), READONLY, ! PyDoc_STR("Number of microseconds (>= and less than 1 second).")}, {NULL} }; static PyMethodDef delta_methods[] = { - {"__getstate__", (PyCFunction)delta_getstate, METH_NOARGS, - PyDoc_STR("__getstate__() -> state")}, {"__setstate__", (PyCFunction)delta_setstate, METH_O, PyDoc_STR("__setstate__(state)")}, {NULL, NULL}, }; --- 614,628 ---- PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")}, {"microseconds", T_LONG, OFFSET(microseconds), READONLY, ! PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")}, {NULL} }; static PyMethodDef delta_methods[] = { {"__setstate__", (PyCFunction)delta_setstate, METH_O, PyDoc_STR("__setstate__(state)")}, + {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS, + NULL}, + {"__getstate__", (PyCFunction)delta_getstate, METH_NOARGS, + PyDoc_STR("__getstate__() -> state")}, {NULL, NULL}, }; Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.15 retrieving revision 1.16 diff -C2 -d -r1.15 -r1.16 *** test_both.py 2 Dec 2002 06:42:28 -0000 1.15 --- test_both.py 2 Dec 2002 17:31:25 -0000 1.16 *************** *** 141,147 **** for binary in 0, 1: # XXX Pickling fails in the C implementation. ! # XXX __getstate__ and __setstate__ are there, but the ! # XXX pickler refuses to use them. I suspect it doesn't ! # XXX know how to create "an empty" base object. green = pickler.dumps(orig, binary) derived = pickler.loads(green) --- 141,152 ---- for binary in 0, 1: # XXX Pickling fails in the C implementation. ! # XXX timedelta has a __reduce__ method, which returns, e.g., ! # XXX ! # XXX (, (), (1, 0, 0)) ! # XXX ! # XXX but pickle then complains ! # XXX ! # XXX PicklingError: Can't pickle : ! # XXX it's not found as __builtin__.timedelta green = pickler.dumps(orig, binary) derived = pickler.loads(green) From tim_one@users.sourceforge.net Mon Dec 2 18:10:39 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 02 Dec 2002 10:10:39 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.c,1.31,1.32 obj_delta.c,1.15,1.16 test_both.py,1.16,1.17 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv21999 Modified Files: datetime.c obj_delta.c test_both.py Log Message: Pickling for the C timedelta implementation finally works. Index: datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.c,v retrieving revision 1.31 retrieving revision 1.32 diff -C2 -d -r1.31 -r1.32 *** datetime.c 2 Dec 2002 00:57:04 -0000 1.31 --- datetime.c 2 Dec 2002 18:10:32 -0000 1.32 *************** *** 545,548 **** --- 545,552 ---- PyObject *m; PyObject *d, *dt; + PyObject *safepickle = PyString_FromString("__safe_for_unpickling__"); + + if (safepickle == NULL) + return; if (PyType_Ready(&PyDateTime_DateType) < 0) *************** *** 553,566 **** --- 557,581 ---- return; + /* timedelta values */ + d = PyDateTime_DeltaType.tp_dict; + if (PyDict_SetItem(d, safepickle, Py_True) < 0) + return; + /* date values */ d = PyDateTime_DateType.tp_dict; + Py_INCREF(Py_True); + if (PyDict_SetItem(d, safepickle, Py_True) < 0) + return; + dt = new_date(1, 1, 1); if (dt == NULL || PyDict_SetItemString(d, "min", dt) < 0) return; Py_DECREF(dt); + dt = new_date(MAXYEAR, 12, 31); if (dt == NULL || PyDict_SetItemString(d, "max", dt) < 0) return; Py_DECREF(dt); + dt = new_delta(1, 0, 0); if (dt == NULL || PyDict_SetItemString(d, "resolution", dt) < 0) *************** *** 568,585 **** Py_DECREF(dt); ! /* date/time values */ d = PyDateTime_DateTimeType.tp_dict; dt = new_datetime(1, 1, 1, 0, 0, 0, 0); if (dt == NULL || PyDict_SetItemString(d, "min", dt) < 0) return; Py_DECREF(dt); dt = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999); if (dt == NULL || PyDict_SetItemString(d, "max", dt) < 0) return; Py_DECREF(dt); dt = new_delta(0, 0, 1); if (dt == NULL || PyDict_SetItemString(d, "resolution", dt) < 0) return; Py_DECREF(dt); /* module initialization */ --- 583,607 ---- Py_DECREF(dt); ! /* datetime values */ d = PyDateTime_DateTimeType.tp_dict; + if (PyDict_SetItem(d, safepickle, Py_True) < 0) + return; + dt = new_datetime(1, 1, 1, 0, 0, 0, 0); if (dt == NULL || PyDict_SetItemString(d, "min", dt) < 0) return; Py_DECREF(dt); + dt = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999); if (dt == NULL || PyDict_SetItemString(d, "max", dt) < 0) return; Py_DECREF(dt); + dt = new_delta(0, 0, 1); if (dt == NULL || PyDict_SetItemString(d, "resolution", dt) < 0) return; Py_DECREF(dt); + + Py_DECREF(safepickle); /* module initialization */ Index: obj_delta.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_delta.c,v retrieving revision 1.15 retrieving revision 1.16 diff -C2 -d -r1.15 -r1.16 *** obj_delta.c 2 Dec 2002 17:31:21 -0000 1.15 --- obj_delta.c 2 Dec 2002 18:10:33 -0000 1.16 *************** *** 545,555 **** } ! /* XXX Broken attempt to get pickles working. An attempt to pickle ! * XXX craps out in ! * XXX ! * XXX if base is self.__class__: ! * XXX raise TypeError, "can't pickle %s objects" % base.__name__ ! * XXX ! * XXX in Python's copy_reg.py. How to fix? */ static PyObject * --- 545,551 ---- } ! /* Pickle support. Quite a maze! While __getstate__/__setstate__ sufficed ! * in the Python implementation, the C implementation also requires ! * __reduce__, and a __safe_for_unpickling__ attr in the type object. */ static PyObject * *************** *** 580,588 **** } - /* XXX A further broken attempt to get pickling to work. - * XXX This avoids the problem above, but dies instead with - * XXX PicklingError: Can't pickle : it's not - * XXX found as __builtin__.tmedelta - */ static PyObject * delta_reduce(PyDateTime_Delta* self) --- 576,579 ---- *************** *** 674,678 **** PyObject_HEAD_INIT(NULL) 0, /* ob_size */ ! "timedelta", /* tp_name */ sizeof(PyDateTime_Delta), /* tp_basicsize */ 0, /* tp_itemsize */ --- 665,670 ---- PyObject_HEAD_INIT(NULL) 0, /* ob_size */ ! /* XXX When this module is renamed to datetime, change tp_name. */ ! "_datetime.timedelta", /* tp_name */ sizeof(PyDateTime_Delta), /* tp_basicsize */ 0, /* tp_itemsize */ Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.16 retrieving revision 1.17 diff -C2 -d -r1.16 -r1.17 *** test_both.py 2 Dec 2002 17:31:25 -0000 1.16 --- test_both.py 2 Dec 2002 18:10:34 -0000 1.17 *************** *** 140,152 **** for pickler in pickle, cPickle: for binary in 0, 1: - # XXX Pickling fails in the C implementation. - # XXX timedelta has a __reduce__ method, which returns, e.g., - # XXX - # XXX (, (), (1, 0, 0)) - # XXX - # XXX but pickle then complains - # XXX - # XXX PicklingError: Can't pickle : - # XXX it's not found as __builtin__.timedelta green = pickler.dumps(orig, binary) derived = pickler.loads(green) --- 140,143 ---- *************** *** 419,425 **** for binary in 0, 1: # XXX Pickling fails in the C implementation. ! # XXX __getstate__ and __setstate__ are there, but the ! # XXX pickler refuses to use them. I suspect it doesn't ! # XXX know how to create "an empty" base object. green = pickler.dumps(orig, binary) derived = pickler.loads(green) --- 410,414 ---- for binary in 0, 1: # XXX Pickling fails in the C implementation. ! # XXX Needs to be fixed as for timedelta. green = pickler.dumps(orig, binary) derived = pickler.loads(green) *************** *** 633,639 **** for binary in 0, 1: # XXX Pickling fails in the C implementation. ! # XXX __getstate__ and __setstate__ are there, but the ! # XXX pickler refuses to use them. I suspect it doesn't ! # XXX know how to create "an empty" base object. green = pickler.dumps(orig, binary) derived = pickler.loads(green) --- 622,626 ---- for binary in 0, 1: # XXX Pickling fails in the C implementation. ! # XXX Needs to be fixed as for timedelta. green = pickler.dumps(orig, binary) derived = pickler.loads(green) From tim.one@comcast.net Mon Dec 2 18:10:56 2002 From: tim.one@comcast.net (Tim Peters) Date: Mon, 02 Dec 2002 13:10:56 -0500 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_delta.c,1.9,1.10 In-Reply-To: <200212020920.gB29Krw24489@pcp02138704pcs.reston01.va.comcast.net> Message-ID: [Guido] > Try defining __reduce__. OK ... but no joy: # XXX Pickling fails in the C implementation. # XXX timedelta has a __reduce__ method, which returns, e.g., # XXX # XXX (, (), (1, 0, 0)) # XXX # XXX but pickle then complains # XXX # XXX PicklingError: Can't pickle : # XXX it's not found as __builtin__.timedelta In one way that's not a mystery: >>> timedelta.__module__ '__builtin__' >>> timedelta.__name__ 'timedelta' >>> OK, if I change the name of the type to "_datetime.timedelta", pickling completes, but on unpicking a new error pops up: UnpicklingError: is not safe for unpickling Arghghghgh ... OK, if I also give the type dict a __safe_for_unpickling__ attr, I guess it works. From barry@python.org Mon Dec 2 18:23:34 2002 From: barry@python.org (Barry A. Warsaw) Date: Mon, 2 Dec 2002 13:23:34 -0500 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_delta.c,1.9,1.10 References: <200212020920.gB29Krw24489@pcp02138704pcs.reston01.va.comcast.net> Message-ID: <15851.42278.959840.140472@gargle.gargle.HOWL> >>>>> "TP" == Tim Peters writes: TP> Arghghghgh ... OK, if I also give the type dict a TP> __safe_for_unpickling__ attr, I guess it works. Read it and weep: http://www.python.org/doc/current/lib/node65.html -Barry From tim.one@comcast.net Mon Dec 2 18:46:59 2002 From: tim.one@comcast.net (Tim Peters) Date: Mon, 02 Dec 2002 13:46:59 -0500 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_delta.c,1.9,1.10 In-Reply-To: <15851.42278.959840.140472@gargle.gargle.HOWL> Message-ID: > TP> Arghghghgh ... OK, if I also give the type dict a > TP> __safe_for_unpickling__ attr, I guess it works. [Barry] > Read it and weep: > > http://www.python.org/doc/current/lib/node65.html Ya, I did. The part that threw me was: A callable object, which in the unpickling environment must be either a class, a callable registered as a ``safe constructor'' ^^^^^^^ (see below), or it must have an attribute __safe_for_unpickling__ with a true value. I figured timedelta *was* "a class", although now I guess that, in this context, it's not "a class" but "a type". That's what you get when you unify the concepts . remind-me-to-eat!-ly y'rs - tim From neal@metaslash.com Mon Dec 2 19:09:58 2002 From: neal@metaslash.com (Neal Norwitz) Date: Mon, 2 Dec 2002 14:09:58 -0500 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_delta.c,1.14,1.15 test_both.py,1.15,1.16 In-Reply-To: References: Message-ID: <20021202190958.GJ28552@epoch.metaslash.com> > + PyObject *emptytuple = PyTuple_New(0); > + if (emptytuple != NULL) { > + result = Py_BuildValue("OOO", > + self->ob_type, > + emptytuple, > + state); > + Py_DECREF(emptytuple); > + } > + Py_DECREF(state); What is the purpose of emptytuple here? Could/should this code be: result = Py_BuildValue(...); if (result != NULL) Py_DECREF(state); Neal From tim_one@users.sourceforge.net Mon Dec 2 19:40:45 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 02 Dec 2002 11:40:45 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.c,1.32,1.33 obj_date.c,1.13,1.14 obj_datetime.c,1.7,1.8 test_both.py,1.17,1.18 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv15411 Modified Files: datetime.c obj_date.c obj_datetime.c test_both.py Log Message: Pickling works now, but doesn't meet its primary design goal for date and datetime: since those types require 3 arguments, __reduce__ has to supply a 3-tuple of args for the constructor to chew on, which __setstate__ then immediately overwrites. So instead of having a pickle that's just a short string in these cases, we also get a pointless 3-tuple buried in the pickle. Perhaps doing this right requires defining Yet Another constructor function? I confess I'm not a pickling professional . Index: datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.c,v retrieving revision 1.32 retrieving revision 1.33 diff -C2 -d -r1.32 -r1.33 *** datetime.c 2 Dec 2002 18:10:32 -0000 1.32 --- datetime.c 2 Dec 2002 19:40:41 -0000 1.33 *************** *** 536,539 **** --- 536,541 ---- } + static PyObject* three_ones = NULL; /* an argument tuple for __reduce__ */ + #include "obj_delta.c" #include "obj_date.c" *************** *** 564,568 **** /* date values */ d = PyDateTime_DateType.tp_dict; - Py_INCREF(Py_True); if (PyDict_SetItem(d, safepickle, Py_True) < 0) return; --- 566,569 ---- *************** *** 652,654 **** --- 653,673 ---- us_per_week = PyLong_FromDouble(604800000000.0); + { + /* Build (1, 1, 1) so __reduce__ for date-like objects + * has something to pass to the type. + */ + int i; + PyObject *one = PyInt_FromLong(1); + + if (one == NULL) + return; + three_ones = PyTuple_New(3); + if (three_ones == NULL) + return; + for (i = 0; i < 3; ++i) { + Py_INCREF(one); + PyTuple_SetItem(three_ones, i, one); + } + Py_DECREF(one); + } } Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** obj_date.c 2 Dec 2002 06:42:28 -0000 1.13 --- obj_date.c 2 Dec 2002 19:40:42 -0000 1.14 *************** *** 372,382 **** } ! /* XXX Broken attempt to get pickles working. An attempt to pickle ! * XXX craps out in ! * XXX ! * XXX if base is self.__class__: ! * XXX raise TypeError, "can't pickle %s objects" % base.__name__ ! * XXX ! * XXX in Python's copy_reg.py. How to fix? */ static PyObject * --- 372,378 ---- } ! /* Pickle support. Quite a maze! While __getstate__/__setstate__ sufficed ! * in the Python implementation, the C implementation also requires ! * __reduce__, and a __safe_for_unpickling__ attr in the type object. */ static PyObject * *************** *** 402,405 **** --- 398,419 ---- } + /* XXX This is a ridiculously inefficient way to pickle a short string. */ + static PyObject * + date_reduce(PyDateTime_Date* self) + { + PyObject* result = NULL; + PyObject* state; + + state = date_getstate(self); + if (state != NULL) { + result = Py_BuildValue("OOO", + self->ob_type, + three_ones, + state); + Py_DECREF(state); + } + return result; + } + static PyMethodDef date_methods[] = { /* Class methods: */ *************** *** 428,435 **** "Return the day of the week represented by the date.\n" "Monday == 0 ... Sunday == 6"}, - {"__getstate__", (PyCFunction)date_getstate, METH_NOARGS, - PyDoc_STR("__getstate__() -> state")}, {"__setstate__", (PyCFunction)date_setstate, METH_O, PyDoc_STR("__setstate__(state)")}, {NULL, NULL} }; --- 442,451 ---- "Return the day of the week represented by the date.\n" "Monday == 0 ... Sunday == 6"}, {"__setstate__", (PyCFunction)date_setstate, METH_O, PyDoc_STR("__setstate__(state)")}, + {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS, + NULL}, + {"__getstate__", (PyCFunction)date_getstate, METH_NOARGS, + PyDoc_STR("__getstate__() -> state")}, {NULL, NULL} }; *************** *** 455,459 **** PyObject_HEAD_INIT(NULL) 0, /* ob_size */ ! "date", /* tp_name */ sizeof(PyDateTime_Date), /* tp_basicsize */ 0, /* tp_itemsize */ --- 471,476 ---- PyObject_HEAD_INIT(NULL) 0, /* ob_size */ ! /* XXX When this module is renamed to datetime, change tp_name. */ ! "_datetime.date", /* tp_name */ sizeof(PyDateTime_Date), /* tp_basicsize */ 0, /* tp_itemsize */ Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** obj_datetime.c 2 Dec 2002 06:42:28 -0000 1.7 --- obj_datetime.c 2 Dec 2002 19:40:42 -0000 1.8 *************** *** 372,382 **** } ! /* XXX Broken attempt to get pickles working. An attempt to pickle ! * XXX craps out in ! * XXX ! * XXX if base is self.__class__: ! * XXX raise TypeError, "can't pickle %s objects" % base.__name__ ! * XXX ! * XXX in Python's copy_reg.py. How to fix? */ static PyObject * --- 372,378 ---- } ! /* Pickle support. Quite a maze! While __getstate__/__setstate__ sufficed ! * in the Python implementation, the C implementation also requires ! * __reduce__, and a __safe_for_unpickling__ attr in the type object. */ static PyObject * *************** *** 402,422 **** } static PyMethodDef datetime_methods[] = { /* Class methods: */ ! {"now", (PyCFunction)datetime_now, METH_O | METH_CLASS, "Return a new datetime that represents the current time."}, ! {"today", (PyCFunction)datetime_today, METH_O | METH_CLASS, "Return a new datetime that represents the current date."}, /* Instance methods: */ ! {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS, "Return ctime() style string."}, {"isoformat", (PyCFunction)datetime_isoformat, METH_KEYWORDS, "Return the day of the week represented by the datetime.\n" "Monday == 1 ... Sunday == 7"}, - {"__getstate__", (PyCFunction)datetime_getstate, METH_NOARGS, - PyDoc_STR("__getstate__() -> state")}, {"__setstate__", (PyCFunction)datetime_setstate, METH_O, PyDoc_STR("__setstate__(state)")}, {NULL, NULL} }; --- 398,438 ---- } + /* XXX This is a ridiculously inefficient way to pickle a short string. */ + static PyObject * + datetime_reduce(PyDateTime_DateTime* self) + { + PyObject* result = NULL; + PyObject* state; + + state = datetime_getstate(self); + if (state != NULL) { + result = Py_BuildValue("OOO", + self->ob_type, + three_ones, + state); + Py_DECREF(state); + } + return result; + } + static PyMethodDef datetime_methods[] = { /* Class methods: */ ! {"now", (PyCFunction)datetime_now, METH_O | METH_CLASS, "Return a new datetime that represents the current time."}, ! {"today", (PyCFunction)datetime_today, METH_O | METH_CLASS, "Return a new datetime that represents the current date."}, /* Instance methods: */ ! {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS, "Return ctime() style string."}, {"isoformat", (PyCFunction)datetime_isoformat, METH_KEYWORDS, "Return the day of the week represented by the datetime.\n" "Monday == 1 ... Sunday == 7"}, {"__setstate__", (PyCFunction)datetime_setstate, METH_O, PyDoc_STR("__setstate__(state)")}, + {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS, + NULL}, + {"__getstate__", (PyCFunction)datetime_getstate, METH_NOARGS, + PyDoc_STR("__getstate__() -> state")}, {NULL, NULL} }; *************** *** 442,446 **** PyObject_HEAD_INIT(NULL) 0, /* ob_size */ ! "datetime", /* tp_name */ sizeof(PyDateTime_DateTime), /* tp_basicsize */ 0, /* tp_itemsize */ --- 458,463 ---- PyObject_HEAD_INIT(NULL) 0, /* ob_size */ ! /* XXX When this module is renamed to datetime, change tp_name. */ ! "_datetime.datetime", /* tp_name */ sizeof(PyDateTime_DateTime), /* tp_basicsize */ 0, /* tp_itemsize */ Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.17 retrieving revision 1.18 diff -C2 -d -r1.17 -r1.18 *** test_both.py 2 Dec 2002 18:10:34 -0000 1.17 --- test_both.py 2 Dec 2002 19:40:42 -0000 1.18 *************** *** 18,24 **** # Import the right implementation, under name "datetime". ! if 'c' in sys.argv: print "Testing the C implementation." import _datetime as datetime else: print "Testing the Python implementation." --- 18,26 ---- # Import the right implementation, under name "datetime". ! TESTING_C = 'c' in sys.argv ! if TESTING_C: print "Testing the C implementation." import _datetime as datetime + import _datetime else: print "Testing the Python implementation." *************** *** 409,414 **** for pickler in pickle, cPickle: for binary in 0, 1: - # XXX Pickling fails in the C implementation. - # XXX Needs to be fixed as for timedelta. green = pickler.dumps(orig, binary) derived = pickler.loads(green) --- 411,414 ---- *************** *** 448,452 **** self.theclass.now()): # Verify dt -> string -> datetime identity. ! s = 'datetime.' + repr(dt) dt2 = eval(s) self.assertEqual(dt, dt2) --- 448,460 ---- self.theclass.now()): # Verify dt -> string -> datetime identity. ! s = repr(dt) ! if not TESTING_C: ! # XXX This hack is due to that the Python implementation of ! # XXX type datetime calls its name 'datetime', but that's a ! # XXX module object here. The C implementation calls its name ! # XXX '_datetime.datetime', so doesn't need a hack. ! # XXX This can get simpler when the Python implementation goes ! # XXX away. ! s = 'datetime.' + s dt2 = eval(s) self.assertEqual(dt, dt2) *************** *** 621,626 **** for pickler in pickle, cPickle: for binary in 0, 1: - # XXX Pickling fails in the C implementation. - # XXX Needs to be fixed as for timedelta. green = pickler.dumps(orig, binary) derived = pickler.loads(green) --- 629,632 ---- From tim.one@comcast.net Mon Dec 2 19:47:04 2002 From: tim.one@comcast.net (Tim Peters) Date: Mon, 02 Dec 2002 14:47:04 -0500 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_delta.c,1.14,1.15 test_both.py,1.15,1.16 In-Reply-To: <20021202190958.GJ28552@epoch.metaslash.com> Message-ID: > > + PyObject *emptytuple = PyTuple_New(0); > > + if (emptytuple != NULL) { > > + result = Py_BuildValue("OOO", > > + self->ob_type, > > + emptytuple, > > + state); > > + Py_DECREF(emptytuple); > > + } > > + Py_DECREF(state); [Neal Norwitz] > What is the purpose of emptytuple here? The docs for __reduce__ say the 2nd component of the return value must be a tuple or None, and the use of None is deprecated. Hence an empty tuple. > Could/should this code be: > > result = Py_BuildValue(...); I have no idea. What does "..." mean? From fdrake@acm.org Mon Dec 2 19:55:42 2002 From: fdrake@acm.org (Fred L. Drake, Jr.) Date: Mon, 2 Dec 2002 14:55:42 -0500 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_delta.c,1.14,1.15 test_both.py,1.15,1.16 In-Reply-To: References: <20021202190958.GJ28552@epoch.metaslash.com> Message-ID: <15851.47806.275680.497745@grendel.zope.com> Tim Peters writes: > The docs for __reduce__ say the 2nd component of the return value must be a > tuple or None, and the use of None is deprecated. Hence an empty tuple. I think you can generate an empty tuple there using: result = Py_BuildValue("O()O", self->ob_type, state); Might be a little simpler. Untested, of course. ;-( -Fred -- Fred L. Drake, Jr. PythonLabs at Zope Corporation From neal@metaslash.com Mon Dec 2 20:13:12 2002 From: neal@metaslash.com (Neal Norwitz) Date: Mon, 2 Dec 2002 15:13:12 -0500 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_delta.c,1.14,1.15 test_both.py,1.15,1.16 In-Reply-To: References: <20021202190958.GJ28552@epoch.metaslash.com> Message-ID: <20021202201312.GK28552@epoch.metaslash.com> On Mon, Dec 02, 2002 at 02:47:04PM -0500, Tim Peters wrote: > > > + PyObject *emptytuple = PyTuple_New(0); > > > + if (emptytuple != NULL) { > > > + result = Py_BuildValue("OOO", > > > + self->ob_type, > > > + emptytuple, > > > + state); > > > + Py_DECREF(emptytuple); > > > + } > > > + Py_DECREF(state); > > [Neal Norwitz] > > What is the purpose of emptytuple here? > > The docs for __reduce__ say the 2nd component of the return value must be a > tuple or None, and the use of None is deprecated. Hence an empty tuple. Whoops, multitasking too much. I didn't see emptytuple in Py_BuildValue(). > > Could/should this code be: > > > > result = Py_BuildValue(...); > > I have no idea. What does "..." mean? I just meant the params were the same. Of course, if I had actually typed it in, I would have realized you were using it. :-) Neal From tim_one@users.sourceforge.net Mon Dec 2 20:43:03 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 02 Dec 2002 12:43:03 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_delta.c,1.16,1.17 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv10627 Modified Files: obj_delta.c Log Message: delta_reduce(): Fred pointed out a niftier way to get an empty tuple embedded in the result tuple. Index: obj_delta.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_delta.c,v retrieving revision 1.16 retrieving revision 1.17 diff -C2 -d -r1.16 -r1.17 *** obj_delta.c 2 Dec 2002 18:10:33 -0000 1.16 --- obj_delta.c 2 Dec 2002 20:42:53 -0000 1.17 *************** *** 580,595 **** { PyObject* result = NULL; ! PyObject* state; - state = delta_getstate(self); if (state != NULL) { ! PyObject *emptytuple = PyTuple_New(0); ! if (emptytuple != NULL) { ! result = Py_BuildValue("OOO", ! self->ob_type, ! emptytuple, ! state); ! Py_DECREF(emptytuple); ! } Py_DECREF(state); } --- 580,590 ---- { PyObject* result = NULL; ! PyObject* state = delta_getstate(self); if (state != NULL) { ! /* The funky "()" in the format string creates an empty ! * tuple as the 2nd component of the result 3-tuple. ! */ ! result = Py_BuildValue("O()O", self->ob_type, state); Py_DECREF(state); } From tim.one@comcast.net Mon Dec 2 20:43:24 2002 From: tim.one@comcast.net (Tim Peters) Date: Mon, 02 Dec 2002 15:43:24 -0500 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_delta.c,1.14,1.15 test_both.py,1.15,1.16 In-Reply-To: <15851.47806.275680.497745@grendel.zope.com> Message-ID: [Fred L. Drake, Jr.] > I think you can generate an empty tuple there using: > > result = Py_BuildValue("O()O", > self->ob_type, > state); Thanks! Works great. From fdrake@acm.org Mon Dec 2 20:51:14 2002 From: fdrake@acm.org (Fred L. Drake, Jr.) Date: Mon, 2 Dec 2002 15:51:14 -0500 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_delta.c,1.14,1.15 test_both.py,1.15,1.16 In-Reply-To: References: <15851.47806.275680.497745@grendel.zope.com> Message-ID: <15851.51138.218721.353223@grendel.zope.com> Tim Peters writes: > Thanks! Works great. I must point out that Jeremy & Barry just groaned when they saw that, but I figure avoiding an extra error check is worth it. -Fred -- Fred L. Drake, Jr. PythonLabs at Zope Corporation From tim_one@users.sourceforge.net Mon Dec 2 21:17:32 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 02 Dec 2002 13:17:32 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_delta.c,1.17,1.18 test_both.py,1.18,1.19 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv20656 Modified Files: obj_delta.c test_both.py Log Message: Repair comparison for timedelta objects. tp_compare is ignored by try_3way_compare because a timedelta isn't an old-style instance, so its tp_compare didn't get called at all unless both comparands were timedelta. This caused, e.g., comparing a timedelta and a dict to compare via type string name instead of raising the intended TypeError. As suggested by Guido, repaired via getting rid of tp_compare and adding tp_richcompare. The test suite didn't provoke these problems, so added a new test that does. I'm sure that date and datetime objects still suffer a similar problem. Index: obj_delta.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_delta.c,v retrieving revision 1.17 retrieving revision 1.18 diff -C2 -d -r1.17 -r1.18 *** obj_delta.c 2 Dec 2002 20:42:53 -0000 1.17 --- obj_delta.c 2 Dec 2002 21:17:14 -0000 1.18 *************** *** 246,278 **** } ! /* XXX This routine is never entered unless self and other are both ! * XXX PyDateTime_Delta. For whatever reason, Python's try_3way_compare ! * XXX ignores tp_compare unless PyInstance_Check returns true, but ! * XXX these aren't old-style classes. */ ! static int ! delta_compare(PyDateTime_Delta *self, PyObject *other) { ! int result = -1; if (! PyObject_TypeCheck(other, &PyDateTime_DeltaType)) { - /* XXX Dead code! See note above. */ PyErr_Format(PyExc_TypeError, "can't compare %s to %s instance", self->ob_type->tp_name, other->ob_type->tp_name); } ! else { ! long 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); ! } if (diff == 0) ! result = 0; ! else if (diff > 0) ! result = 1; } return result; } --- 246,285 ---- } ! /* 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) { ! PyObject *result; ! long diff; ! int istrue; if (! PyObject_TypeCheck(other, &PyDateTime_DeltaType)) { PyErr_Format(PyExc_TypeError, "can't compare %s to %s instance", self->ob_type->tp_name, other->ob_type->tp_name); + return NULL; } ! 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); ! } ! switch (op) { ! case Py_EQ: istrue = diff == 0; break; ! case Py_NE: istrue = diff != 0; break; ! case Py_LE: istrue = diff <= 0; break; ! case Py_GE: istrue = diff >= 0; break; ! case Py_LT: istrue = diff < 0; break; ! case Py_GT: istrue = diff > 0; break; ! default: ! assert(! "op unknown"); } + result = istrue ? Py_True : Py_False; + Py_INCREF(result); return result; } *************** *** 668,672 **** 0, /* tp_getattr */ 0, /* tp_setattr */ ! (cmpfunc)delta_compare, /* tp_compare */ (reprfunc)delta_repr, /* tp_repr */ &delta_as_number, /* tp_as_number */ --- 675,679 ---- 0, /* tp_getattr */ 0, /* tp_setattr */ ! 0, /* tp_compare */ (reprfunc)delta_repr, /* tp_repr */ &delta_as_number, /* tp_as_number */ *************** *** 683,687 **** 0, /* tp_traverse */ 0, /* tp_clear */ ! 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ --- 690,694 ---- 0, /* tp_traverse */ 0, /* tp_clear */ ! delta_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** test_both.py 2 Dec 2002 19:40:42 -0000 1.18 --- test_both.py 2 Dec 2002 21:17:18 -0000 1.19 *************** *** 146,149 **** --- 146,192 ---- self.assertEqual(orig, derived) + def test_compare(self): + t1 = timedelta(2, 3, 4) + t2 = timedelta(2, 3, 4) + self.failUnless(t1 == t2) + self.failUnless(t1 <= t2) + self.failUnless(t1 >= t2) + self.failUnless(not t1 != t2) + self.failUnless(not t1 < t2) + self.failUnless(not t1 > t2) + self.assertEqual(cmp(t1, t2), 0) + self.assertEqual(cmp(t2, t1), 0) + + for args in (3, 3, 3), (2, 4, 4), (2, 3, 5): + t2 = timedelta(*args) # this is larger than t1 + self.failUnless(t1 < t2) + self.failUnless(t2 > t1) + self.failUnless(t1 <= t2) + self.failUnless(t2 >= t1) + self.failUnless(t1 != t2) + self.failUnless(t2 != t1) + self.failUnless(not t1 == t2) + self.failUnless(not t2 == t1) + self.failUnless(not t1 > t2) + self.failUnless(not t2 < t1) + self.failUnless(not t1 >= t2) + self.failUnless(not t2 <= t1) + self.assertEqual(cmp(t1, t2), -1) + self.assertEqual(cmp(t2, t1), 1) + + for badarg in 10, 10L, 34.5, "abc", {}, [], (): + self.assertRaises(TypeError, lambda: t1 == badarg) + self.assertRaises(TypeError, lambda: t1 != badarg) + self.assertRaises(TypeError, lambda: t1 <= badarg) + self.assertRaises(TypeError, lambda: t1 < badarg) + self.assertRaises(TypeError, lambda: t1 > badarg) + self.assertRaises(TypeError, lambda: t1 >= badarg) + self.assertRaises(TypeError, lambda: badarg == t1) + self.assertRaises(TypeError, lambda: badarg != t1) + self.assertRaises(TypeError, lambda: badarg <= t1) + self.assertRaises(TypeError, lambda: badarg < t1) + self.assertRaises(TypeError, lambda: badarg > t1) + self.assertRaises(TypeError, lambda: badarg >= t1) + ############################################################################# # date tests From tim.one@comcast.net Mon Dec 2 21:29:14 2002 From: tim.one@comcast.net (Tim Peters) Date: Mon, 02 Dec 2002 16:29:14 -0500 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_delta.c,1.14,1.15 test_both.py,1.15,1.16 In-Reply-To: <15851.51138.218721.353223@grendel.zope.com> Message-ID: > I must point out that Jeremy & Barry just groaned when they saw that, > but I figure avoiding an extra error check is worth it. I added sufficient comments to shush their wails of anguish. I'd rather find a way to avoid __reduce__ entirely, though! The Python implementation of these things didn't need it, and in the date and datetime cases it's creating bigger pickles than it should -- __getstate__ and __setstate__ already did all that was necessary, and no more than that. Supplying an argument tuple for __reduce__'s benefit loses either way: I either put the real date/datetime arguments there, but then the pickle is of a big tuple rather than of a tiny string. Or I put a dummy argument tuple there and also include the tiny string for __setstate__, but these constructors require at least 3 arguments so that the "dummy argument tuple" consumes substantial space of its own. So, as it stands, ignoring the new-style-class administrative pickle bloat in the Python implementation, the *guts* of the pickles produced by the Python implementation are substantially smaller than those produced by the C implementation. From fdrake@acm.org Mon Dec 2 21:47:04 2002 From: fdrake@acm.org (Fred L. Drake, Jr.) Date: Mon, 2 Dec 2002 16:47:04 -0500 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_delta.c,1.14,1.15 test_both.py,1.15,1.16 In-Reply-To: References: <15851.51138.218721.353223@grendel.zope.com> Message-ID: <15851.54488.963027.945729@grendel.zope.com> Tim Peters writes: > So, as it stands, ignoring the new-style-class administrative pickle bloat > in the Python implementation, the *guts* of the pickles produced by the > Python implementation are substantially smaller than those produced by the C > implementation. You might be able to work with the copy_reg module instead of using __reduce__. That's what I did for the parser module (Modules/parsermodule.c). I don't know if that'll work for new-style objects. -Fred -- Fred L. Drake, Jr. PythonLabs at Zope Corporation From tim_one@users.sourceforge.net Mon Dec 2 21:51:07 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 02 Dec 2002 13:51:07 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.c,1.33,1.34 obj_date.c,1.14,1.15 obj_delta.c,1.18,1.19 test_both.py,1.20,1.21 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv2377 Modified Files: datetime.c obj_date.c obj_delta.c test_both.py Log Message: Repaired comparison for date objects. datetime comparison is still broken in the C implementation. Index: datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.c,v retrieving revision 1.33 retrieving revision 1.34 diff -C2 -d -r1.33 -r1.34 *** datetime.c 2 Dec 2002 19:40:41 -0000 1.33 --- datetime.c 2 Dec 2002 21:50:55 -0000 1.34 *************** *** 538,541 **** --- 538,566 ---- static PyObject* three_ones = NULL; /* an argument tuple for __reduce__ */ + /* For obscure 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. + */ + static PyObject * + diff_to_bool(long diff, int op) + { + PyObject *result; + int istrue; + + switch (op) { + case Py_EQ: istrue = diff == 0; break; + case Py_NE: istrue = diff != 0; break; + case Py_LE: istrue = diff <= 0; break; + case Py_GE: istrue = diff >= 0; break; + case Py_LT: istrue = diff < 0; break; + case Py_GT: istrue = diff > 0; break; + default: + assert(! "op unknown"); + } + result = istrue ? Py_True : Py_False; + Py_INCREF(result); + return result; + } + #include "obj_delta.c" #include "obj_date.c" Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.14 retrieving revision 1.15 diff -C2 -d -r1.14 -r1.15 *** obj_date.c 2 Dec 2002 19:40:42 -0000 1.14 --- obj_date.c 2 Dec 2002 21:50:57 -0000 1.15 *************** *** 95,108 **** } ! static int ! date_compare(PyDateTime_Date *self, PyObject *other) { ! if (!PyType_IsSubtype(other->ob_type, &PyDateTime_DateType)) { PyErr_SetString(PyExc_TypeError, "can't compare date to %s instance"); ! return -1; } ! return memcmp(self->data, ((PyDateTime_Date *)other)->data, _PyDateTime_DATE_DATA_SIZE); } --- 95,115 ---- } ! /* 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) { ! long diff; ! ! if (! PyType_IsSubtype(other->ob_type, &PyDateTime_DateType)) { PyErr_SetString(PyExc_TypeError, "can't compare date to %s instance"); ! return NULL; } ! diff = memcmp(self->data, ((PyDateTime_Date *)other)->data, _PyDateTime_DATE_DATA_SIZE); + return diff_to_bool(diff, op); } *************** *** 479,483 **** 0, /* tp_getattr */ 0, /* tp_setattr */ ! (cmpfunc)date_compare, /* tp_compare */ (reprfunc)date_repr, /* tp_repr */ &date_as_number, /* tp_as_number */ --- 486,490 ---- 0, /* tp_getattr */ 0, /* tp_setattr */ ! 0, /* tp_compare */ (reprfunc)date_repr, /* tp_repr */ &date_as_number, /* tp_as_number */ *************** *** 495,499 **** 0, /* tp_traverse */ 0, /* tp_clear */ ! 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ --- 502,506 ---- 0, /* tp_traverse */ 0, /* tp_clear */ ! (richcmpfunc)date_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ Index: obj_delta.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_delta.c,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** obj_delta.c 2 Dec 2002 21:17:14 -0000 1.18 --- obj_delta.c 2 Dec 2002 21:50:59 -0000 1.19 *************** *** 253,259 **** delta_richcompare(PyDateTime_Delta *self, PyObject *other, int op) { - PyObject *result; long diff; - int istrue; if (! PyObject_TypeCheck(other, &PyDateTime_DeltaType)) { --- 253,257 ---- *************** *** 270,286 **** GET_TD_MICROSECONDS(other); } ! switch (op) { ! case Py_EQ: istrue = diff == 0; break; ! case Py_NE: istrue = diff != 0; break; ! case Py_LE: istrue = diff <= 0; break; ! case Py_GE: istrue = diff >= 0; break; ! case Py_LT: istrue = diff < 0; break; ! case Py_GT: istrue = diff > 0; break; ! default: ! assert(! "op unknown"); ! } ! result = istrue ? Py_True : Py_False; ! Py_INCREF(result); ! return result; } --- 268,272 ---- GET_TD_MICROSECONDS(other); } ! return diff_to_bool(diff, op); } *************** *** 690,694 **** 0, /* tp_traverse */ 0, /* tp_clear */ ! delta_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ --- 676,680 ---- 0, /* tp_traverse */ 0, /* tp_clear */ ! (richcmpfunc)delta_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.20 retrieving revision 1.21 diff -C2 -d -r1.20 -r1.21 *** test_both.py 2 Dec 2002 21:37:47 -0000 1.20 --- test_both.py 2 Dec 2002 21:51:00 -0000 1.21 *************** *** 458,463 **** self.assertEqual(orig, derived) ! # XXX This currently fails in the C implementation, due to never raising ! # XXX TypeError. Needs to be fixed as timedelta got fixed. def test_compare(self): t1 = self.theclass(2, 3, 4) --- 458,464 ---- self.assertEqual(orig, derived) ! # XXX This currently fails in the C implementation, for datetime (but not ! # XXX date) objects, due to never raising TypeError. Needs to be fixed ! # XXX as timedelta and date got fixed. def test_compare(self): t1 = self.theclass(2, 3, 4) From tim_one@users.sourceforge.net Mon Dec 2 21:55:26 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 02 Dec 2002 13:55:26 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_datetime.c,1.8,1.9 test_both.py,1.21,1.22 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv4482 Modified Files: obj_datetime.c test_both.py Log Message: Repaired comparison for C datetime objects. All the tests currently pass. datetime objects could stand to have another comparison test (they're only tested now to the extent that the inherited TestDate tests exercise the year, month, and day fields). Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** obj_datetime.c 2 Dec 2002 19:40:42 -0000 1.8 --- obj_datetime.c 2 Dec 2002 21:55:21 -0000 1.9 *************** *** 126,139 **** } ! static int ! datetime_compare(PyDateTime_DateTime *self, PyObject *other) { if (!PyType_IsSubtype(other->ob_type, &PyDateTime_DateTimeType)) { PyErr_SetString(PyExc_TypeError, "can't compare date to %s instance"); ! return -1; } ! return memcmp(self->data, ((PyDateTime_DateTime *)other)->data, _PyDateTime_DATETIME_DATA_SIZE); } --- 126,146 ---- } ! /* 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) { + long diff; + if (!PyType_IsSubtype(other->ob_type, &PyDateTime_DateTimeType)) { PyErr_SetString(PyExc_TypeError, "can't compare date to %s instance"); ! return NULL; } ! diff = memcmp(self->data, ((PyDateTime_DateTime *)other)->data, _PyDateTime_DATETIME_DATA_SIZE); + return diff_to_bool(diff, op); } *************** *** 466,470 **** 0, /* tp_getattr */ 0, /* tp_setattr */ ! (cmpfunc)datetime_compare, /* tp_compare */ (reprfunc)datetime_repr, /* tp_repr */ &datetime_as_number, /* tp_as_number */ --- 473,477 ---- 0, /* tp_getattr */ 0, /* tp_setattr */ ! 0, /* tp_compare */ (reprfunc)datetime_repr, /* tp_repr */ &datetime_as_number, /* tp_as_number */ *************** *** 482,486 **** 0, /* tp_traverse */ 0, /* tp_clear */ ! 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ --- 489,493 ---- 0, /* tp_traverse */ 0, /* tp_clear */ ! (richcmpfunc)datetime_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.21 retrieving revision 1.22 diff -C2 -d -r1.21 -r1.22 *** test_both.py 2 Dec 2002 21:51:00 -0000 1.21 --- test_both.py 2 Dec 2002 21:55:21 -0000 1.22 *************** *** 458,464 **** self.assertEqual(orig, derived) - # XXX This currently fails in the C implementation, for datetime (but not - # XXX date) objects, due to never raising TypeError. Needs to be fixed - # XXX as timedelta and date got fixed. def test_compare(self): t1 = self.theclass(2, 3, 4) --- 458,461 ---- From tim_one@users.sourceforge.net Mon Dec 2 21:37:50 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 02 Dec 2002 13:37:50 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime test_both.py,1.19,1.20 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv28331 Modified Files: test_both.py Log Message: Added a comparison test for the date type. This currently fails in the C implementation. Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.19 retrieving revision 1.20 diff -C2 -d -r1.19 -r1.20 *** test_both.py 2 Dec 2002 21:17:18 -0000 1.19 --- test_both.py 2 Dec 2002 21:37:47 -0000 1.20 *************** *** 458,461 **** --- 458,506 ---- self.assertEqual(orig, derived) + # XXX This currently fails in the C implementation, due to never raising + # XXX TypeError. Needs to be fixed as timedelta got fixed. + def test_compare(self): + t1 = self.theclass(2, 3, 4) + t2 = self.theclass(2, 3, 4) + self.failUnless(t1 == t2) + self.failUnless(t1 <= t2) + self.failUnless(t1 >= t2) + self.failUnless(not t1 != t2) + self.failUnless(not t1 < t2) + self.failUnless(not t1 > t2) + self.assertEqual(cmp(t1, t2), 0) + self.assertEqual(cmp(t2, t1), 0) + + for args in (3, 3, 3), (2, 4, 4), (2, 3, 5): + t2 = self.theclass(*args) # this is larger than t1 + self.failUnless(t1 < t2) + self.failUnless(t2 > t1) + self.failUnless(t1 <= t2) + self.failUnless(t2 >= t1) + self.failUnless(t1 != t2) + self.failUnless(t2 != t1) + self.failUnless(not t1 == t2) + self.failUnless(not t2 == t1) + self.failUnless(not t1 > t2) + self.failUnless(not t2 < t1) + self.failUnless(not t1 >= t2) + self.failUnless(not t2 <= t1) + self.assertEqual(cmp(t1, t2), -1) + self.assertEqual(cmp(t2, t1), 1) + + for badarg in 10, 10L, 34.5, "abc", {}, [], (): + self.assertRaises(TypeError, lambda: t1 == badarg) + self.assertRaises(TypeError, lambda: t1 != badarg) + self.assertRaises(TypeError, lambda: t1 <= badarg) + self.assertRaises(TypeError, lambda: t1 < badarg) + self.assertRaises(TypeError, lambda: t1 > badarg) + self.assertRaises(TypeError, lambda: t1 >= badarg) + self.assertRaises(TypeError, lambda: badarg == t1) + self.assertRaises(TypeError, lambda: badarg != t1) + self.assertRaises(TypeError, lambda: badarg <= t1) + self.assertRaises(TypeError, lambda: badarg < t1) + self.assertRaises(TypeError, lambda: badarg > t1) + self.assertRaises(TypeError, lambda: badarg >= t1) + ############################################################################# # datetime tests From tim_one@users.sourceforge.net Mon Dec 2 22:07:24 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 02 Dec 2002 14:07:24 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_date.c,1.15,1.16 obj_datetime.c,1.9,1.10 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv10012 Modified Files: obj_date.c obj_datetime.c Log Message: Old bug in date and datetime comparison, not noticed before because the TypeError code was unreachable: use PyErr_Format instead of PyErr_String, because these guys are trying to give the name of the offending type. Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.15 retrieving revision 1.16 diff -C2 -d -r1.15 -r1.16 *** obj_date.c 2 Dec 2002 21:50:57 -0000 1.15 --- obj_date.c 2 Dec 2002 22:07:16 -0000 1.16 *************** *** 105,110 **** if (! PyType_IsSubtype(other->ob_type, &PyDateTime_DateType)) { ! PyErr_SetString(PyExc_TypeError, ! "can't compare date to %s instance"); return NULL; } --- 105,111 ---- if (! PyType_IsSubtype(other->ob_type, &PyDateTime_DateType)) { ! PyErr_Format(PyExc_TypeError, ! "can't compare date to %s instance", ! other->ob_type->tp_name); return NULL; } Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** obj_datetime.c 2 Dec 2002 21:55:21 -0000 1.9 --- obj_datetime.c 2 Dec 2002 22:07:17 -0000 1.10 *************** *** 136,141 **** if (!PyType_IsSubtype(other->ob_type, &PyDateTime_DateTimeType)) { ! PyErr_SetString(PyExc_TypeError, ! "can't compare date to %s instance"); return NULL; } --- 136,142 ---- if (!PyType_IsSubtype(other->ob_type, &PyDateTime_DateTimeType)) { ! PyErr_Format(PyExc_TypeError, ! "can't compare datetime to %s instance", ! other->ob_type->tp_name); return NULL; } From loewis@users.sourceforge.net Mon Dec 2 22:17:03 2002 From: loewis@users.sourceforge.net (loewis@users.sourceforge.net) Date: Mon, 02 Dec 2002 14:17:03 -0800 Subject: [Python-checkins] python/dist/src README,1.159,1.160 configure,1.361,1.362 configure.in,1.372,1.373 Message-ID: Update of /cvsroot/python/python/dist/src In directory sc8-pr-cvs1:/tmp/cvs-serv14112 Modified Files: README configure configure.in Log Message: Add compile-time errors for unsupported systems. Index: README =================================================================== RCS file: /cvsroot/python/python/dist/src/README,v retrieving revision 1.159 retrieving revision 1.160 diff -C2 -d -r1.159 -r1.160 *** README 2 Dec 2002 15:49:13 -0000 1.159 --- README 2 Dec 2002 22:16:56 -0000 1.160 *************** *** 225,228 **** --- 225,250 ---- compilers from the vendor, or one of the free compilers (gcc). + Unsupported systems + ------------------- + + A number of features are not supported in Python 2.3 anymore. Some + support code is still present, but will be removed in Python 2.4. + If you still need to use current Python versions on these systems, + please send a message to python-dev@python.org indicating that you + volunteer to support this system. + + More specifically, the following systems are not supported any + longer: + - SunOS 4 + - DYNIX + - dgux + - Minix + - Irix 4 and --with-sgi-dl + - Linux 1 + - Systems defining __d6_pthread_create (configure.in) + - Systems defining PY_PTHREAD_D4, PY_PTHREAD_D6, + or PY_PTHREAD_D7 in thread_pthread.h + - Systems using --with-dl-dld + Platform specific notes ----------------------- *************** *** 352,355 **** --- 374,378 ---- '-Xa' option instead of '-Xc', to enable some needed non-ANSI Sunisms. + THIS SYSTEM IS NO LONGER SUPPORTED. NeXT: Not supported anymore. Start with the MacOSX/Darwin code if you *************** *** 887,891 **** is the absolute pathname of the dl library. (Don't bother on IRIX 5, it already has dynamic linking using SunOS style ! shared libraries.) Support for this feature is deprecated. --with-dl-dld: Dynamic loading of modules is rumored to be supported --- 910,914 ---- is the absolute pathname of the dl library. (Don't bother on IRIX 5, it already has dynamic linking using SunOS style ! shared libraries.) THIS OPTION IS UNSUPPORTED. --with-dl-dld: Dynamic loading of modules is rumored to be supported *************** *** 903,908 **** DLD_DIRECTORY is the absolute pathname of the GNU dld library. (Don't bother on SunOS 4 or 5, they already have dynamic ! linking using shared libraries.) Support for this feature is ! deprecated. --with-libm, --with-libc: It is possible to specify alternative --- 926,930 ---- DLD_DIRECTORY is the absolute pathname of the GNU dld library. (Don't bother on SunOS 4 or 5, they already have dynamic ! linking using shared libraries.) THIS OPTION IS UNSUPPORTED. --with-libm, --with-libc: It is possible to specify alternative Index: configure =================================================================== RCS file: /cvsroot/python/python/dist/src/configure,v retrieving revision 1.361 retrieving revision 1.362 diff -C2 -d -r1.361 -r1.362 *** configure 23 Nov 2002 09:13:38 -0000 1.361 --- configure 2 Dec 2002 22:16:56 -0000 1.362 *************** *** 1,4 **** #! /bin/sh ! # From configure.in Revision: 1.371 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.53 for python 2.3. --- 1,4 ---- #! /bin/sh ! # From configure.in Revision: 1.372 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.53 for python 2.3. *************** *** 3000,3003 **** --- 3000,3017 ---- + # Check for unsupported systems + case $ac_sys_system/$ac_sys_release in + SunOS/4*|DYNIX/*|dgux*/*|IRIX/4*|Linux*/1*) + echo This system \($ac_sys_system/$ac_sys_release\) is no longer supported. + echo See README for details. + exit 1;; + esac + + if test "$MINIX" = yes; then + echo This system \(MINIX\) is no longer supported. + echo Read README for details. + exit 1 + fi + echo "$as_me:$LINENO: checking for --with-suffix" >&5 *************** *** 10867,10870 **** --- 10881,10887 ---- _ACEOF + echo Systems with __d6_pthread_create are not supported anymore. + echo See README + exit 1 posix_threads=yes LIBS="$LIBS -lthread" *************** *** 11734,11737 **** --- 11751,11756 ---- echo "$as_me:$LINENO: result: $withval" >&5 echo "${ECHO_T}$withval" >&6 + echo --with-sgi-dl is unsupported; see README + exit 1 cat >>confdefs.h <<\_ACEOF *************** *** 11763,11766 **** --- 11782,11787 ---- echo "$as_me:$LINENO: result: $withval" >&5 echo "${ECHO_T}$withval" >&6 + echo --with-dl-dld is unsupported; see README + exit 1 cat >>confdefs.h <<\_ACEOF Index: configure.in =================================================================== RCS file: /cvsroot/python/python/dist/src/configure.in,v retrieving revision 1.372 retrieving revision 1.373 diff -C2 -d -r1.372 -r1.373 *** configure.in 23 Nov 2002 09:13:40 -0000 1.372 --- configure.in 2 Dec 2002 22:17:00 -0000 1.373 *************** *** 262,265 **** --- 262,279 ---- AC_MINIX + # Check for unsupported systems + case $ac_sys_system/$ac_sys_release in + SunOS/4*|DYNIX/*|dgux*/*|IRIX/4*|Linux*/1*) + echo This system \($ac_sys_system/$ac_sys_release\) is no longer supported. + echo See README for details. + exit 1;; + esac + + if test "$MINIX" = yes; then + echo This system \(MINIX\) is no longer supported. + echo Read README for details. + exit 1 + fi + AC_EXEEXT AC_MSG_CHECKING(for --with-suffix) *************** *** 1339,1342 **** --- 1353,1359 ---- THREADOBJ="Python/thread.o"], [ AC_CHECK_LIB(thread, __d6_pthread_create, [AC_DEFINE(WITH_THREAD) + echo Systems with __d6_pthread_create are not supported anymore. + echo See README + exit 1 posix_threads=yes LIBS="$LIBS -lthread" *************** *** 1651,1654 **** --- 1668,1673 ---- [ AC_MSG_RESULT($withval) + echo --with-sgi-dl is unsupported; see README + exit 1 AC_DEFINE(WITH_SGI_DL, 1, [Define if you want to use SGI (IRIX 4) dynamic linking. *************** *** 1671,1674 **** --- 1690,1695 ---- [ AC_MSG_RESULT($withval) + echo --with-dl-dld is unsupported; see README + exit 1 AC_DEFINE(WITH_DL_DLD, 1, [Define if you want to emulate SGI (IRIX 4) dynamic linking. From loewis@users.sourceforge.net Mon Dec 2 22:17:03 2002 From: loewis@users.sourceforge.net (loewis@users.sourceforge.net) Date: Mon, 02 Dec 2002 14:17:03 -0800 Subject: [Python-checkins] python/dist/src/Python thread_pthread.h,2.41,2.42 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv14112/Python Modified Files: thread_pthread.h Log Message: Add compile-time errors for unsupported systems. Index: thread_pthread.h =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/thread_pthread.h,v retrieving revision 2.41 retrieving revision 2.42 diff -C2 -d -r2.41 -r2.42 *** thread_pthread.h 4 Oct 2002 07:21:24 -0000 2.41 --- thread_pthread.h 2 Dec 2002 22:17:01 -0000 2.42 *************** *** 32,35 **** --- 32,36 ---- /* _DECTHREADS_ is defined in cma.h which is included by pthread.h */ # define PY_PTHREAD_D4 + # error Systems with PY_PTHREAD_D4 are unsupported. See README. #elif defined(__osf__) && defined (__alpha) *************** *** 37,40 **** --- 38,42 ---- # if !defined(_PTHREAD_ENV_ALPHA) || defined(_PTHREAD_USE_D4) || defined(PTHREAD_USE_D4) # define PY_PTHREAD_D4 + # error Systems with PY_PTHREAD_D4 are unsupported. See README. # else # define PY_PTHREAD_STD *************** *** 51,61 **** --- 53,66 ---- # else # define PY_PTHREAD_D7 + # error Systems with PY_PTHREAD_D7 are unsupported. See README. # endif #elif defined(__DGUX) # define PY_PTHREAD_D6 + # error Systems with PY_PTHREAD_D6 are unsupported. See README. #elif defined(__hpux) && defined(_DECTHREADS_) # define PY_PTHREAD_D4 + # error Systems with PY_PTHREAD_D4 are unsupported. See README. #else /* Default case */ From loewis@users.sourceforge.net Mon Dec 2 22:23:59 2002 From: loewis@users.sourceforge.net (loewis@users.sourceforge.net) Date: Mon, 02 Dec 2002 14:23:59 -0800 Subject: [Python-checkins] python/dist/src configure,1.362,1.363 configure.in,1.373,1.374 Message-ID: Update of /cvsroot/python/python/dist/src In directory sc8-pr-cvs1:/tmp/cvs-serv17551 Modified Files: configure configure.in Log Message: Avoid semicolon usage in echo. Index: configure =================================================================== RCS file: /cvsroot/python/python/dist/src/configure,v retrieving revision 1.362 retrieving revision 1.363 diff -C2 -d -r1.362 -r1.363 *** configure 2 Dec 2002 22:16:56 -0000 1.362 --- configure 2 Dec 2002 22:23:52 -0000 1.363 *************** *** 1,4 **** #! /bin/sh ! # From configure.in Revision: 1.372 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.53 for python 2.3. --- 1,4 ---- #! /bin/sh ! # From configure.in Revision: 1.373 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.53 for python 2.3. *************** *** 11751,11755 **** echo "$as_me:$LINENO: result: $withval" >&5 echo "${ECHO_T}$withval" >&6 ! echo --with-sgi-dl is unsupported; see README exit 1 --- 11751,11755 ---- echo "$as_me:$LINENO: result: $withval" >&5 echo "${ECHO_T}$withval" >&6 ! echo --with-sgi-dl is unsupported, see README exit 1 *************** *** 11782,11786 **** echo "$as_me:$LINENO: result: $withval" >&5 echo "${ECHO_T}$withval" >&6 ! echo --with-dl-dld is unsupported; see README exit 1 --- 11782,11786 ---- echo "$as_me:$LINENO: result: $withval" >&5 echo "${ECHO_T}$withval" >&6 ! echo --with-dl-dld is unsupported, see README exit 1 Index: configure.in =================================================================== RCS file: /cvsroot/python/python/dist/src/configure.in,v retrieving revision 1.373 retrieving revision 1.374 diff -C2 -d -r1.373 -r1.374 *** configure.in 2 Dec 2002 22:17:00 -0000 1.373 --- configure.in 2 Dec 2002 22:23:56 -0000 1.374 *************** *** 1668,1672 **** [ AC_MSG_RESULT($withval) ! echo --with-sgi-dl is unsupported; see README exit 1 AC_DEFINE(WITH_SGI_DL, 1, --- 1668,1672 ---- [ AC_MSG_RESULT($withval) ! echo --with-sgi-dl is unsupported, see README exit 1 AC_DEFINE(WITH_SGI_DL, 1, *************** *** 1690,1694 **** [ AC_MSG_RESULT($withval) ! echo --with-dl-dld is unsupported; see README exit 1 AC_DEFINE(WITH_DL_DLD, 1, --- 1690,1694 ---- [ AC_MSG_RESULT($withval) ! echo --with-dl-dld is unsupported, see README exit 1 AC_DEFINE(WITH_DL_DLD, 1, From tim_one@users.sourceforge.net Mon Dec 2 23:28:15 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 02 Dec 2002 15:28:15 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_datetime.c,1.10,1.11 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv9751 Modified Files: obj_datetime.c Log Message: Folded long lines. Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** obj_datetime.c 2 Dec 2002 22:07:17 -0000 1.10 --- obj_datetime.c 2 Dec 2002 23:28:13 -0000 1.11 *************** *** 159,165 **** PyObject *temp; temp = Py_BuildValue("lllllll", GET_YEAR(self), ! GET_MONTH(self), GET_DAY(self), ! GET_HOUR(self), GET_MINUTE(self), ! GET_SECOND(self), GET_MICROSECOND(self)); if (temp != NULL) { self->hashcode = PyObject_Hash(temp); --- 159,165 ---- PyObject *temp; temp = Py_BuildValue("lllllll", GET_YEAR(self), ! GET_MONTH(self), GET_DAY(self), ! GET_HOUR(self), GET_MINUTE(self), ! GET_SECOND(self), GET_MICROSECOND(self)); if (temp != NULL) { self->hashcode = PyObject_Hash(temp); *************** *** 174,181 **** { PyObject *self = NULL; ! long int year, month, day, hour = 0, minute = 0, second = 0, usecond = 0; static char *keywords[] = { ! "year", "month", "day", "hour", "minute", "second", "microsecond", NULL }; --- 174,188 ---- { PyObject *self = NULL; ! long year; ! long month; ! long day; ! long hour = 0; ! long minute = 0; ! long second = 0; ! long usecond = 0; static char *keywords[] = { ! "year", "month", "day", "hour", "minute", "second", ! "microsecond", NULL }; *************** *** 184,208 **** &second, &usecond)) { if (year < MINYEAR || year > MAXYEAR) { ! PyErr_SetString(PyExc_ValueError, "year is out of range"); return NULL; } if (month < 1 || month > 12) { ! PyErr_SetString(PyExc_ValueError, "month must be in 1..12"); return NULL; } if (day < 1 || day > days_in_month(year, month)) { ! PyErr_SetString(PyExc_ValueError, "day is out of range for month"); return NULL; } if (hour < 0 || hour > 23) { ! PyErr_SetString(PyExc_ValueError, "hour must be in 0..23"); return NULL; } if (minute < 0 || minute > 59) { ! PyErr_SetString(PyExc_ValueError, "minute must be in 0..59"); return NULL; } if (second < 0 || second > 59) { ! PyErr_SetString(PyExc_ValueError, "second must be in 0..59"); return NULL; } --- 191,221 ---- &second, &usecond)) { if (year < MINYEAR || year > MAXYEAR) { ! PyErr_SetString(PyExc_ValueError, ! "year is out of range"); return NULL; } if (month < 1 || month > 12) { ! PyErr_SetString(PyExc_ValueError, ! "month must be in 1..12"); return NULL; } if (day < 1 || day > days_in_month(year, month)) { ! PyErr_SetString(PyExc_ValueError, ! "day is out of range for month"); return NULL; } if (hour < 0 || hour > 23) { ! PyErr_SetString(PyExc_ValueError, ! "hour must be in 0..23"); return NULL; } if (minute < 0 || minute > 59) { ! PyErr_SetString(PyExc_ValueError, ! "minute must be in 0..59"); return NULL; } if (second < 0 || second > 59) { ! PyErr_SetString(PyExc_ValueError, ! "second must be in 0..59"); return NULL; } *************** *** 212,216 **** return NULL; } ! self = new_datetime(year, month, day, hour, minute, second, usecond); } return self; --- 225,230 ---- return NULL; } ! self = new_datetime(year, month, day, hour, minute, second, ! usecond); } return self; From tim_one@users.sourceforge.net Mon Dec 2 23:35:49 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 02 Dec 2002 15:35:49 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime test_both.py,1.22,1.23 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv12413 Modified Files: test_both.py Log Message: TestDateTime: added a new test to cover normal comparisons not already covered by the inherited TestDate.test_compare(). Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.22 retrieving revision 1.23 diff -C2 -d -r1.22 -r1.23 *** test_both.py 2 Dec 2002 21:55:21 -0000 1.22 --- test_both.py 2 Dec 2002 23:35:46 -0000 1.23 *************** *** 719,722 **** --- 719,758 ---- self.assertEqual(orig, derived) + def test_more_compare(self): + # The test_compare() inherited from TestDate covers the error cases. + # We just want to test lexicographic ordering on the members datetime + # has that date lacks. + args = [2000, 11, 29, 20, 58, 16, 999998] + t1 = self.theclass(*args) + t2 = self.theclass(*args) + self.failUnless(t1 == t2) + self.failUnless(t1 <= t2) + self.failUnless(t1 >= t2) + self.failUnless(not t1 != t2) + self.failUnless(not t1 < t2) + self.failUnless(not t1 > t2) + self.assertEqual(cmp(t1, t2), 0) + self.assertEqual(cmp(t2, t1), 0) + + for i in range(len(args)): + newargs = args[:] + newargs[i] = args[i] + 1 + t2 = self.theclass(*newargs) # this is larger than t1 + self.failUnless(t1 < t2) + self.failUnless(t2 > t1) + self.failUnless(t1 <= t2) + self.failUnless(t2 >= t1) + self.failUnless(t1 != t2) + self.failUnless(t2 != t1) + self.failUnless(not t1 == t2) + self.failUnless(not t2 == t1) + self.failUnless(not t1 > t2) + self.failUnless(not t2 < t1) + self.failUnless(not t1 >= t2) + self.failUnless(not t2 <= t1) + self.assertEqual(cmp(t1, t2), -1) + self.assertEqual(cmp(t2, t1), 1) + + def test_suite(): allsuites = [unittest.makeSuite(klass, 'test') From tim_one@users.sourceforge.net Mon Dec 2 23:47:22 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 02 Dec 2002 15:47:22 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime test_both.py,1.23,1.24 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv16552 Modified Files: test_both.py Log Message: TestTimeDelta: added simple tests for things that weren't being tested; fiddled some code for a more uniform style. Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.23 retrieving revision 1.24 diff -C2 -d -r1.23 -r1.24 *** test_both.py 2 Dec 2002 23:35:46 -0000 1.23 --- test_both.py 2 Dec 2002 23:47:20 -0000 1.24 *************** *** 41,79 **** class TestTimeDelta(unittest.TestCase): ! def test_timedelta(self): ! a = timedelta(7) # One week ! b = timedelta(0, 60) # One minute ! c = timedelta(0, 0, 1000) # One millisecond ! self.assertEqual(a+b+c, timedelta(7, 60, 1000)) ! self.assertEqual(a-b, timedelta(6, 24*3600 - 60)) ! self.assertEqual(-a, timedelta(-7)) ! self.assertEqual(+a, timedelta(7)) ! self.assertEqual(-b, timedelta(-1, 24*3600 - 60)) ! self.assertEqual(-c, timedelta(-1, 24*3600 - 1, 999000)) ! self.assertEqual(abs(a), a) ! self.assertEqual(abs(-a), a) ! self.assertEqual(timedelta(6, 24*3600), a) ! self.assertEqual(timedelta(0, 0, 60*1000000), b) ! self.assertEqual(a*10, timedelta(70)) ! self.assertEqual(a*10, 10*a) ! self.assertEqual(a*10L, 10*a) ! self.assertEqual(b*10, timedelta(0, 600)) ! self.assertEqual(10*b, timedelta(0, 600)) ! self.assertEqual(b*10L, timedelta(0, 600)) ! self.assertEqual(c*10, timedelta(0, 0, 10000)) ! self.assertEqual(10*c, timedelta(0, 0, 10000)) ! self.assertEqual(c*10L, timedelta(0, 0, 10000)) ! self.assertEqual(a*-1, -a) ! self.assertEqual(b*-2, -b-b) ! self.assertEqual(c*-2, -c+-c) ! self.assertEqual(b*(60*24), (b*60)*24) ! self.assertEqual(b*(60*24), (60*b)*24) ! self.assertEqual(c*1000, timedelta(0, 1)) ! self.assertEqual(1000*c, timedelta(0, 1)) ! self.assertEqual(a//7, timedelta(1)) ! self.assertEqual(b//10, timedelta(0, 6)) ! self.assertEqual(c//1000, timedelta(0, 0, 1)) ! self.assertEqual(a//10, timedelta(0, 7*24*360)) ! self.assertEqual(a//3600000, timedelta(0, 0, 7*24*1000)) # Add/sub ints, longs, floats should be illegal for i in 1, 1L, 1.0: --- 41,83 ---- class TestTimeDelta(unittest.TestCase): ! def test_computations(self): ! eq = self.assertEqual ! td = timedelta ! ! a = td(7) # One week ! b = td(0, 60) # One minute ! c = td(0, 0, 1000) # One millisecond ! eq(a+b+c, td(7, 60, 1000)) ! eq(a-b, td(6, 24*3600 - 60)) ! eq(-a, td(-7)) ! eq(+a, td(7)) ! eq(-b, td(-1, 24*3600 - 60)) ! eq(-c, td(-1, 24*3600 - 1, 999000)) ! eq(abs(a), a) ! eq(abs(-a), a) ! eq(td(6, 24*3600), a) ! eq(td(0, 0, 60*1000000), b) ! eq(a*10, td(70)) ! eq(a*10, 10*a) ! eq(a*10L, 10*a) ! eq(b*10, td(0, 600)) ! eq(10*b, td(0, 600)) ! eq(b*10L, td(0, 600)) ! eq(c*10, td(0, 0, 10000)) ! eq(10*c, td(0, 0, 10000)) ! eq(c*10L, td(0, 0, 10000)) ! eq(a*-1, -a) ! eq(b*-2, -b-b) ! eq(c*-2, -c+-c) ! eq(b*(60*24), (b*60)*24) ! eq(b*(60*24), (60*b)*24) ! eq(c*1000, td(0, 1)) ! eq(1000*c, td(0, 1)) ! eq(a//7, td(1)) ! eq(b//10, td(0, 6)) ! eq(c//1000, td(0, 0, 1)) ! eq(a//10, td(0, 7*24*360)) ! eq(a//3600000, td(0, 0, 7*24*1000)) ! # Add/sub ints, longs, floats should be illegal for i in 1, 1L, 1.0: *************** *** 82,88 **** self.assertRaises(TypeError, lambda: i+a) self.assertRaises(TypeError, lambda: i-a) # Check keyword args to constructor - eq = self.assertEqual - td = timedelta eq(td(1), td(days=1)) eq(td(0, 1), td(seconds=1)) --- 86,91 ---- self.assertRaises(TypeError, lambda: i+a) self.assertRaises(TypeError, lambda: i-a) + # Check keyword args to constructor eq(td(1), td(days=1)) eq(td(0, 1), td(seconds=1)) *************** *** 94,97 **** --- 97,101 ---- eq(td(seconds=1), td(milliseconds=1000)) eq(td(milliseconds=1), td(microseconds=1000)) + # Check float args to constructor eq(td(weeks=1.0/7), td(days=1)) *************** *** 102,105 **** --- 106,116 ---- eq(td(milliseconds=0.001), td(microseconds=1)) + def test_basic_attributes(self): + days, seconds, us = 1, 7, 31 + td = timedelta(days, seconds, us) + self.assertEqual(td.days, days) + self.assertEqual(td.seconds, seconds) + self.assertEqual(td.microseconds, us) + def test_carries(self): t1 = timedelta(days=100, *************** *** 108,113 **** minutes=-3, seconds=12, ! microseconds=(3*60 - 12) * 1000000) ! t2 = timedelta() self.assertEqual(t1, t2) --- 119,124 ---- minutes=-3, seconds=12, ! microseconds=(3*60 - 12) * 1e6 + 1) ! t2 = timedelta(microseconds=1) self.assertEqual(t1, t2) *************** *** 130,133 **** --- 141,145 ---- d[t2] = 2 self.assertEqual(len(d), 1) + self.assertEqual(d[t1], 2) def test_pickling(self): From tim_one@users.sourceforge.net Tue Dec 3 00:20:50 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 02 Dec 2002 16:20:50 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.c,1.34,1.35 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv27761 Modified Files: datetime.c Log Message: Used MINYEAR macro in place of a hardcoded 1. Index: datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.c,v retrieving revision 1.34 retrieving revision 1.35 diff -C2 -d -r1.34 -r1.35 *** datetime.c 2 Dec 2002 21:50:55 -0000 1.34 --- datetime.c 3 Dec 2002 00:20:47 -0000 1.35 *************** *** 634,638 **** m = Py_InitModule3("_datetime", NULL, "Fast implementation of the datetime type."); ! PyModule_AddIntConstant(m, "MINYEAR", 1); PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR); Py_INCREF(&PyDateTime_DateType); --- 634,638 ---- m = Py_InitModule3("_datetime", NULL, "Fast implementation of the datetime type."); ! PyModule_AddIntConstant(m, "MINYEAR", MINYEAR); PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR); Py_INCREF(&PyDateTime_DateType); From tim_one@users.sourceforge.net Tue Dec 3 02:27:04 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 02 Dec 2002 18:27:04 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.c,1.35,1.36 obj_date.c,1.16,1.17 obj_datetime.c,1.11,1.12 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv15088 Modified Files: datetime.c obj_date.c obj_datetime.c Log Message: Following a suggestion from Fred, reworked pickling of date and datetime objects to get the copy_reg module involved. I'm not sure how much space this saves -- the pickler function still needs to create a tuple with an embedded tuple, and the name of the unpickler function gets stuffed into the pickle too (hmm -- since the unpickler function is registered with copy_reg, why does its name need to be repeated in the pickle?). The __reduce__ code is #if 0'ed out cuz I'm not sure this is an improvement. No matter how I cut this, pickling is painful. Index: datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.c,v retrieving revision 1.35 retrieving revision 1.36 diff -C2 -d -r1.35 -r1.36 *** datetime.c 3 Dec 2002 00:20:47 -0000 1.35 --- datetime.c 3 Dec 2002 02:27:01 -0000 1.36 *************** *** 536,540 **** } ! static PyObject* three_ones = NULL; /* an argument tuple for __reduce__ */ /* For obscure reasons, we need to use tp_richcompare instead of tp_compare. --- 536,545 ---- } ! #if 0 ! static PyObject *three_ones = NULL; /* an argument tuple for __reduce__ */ ! #endif ! ! static PyObject *date_unpickler_object = NULL; ! static PyObject *datetime_unpickler_object = NULL; /* For obscure reasons, we need to use tp_richcompare instead of tp_compare. *************** *** 567,570 **** --- 572,583 ---- #include "obj_datetime.c" + static PyMethodDef module_methods[] = { + {"_date_pickler", (PyCFunction)date_pickler, METH_O, NULL}, + {"_date_unpickler", (PyCFunction)date_unpickler, METH_O, NULL}, + {"_datetime_pickler", (PyCFunction)datetime_pickler, METH_O, NULL}, + {"_datetime_unpickler", (PyCFunction)datetime_unpickler,METH_O, NULL}, + {NULL, NULL} + }; + void init_datetime(void) *************** *** 632,636 **** /* module initialization */ ! m = Py_InitModule3("_datetime", NULL, "Fast implementation of the datetime type."); PyModule_AddIntConstant(m, "MINYEAR", MINYEAR); --- 645,649 ---- /* module initialization */ ! m = Py_InitModule3("_datetime", module_methods, "Fast implementation of the datetime type."); PyModule_AddIntConstant(m, "MINYEAR", MINYEAR); *************** *** 678,681 **** --- 691,735 ---- us_per_week = PyLong_FromDouble(604800000000.0); + /* Pickling support, via registering functions with copy_reg. */ + { + PyObject *temp; + PyObject *copyreg_pickle; + PyObject *pickler; + + temp = PyImport_ImportModule("copy_reg"); + assert(temp); + copyreg_pickle = PyObject_GetAttrString(temp, "pickle"); + assert(copyreg_pickle); + Py_DECREF(temp); + + pickler = PyObject_GetAttrString(m, "_date_pickler"); + assert(pickler); + date_unpickler_object = PyObject_GetAttrString(m, + "_date_unpickler"); + assert(date_unpickler_object); + temp = PyObject_CallFunction(copyreg_pickle, "OOO", + &PyDateTime_DateType, + pickler, + date_unpickler_object); + assert(temp); + Py_DECREF(temp); + Py_DECREF(pickler); + + pickler = PyObject_GetAttrString(m, "_datetime_pickler"); + assert(pickler); + datetime_unpickler_object = PyObject_GetAttrString(m, + "_datetime_unpickler"); + assert(datetime_unpickler_object); + temp = PyObject_CallFunction(copyreg_pickle, "OOO", + &PyDateTime_DateTimeType, + pickler, + datetime_unpickler_object); + assert(temp); + Py_DECREF(temp); + Py_DECREF(pickler); + + Py_DECREF(copyreg_pickle); + } + #if 0 { /* Build (1, 1, 1) so __reduce__ for date-like objects *************** *** 696,698 **** --- 750,753 ---- Py_DECREF(one); } + #endif } Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.16 retrieving revision 1.17 diff -C2 -d -r1.16 -r1.17 *** obj_date.c 2 Dec 2002 22:07:16 -0000 1.16 --- obj_date.c 3 Dec 2002 02:27:01 -0000 1.17 *************** *** 406,410 **** } ! /* XXX This is a ridiculously inefficient way to pickle a short string. */ static PyObject * date_reduce(PyDateTime_Date* self) --- 406,410 ---- } ! #if 0 static PyObject * date_reduce(PyDateTime_Date* self) *************** *** 423,426 **** --- 423,451 ---- return result; } + #endif + + /* XXX This seems a ridiculously inefficient way to pickle a short string. */ + static PyObject * + date_pickler(PyObject *module, PyDateTime_Date *date) + { + PyObject *state = date_getstate(date); + PyObject *tuple = Py_BuildValue("O(O)", + date_unpickler_object, state); + return tuple; + } + + static PyObject * + date_unpickler(PyObject *module, PyObject *arg) + { + PyDateTime_Date *self; + PyObject *res; + + self = PyObject_New(PyDateTime_Date, &PyDateTime_DateType); + if (self != NULL) { + res = date_setstate(self, arg); + Py_XDECREF(res); + } + return (PyObject *)self; + } static PyMethodDef date_methods[] = { *************** *** 452,457 **** --- 477,484 ---- {"__setstate__", (PyCFunction)date_setstate, METH_O, PyDoc_STR("__setstate__(state)")}, + #if 0 {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS, NULL}, + #endif {"__getstate__", (PyCFunction)date_getstate, METH_NOARGS, PyDoc_STR("__getstate__() -> state")}, Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** obj_datetime.c 2 Dec 2002 23:28:13 -0000 1.11 --- obj_datetime.c 3 Dec 2002 02:27:01 -0000 1.12 *************** *** 420,424 **** } ! /* XXX This is a ridiculously inefficient way to pickle a short string. */ static PyObject * datetime_reduce(PyDateTime_DateTime* self) --- 420,424 ---- } ! #if 0 static PyObject * datetime_reduce(PyDateTime_DateTime* self) *************** *** 437,440 **** --- 437,465 ---- return result; } + #endif + + /* XXX This seems a ridiculously inefficient way to pickle a short string. */ + static PyObject * + datetime_pickler(PyObject *module, PyDateTime_DateTime *datetime) + { + PyObject *state = datetime_getstate(datetime); + PyObject *tuple = Py_BuildValue("O(O)", + datetime_unpickler_object, state); + return tuple; + } + + static PyObject * + datetime_unpickler(PyObject *module, PyObject *arg) + { + PyDateTime_DateTime *self; + PyObject *res; + + self = PyObject_New(PyDateTime_DateTime, &PyDateTime_DateTimeType); + if (self != NULL) { + res = datetime_setstate(self, arg); + Py_XDECREF(res); + } + return (PyObject *)self; + } static PyMethodDef datetime_methods[] = { *************** *** 453,458 **** --- 478,485 ---- {"__setstate__", (PyCFunction)datetime_setstate, METH_O, PyDoc_STR("__setstate__(state)")}, + #if 0 {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS, NULL}, + #endif {"__getstate__", (PyCFunction)datetime_getstate, METH_NOARGS, PyDoc_STR("__getstate__() -> state")}, From tim.one@comcast.net Tue Dec 3 02:35:26 2002 From: tim.one@comcast.net (Tim Peters) Date: Mon, 02 Dec 2002 21:35:26 -0500 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_delta.c,1.14,1.15 test_both.py,1.15,1.16 In-Reply-To: <15851.54488.963027.945729@grendel.zope.com> Message-ID: [Fred L. Drake, Jr.] > You might be able to work with the copy_reg module instead of using > __reduce__. That's what I did for the parser module > (Modules/parsermodule.c). I don't know if that'll work for new-style > objects. It works, and I checked it in, but I'm not sure it's an improvement -- the pickler function still needs to produce a tuple with an embedded tuple, and the name of the unpickling function ends up in the pickle too. >>> from _datetime import * >>> import pickle >>> len(pickle.dumps(date(1, 1, 1), 1)) 45 >>> The *state* of the date object is 4 bytes. It's hard to swallow that administrative pickle bloat consumes 41 additional bytes. OTOH, it's a lot better than the bloat in the Python implementation: >>> import datetime >>> d = datetime.date(1, 1, 1) >>> len(pickle.dumps(d, 1)) 84 >>> From mhammond@users.sourceforge.net Tue Dec 3 05:39:52 2002 From: mhammond@users.sourceforge.net (mhammond@users.sourceforge.net) Date: Mon, 02 Dec 2002 21:39:52 -0800 Subject: [Python-checkins] python/dist/src/PCbuild pcbuild.dsw,1.29,1.30 Message-ID: Update of /cvsroot/python/python/dist/src/PCbuild In directory sc8-pr-cvs1:/tmp/cvs-serv17057 Modified Files: pcbuild.dsw Log Message: My MSVC seems to like writing the project names in quotes. Letting it do this before I add the _ssl project, so that checkin is cleaner. Index: pcbuild.dsw =================================================================== RCS file: /cvsroot/python/python/dist/src/PCbuild/pcbuild.dsw,v retrieving revision 1.29 retrieving revision 1.30 diff -C2 -d -r1.29 -r1.30 *** pcbuild.dsw 23 Nov 2002 18:48:06 -0000 1.29 --- pcbuild.dsw 3 Dec 2002 05:39:49 -0000 1.30 *************** *** 4,8 **** ############################################################################### ! Project: "_bsddb"=.\_bsddb.dsp - Package Owner=<4> Package=<5> --- 4,8 ---- ############################################################################### ! Project: "_bsddb"=".\_bsddb.dsp" - Package Owner=<4> Package=<5> *************** *** 19,23 **** ############################################################################### ! Project: "_socket"=.\_socket.dsp - Package Owner=<4> Package=<5> --- 19,23 ---- ############################################################################### ! Project: "_socket"=".\_socket.dsp" - Package Owner=<4> Package=<5> *************** *** 34,38 **** ############################################################################### ! Project: "_sre"=.\_sre.dsp - Package Owner=<4> Package=<5> --- 34,38 ---- ############################################################################### ! Project: "_sre"=".\_sre.dsp" - Package Owner=<4> Package=<5> *************** *** 49,53 **** ############################################################################### ! Project: "_symtable"=.\_symtable.dsp - Package Owner=<4> Package=<5> --- 49,53 ---- ############################################################################### ! Project: "_symtable"=".\_symtable.dsp" - Package Owner=<4> Package=<5> *************** *** 64,68 **** ############################################################################### ! Project: "_testcapi"=.\_testcapi.dsp - Package Owner=<4> Package=<5> --- 64,68 ---- ############################################################################### ! Project: "_testcapi"=".\_testcapi.dsp" - Package Owner=<4> Package=<5> *************** *** 79,83 **** ############################################################################### ! Project: "_tkinter"=.\_tkinter.dsp - Package Owner=<4> Package=<5> --- 79,83 ---- ############################################################################### ! Project: "_tkinter"=".\_tkinter.dsp" - Package Owner=<4> Package=<5> *************** *** 94,98 **** ############################################################################### ! Project: "bz2"=.\bz2.dsp - Package Owner=<4> Package=<5> --- 94,98 ---- ############################################################################### ! Project: "bz2"=".\bz2.dsp" - Package Owner=<4> Package=<5> *************** *** 106,110 **** ############################################################################### ! Project: "mmap"=.\mmap.dsp - Package Owner=<4> Package=<5> --- 106,110 ---- ############################################################################### ! Project: "mmap"=".\mmap.dsp" - Package Owner=<4> Package=<5> *************** *** 121,125 **** ############################################################################### ! Project: "parser"=.\parser.dsp - Package Owner=<4> Package=<5> --- 121,125 ---- ############################################################################### ! Project: "parser"=".\parser.dsp" - Package Owner=<4> Package=<5> *************** *** 136,140 **** ############################################################################### ! Project: "pyexpat"=.\pyexpat.dsp - Package Owner=<4> Package=<5> --- 136,140 ---- ############################################################################### ! Project: "pyexpat"=".\pyexpat.dsp" - Package Owner=<4> Package=<5> *************** *** 151,155 **** ############################################################################### ! Project: "python"=.\python.dsp - Package Owner=<4> Package=<5> --- 151,155 ---- ############################################################################### ! Project: "python"=".\python.dsp" - Package Owner=<4> Package=<5> *************** *** 166,170 **** ############################################################################### ! Project: "pythoncore"=.\pythoncore.dsp - Package Owner=<4> Package=<5> --- 166,170 ---- ############################################################################### ! Project: "pythoncore"=".\pythoncore.dsp" - Package Owner=<4> Package=<5> *************** *** 178,182 **** ############################################################################### ! Project: "pythonw"=.\pythonw.dsp - Package Owner=<4> Package=<5> --- 178,182 ---- ############################################################################### ! Project: "pythonw"=".\pythonw.dsp" - Package Owner=<4> Package=<5> *************** *** 193,197 **** ############################################################################### ! Project: "select"=.\select.dsp - Package Owner=<4> Package=<5> --- 193,197 ---- ############################################################################### ! Project: "select"=".\select.dsp" - Package Owner=<4> Package=<5> *************** *** 208,212 **** ############################################################################### ! Project: "unicodedata"=.\unicodedata.dsp - Package Owner=<4> Package=<5> --- 208,212 ---- ############################################################################### ! Project: "unicodedata"=".\unicodedata.dsp" - Package Owner=<4> Package=<5> *************** *** 223,227 **** ############################################################################### ! Project: "w9xpopen"=.\w9xpopen.dsp - Package Owner=<4> Package=<5> --- 223,227 ---- ############################################################################### ! Project: "w9xpopen"=".\w9xpopen.dsp" - Package Owner=<4> Package=<5> *************** *** 235,239 **** ############################################################################### ! Project: "winreg"=.\winreg.dsp - Package Owner=<4> Package=<5> --- 235,239 ---- ############################################################################### ! Project: "winreg"=".\winreg.dsp" - Package Owner=<4> Package=<5> *************** *** 250,254 **** ############################################################################### ! Project: "winsound"=.\winsound.dsp - Package Owner=<4> Package=<5> --- 250,254 ---- ############################################################################### ! Project: "winsound"=".\winsound.dsp" - Package Owner=<4> Package=<5> *************** *** 265,269 **** ############################################################################### ! Project: "zlib"=.\zlib.dsp - Package Owner=<4> Package=<5> --- 265,269 ---- ############################################################################### ! Project: "zlib"=".\zlib.dsp" - Package Owner=<4> Package=<5> From mhammond@users.sourceforge.net Tue Dec 3 05:47:28 2002 From: mhammond@users.sourceforge.net (mhammond@users.sourceforge.net) Date: Mon, 02 Dec 2002 21:47:28 -0800 Subject: [Python-checkins] python/dist/src/PCbuild _ssl.mak,NONE,1.1 _ssl.dsp,NONE,1.1 build_ssl.py,NONE,1.1 pcbuild.dsw,1.30,1.31 readme.txt,1.31,1.32 Message-ID: Update of /cvsroot/python/python/dist/src/PCbuild In directory sc8-pr-cvs1:/tmp/cvs-serv22359 Modified Files: pcbuild.dsw readme.txt Added Files: _ssl.mak _ssl.dsp build_ssl.py Log Message: Add _ssl build process for Windows. --- NEW FILE: _ssl.mak --- !IFDEF DEBUG MODULE=_ssl_d.pyd TEMP_DIR=x86-temp-debug/_ssl CFLAGS=/Od /Zi /MDd /LDd /DDEBUG /D_DEBUG SSL_LIB_DIR=$(SSL_DIR)/out32.dbg !ELSE MODULE=_ssl.pyd TEMP_DIR=x86-temp-release/_ssl CFLAGS=/Ox /MD /LD SSL_LIB_DIR=$(SSL_DIR)/out32 !ENDIF INCLUDES=-I ../Include -I ../PC -I $(SSL_DIR)/inc32 LIBS=gdi32.lib wsock32.lib /libpath:$(SSL_LIB_DIR) libeay32.lib ssleay32.lib SOURCE=../Modules/_ssl.c $(MODULE): $(SOURCE) ../PC/*.h ../Include/*.h cl /nologo $(SOURCE) $(CFLAGS) /Fo$(TEMP_DIR)\$*.obj $(INCLUDES) /link /out:$(MODULE) $(LIBS) --- NEW FILE: _ssl.dsp --- # Microsoft Developer Studio Project File - Name="_ssl" - Package Owner=<4> # Microsoft Developer Studio Generated Build File, Format Version 6.00 # ** DO NOT EDIT ** # TARGTYPE "Win32 (x86) External Target" 0x0106 CFG=_ssl - Win32 Debug !MESSAGE This is not a valid makefile. To build this project using NMAKE, !MESSAGE use the Export Makefile command and run !MESSAGE !MESSAGE NMAKE /f "_ssl.mak". !MESSAGE !MESSAGE You can specify a configuration when running NMAKE !MESSAGE by defining the macro CFG on the command line. For example: !MESSAGE !MESSAGE NMAKE /f "_ssl.mak" CFG="_ssl - Win32 Debug" !MESSAGE !MESSAGE Possible choices for configuration are: !MESSAGE !MESSAGE "_ssl - Win32 Release" (based on "Win32 (x86) External Target") !MESSAGE "_ssl - Win32 Debug" (based on "Win32 (x86) External Target") !MESSAGE # Begin Project # PROP AllowPerConfigDependencies 0 # PROP Scc_ProjName "" # PROP Scc_LocalPath "" !IF "$(CFG)" == "_ssl - Win32 Release" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 0 # PROP BASE Output_Dir "Release" # PROP BASE Intermediate_Dir "Release" # PROP BASE Cmd_Line "NMAKE /f _ssl.mak" # PROP BASE Rebuild_Opt "/a" # PROP BASE Target_File "_ssl.exe" # PROP BASE Bsc_Name "_ssl.bsc" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 0 # PROP Output_Dir "." # PROP Intermediate_Dir "x86-temp-release\_ssl" # PROP Cmd_Line "python build_ssl.py" # PROP Rebuild_Opt "-a" # PROP Target_File "_ssl.pyd" # PROP Bsc_Name "" # PROP Target_Dir "" !ELSEIF "$(CFG)" == "_ssl - Win32 Debug" # PROP BASE Use_MFC 0 # PROP BASE Use_Debug_Libraries 1 # PROP BASE Output_Dir "x86-temp-debug\_ssl" # PROP BASE Intermediate_Dir "x86-temp-debug\_ssl" # PROP BASE Cmd_Line "NMAKE /f _ssl.mak" # PROP BASE Rebuild_Opt "/a" # PROP BASE Target_File "_ssl_d.pyd" # PROP BASE Bsc_Name "_ssl_d.bsc" # PROP BASE Target_Dir "" # PROP Use_MFC 0 # PROP Use_Debug_Libraries 1 # PROP Output_Dir "." # PROP Intermediate_Dir "x86-temp-debug\_ssl" # PROP Cmd_Line "python -u build_ssl.py -d" # PROP Rebuild_Opt "-a" # PROP Target_File "_ssl_d.pyd" # PROP Bsc_Name "" # PROP Target_Dir "" !ENDIF # Begin Target # Name "_ssl - Win32 Release" # Name "_ssl - Win32 Debug" !IF "$(CFG)" == "_ssl - Win32 Release" !ELSEIF "$(CFG)" == "_ssl - Win32 Debug" !ENDIF # Begin Source File SOURCE=..\Modules\_ssl.c # End Source File # End Target # End Project --- NEW FILE: build_ssl.py --- # Script for building the _ssl module for Windows. # Uses Perl to setup the OpenSSL environment correctly # and build OpenSSL, then invokes a simple nmake session # for _ssl.pyd itself. # THEORETICALLY, you can: # * Unpack the latest SSL release one level above your main Python source # directory. It is likely you will already find the zlib library and # any other external packages there. # * Install ActivePerl and ensure it is somewhere on your path. # * Run this script from the PCBuild directory. # # it should configure and build SSL, then build the ssl Python extension # without intervention. import os, sys, re # Find all "foo.exe" files on the PATH. def find_all_on_path(filename, extras = None): entries = os.environ["PATH"].split(os.pathsep) ret = [] for p in entries: fname = os.path.abspath(os.path.join(p, filename)) if os.path.isfile(fname) and fname not in ret: ret.append(fname) if extras: for p in extras: fname = os.path.abspath(os.path.join(p, filename)) if os.path.isfile(fname) and fname not in ret: ret.append(fname) return ret # Find a suitable Perl installation for OpenSSL. # cygwin perl does *not* work. ActivePerl does. # Being a Perl dummy, the simplest way I can check is if the "Win32" package # is available. def find_working_perl(perls): for perl in perls: fh = os.popen(perl + ' -e "use Win32;"') fh.read() rc = fh.close() if rc: continue return perl print "Can not find a suitable PERL:" if perls: print " the following perl interpreters were found:" for p in perls: print " ", p print " None of these versions appear suitable for building OpenSSL" else: print " NO perl interpreters were found on this machine at all!" print " Please install ActivePerl and ensure it appears on your path" print "The Python SSL module was not built" return None # Locate the best SSL directory given a few roots to look into. def find_best_ssl_dir(sources): candidates = [] for s in sources: try: s = os.path.abspath(s) fnames = os.listdir(s) except os.error: fnames = [] for fname in fnames: fqn = os.path.join(s, fname) if os.path.isdir(fqn) and fname.startswith("openssl-"): candidates.append(fqn) # Now we have all the candidates, locate the best. best_parts = [] best_name = None for c in candidates: parts = re.split("[.-]", os.path.basename(c))[1:] # eg - openssl-0.9.7-beta1 - ignore all "beta" or any other qualifiers if len(parts) >= 4: continue if parts > best_parts: best_parts = parts best_name = c if best_name is not None: print "Found an SSL directory at '%s'" % (best_name,) else: print "Could not find an SSL directory in '%s'" % (sources,) return best_name def main(): debug = "-d" in sys.argv build_all = "-a" in sys.argv make_flags = "" if build_all: make_flags = "-a" # perl should be on the path, but we also look in "\perl" and "c:\\perl" # as "well known" locations perls = find_all_on_path("perl.exe", ["\\perl\\bin", "C:\\perl\\bin"]) perl = find_working_perl(perls) if perl is None: sys.exit(1) print "Found a working perl at '%s'" % (perl,) # Look for SSL 2 levels up from pcbuild - ie, same place zlib etc all live. ssl_dir = find_best_ssl_dir(("../..",)) if ssl_dir is None: sys.exit(1) old_cd = os.getcwd() try: os.chdir(ssl_dir) # If the ssl makefiles do not exist, we invoke Perl to generate them. if not os.path.isfile(os.path.join(ssl_dir, "32.mak")) or \ not os.path.isfile(os.path.join(ssl_dir, "d32.mak")): print "Creating the makefiles..." # Put our working Perl at the front of our path os.environ["PATH"] = os.path.split(perl)[0] + \ os.pathsep + \ os.environ["PATH"] rc = os.system("ms\\32all.bat") # Now run make. print "Executing nmake over the ssl makefiles..." if debug: rc = os.system("nmake /nologo -f d32.mak") if rc: print "Executing d32.mak failed" print rc sys.exit(rc) else: rc = os.system("nmake /nologo -f 32.mak") if rc: print "Executing 32.mak failed" print rc sys.exit(rc) finally: os.chdir(old_cd) # And finally, we can build the _ssl module itself for Python. defs = "SSL_DIR=%s" % (ssl_dir,) if debug: defs = defs + " " + "DEBUG=1" rc = os.system('nmake /nologo -f _ssl.mak ' + defs + " " + make_flags) sys.exit(rc) if __name__=='__main__': main() Index: pcbuild.dsw =================================================================== RCS file: /cvsroot/python/python/dist/src/PCbuild/pcbuild.dsw,v retrieving revision 1.30 retrieving revision 1.31 diff -C2 -d -r1.30 -r1.31 *** pcbuild.dsw 3 Dec 2002 05:39:49 -0000 1.30 --- pcbuild.dsw 3 Dec 2002 05:47:26 -0000 1.31 *************** *** 49,52 **** --- 49,73 ---- ############################################################################### + Project: "_ssl"=".\_ssl.dsp" - Package Owner=<4> + + Package=<5> + {{{ + }}} + + Package=<4> + {{{ + Begin Project Dependency + Project_Dep_Name pythoncore + End Project Dependency + Begin Project Dependency + Project_Dep_Name _sre + End Project Dependency + Begin Project Dependency + Project_Dep_Name python + End Project Dependency + }}} + + ############################################################################### + Project: "_symtable"=".\_symtable.dsp" - Package Owner=<4> Index: readme.txt =================================================================== RCS file: /cvsroot/python/python/dist/src/PCbuild/readme.txt,v retrieving revision 1.31 retrieving revision 1.32 diff -C2 -d -r1.31 -r1.32 *** readme.txt 23 Nov 2002 18:48:06 -0000 1.31 --- readme.txt 3 Dec 2002 05:47:26 -0000 1.32 *************** *** 200,204 **** --- 200,234 ---- XXX This isn't encouraging, but I don't know what to do about it. + _ssl + Python wrapper for the secure sockets library. + + Get the latest source code for OpenSSL from + http://www.openssl.org + + Unpack into the "dist" directory, retaining the folder name from + the archive - for example, the latest stable OpenSSL will install as + dist/openssl-0.9.6g + + You can (theoretically) use any version of OpenSSL you like - the + build process will automatically select the latest version. + + You must also install ActivePerl from + http://www.activestate.com/Products/ActivePerl/ + as this is used by the OpenSSL build process. Complain to them + + The MSVC project simply invokes PCBuild/build_ssl.py to perform + the build. This Python script locates and builds your OpenSSL + installation, then invokes a simple makefile to build the final .pyd. + build_ssl.py attempts to catch the most common errors (such as not + being able to find OpenSSL sources, or not being able to find a Perl + that works with OpenSSL) and give a reasonable error message. + If you have a problem that doesn't seem to be handled correctly + (eg, you know you have ActivePerl but we can't find it), please take + a peek at build_ssl.py and suggest patches. Note that build_ssl.py + should be able to be run directly from the command-line. + + build_ssl.py/MSVC isn't clever enough to clean OpenSSL - you must do this + by hand. YOUR OWN EXTENSION DLLs From mhammond@users.sourceforge.net Tue Dec 3 06:03:02 2002 From: mhammond@users.sourceforge.net (mhammond@users.sourceforge.net) Date: Mon, 02 Dec 2002 22:03:02 -0800 Subject: [Python-checkins] python/dist/src/PCbuild python20.wse,1.108,1.109 Message-ID: Update of /cvsroot/python/python/dist/src/PCbuild In directory sc8-pr-cvs1:/tmp/cvs-serv32305 Modified Files: python20.wse Log Message: Add _ssl.pyd to the list of files to be installed by Wise. Index: python20.wse =================================================================== RCS file: /cvsroot/python/python/dist/src/PCbuild/python20.wse,v retrieving revision 1.108 retrieving revision 1.109 diff -C2 -d -r1.108 -r1.109 *** python20.wse 23 Nov 2002 18:48:06 -0000 1.108 --- python20.wse 3 Dec 2002 06:02:59 -0000 1.109 *************** *** 1701,1704 **** --- 1701,1709 ---- end item: Install File + Source=.\_ssl.pyd + Destination=%MAINDIR%\DLLs\_ssl.pyd + Flags=0000000000000010 + end + item: Install File Source=.\_sre.pyd Destination=%MAINDIR%\DLLs\_sre.pyd From mhammond@users.sourceforge.net Tue Dec 3 06:13:37 2002 From: mhammond@users.sourceforge.net (mhammond@users.sourceforge.net) Date: Mon, 02 Dec 2002 22:13:37 -0800 Subject: [Python-checkins] python/dist/src/Doc/whatsnew whatsnew23.tex,1.81,1.82 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/whatsnew In directory sc8-pr-cvs1:/tmp/cvs-serv6757 Modified Files: whatsnew23.tex Log Message: _ssl.pyd available for Windows. Index: whatsnew23.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/whatsnew/whatsnew23.tex,v retrieving revision 1.81 retrieving revision 1.82 diff -C2 -d -r1.81 -r1.82 *** whatsnew23.tex 1 Dec 2002 14:00:21 -0000 1.81 --- whatsnew23.tex 3 Dec 2002 06:13:35 -0000 1.82 *************** *** 1220,1223 **** --- 1220,1226 ---- software development process in action. + \item On Windows, the \module{socket} module now ships with Secure + Sockets Library (SSL) support. + \item The value of the C \constant{PYTHON_API_VERSION} macro is now exposed at the Python level as \code{sys.api_version}. From mhammond@users.sourceforge.net Tue Dec 3 06:16:11 2002 From: mhammond@users.sourceforge.net (mhammond@users.sourceforge.net) Date: Mon, 02 Dec 2002 22:16:11 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.551,1.552 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv8508 Modified Files: NEWS Log Message: _ssl.pyd added for Windows. Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.551 retrieving revision 1.552 diff -C2 -d -r1.551 -r1.552 *** NEWS 1 Dec 2002 21:43:13 -0000 1.551 --- NEWS 3 Dec 2002 06:16:08 -0000 1.552 *************** *** 852,855 **** --- 852,858 ---- XXX I'm still not sure how to link this thing (see PCbuild/readme.txt). XXX The version # is likely to change before 2.3a1. + + - The Windows distribution now ships with a Secure Sockets Library (SLL) + module (_ssl.pyd) - The Windows distribution now ships with Tcl/Tk version 8.4.1 (it From mhammond@users.sourceforge.net Tue Dec 3 06:29:50 2002 From: mhammond@users.sourceforge.net (mhammond@users.sourceforge.net) Date: Mon, 02 Dec 2002 22:29:50 -0800 Subject: [Python-checkins] python/dist/src/PCbuild _ssl.mak,1.1,1.2 Message-ID: Update of /cvsroot/python/python/dist/src/PCbuild In directory sc8-pr-cvs1:/tmp/cvs-serv17371 Modified Files: _ssl.mak Log Message: Ensure the ssl temp directory exists! Index: _ssl.mak =================================================================== RCS file: /cvsroot/python/python/dist/src/PCbuild/_ssl.mak,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** _ssl.mak 3 Dec 2002 05:47:26 -0000 1.1 --- _ssl.mak 3 Dec 2002 06:29:48 -0000 1.2 *************** *** 18,20 **** --- 18,21 ---- $(MODULE): $(SOURCE) ../PC/*.h ../Include/*.h + @if not exist "$(TEMP_DIR)/." mkdir "$(TEMP_DIR)" cl /nologo $(SOURCE) $(CFLAGS) /Fo$(TEMP_DIR)\$*.obj $(INCLUDES) /link /out:$(MODULE) $(LIBS) From gvanrossum@users.sourceforge.net Tue Dec 3 08:14:37 2002 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 03 Dec 2002 00:14:37 -0800 Subject: [Python-checkins] python/dist/src/Lib pyclbr.py,1.29,1.30 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv6177 Modified Files: pyclbr.py Log Message: Another big update, fixing all known bugs related to nesting functions and classes. Also add a mini main program that dumps the results for a given file or module. Index: pyclbr.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/pyclbr.py,v retrieving revision 1.29 retrieving revision 1.30 diff -C2 -d -r1.29 -r1.30 *** pyclbr.py 2 Dec 2002 14:54:19 -0000 1.29 --- pyclbr.py 3 Dec 2002 08:14:35 -0000 1.30 *************** *** 1,17 **** ! """Parse a Python file and retrieve classes and methods. ! Parse enough of a Python file to recognize class and method ! definitions and to find out the superclasses of a class. The interface consists of a single function: ! readmodule_ex(module [, path[, inpackage]]) ! module is the name of a Python module, path is an optional list of ! directories where the module is to be searched. If present, path is ! prepended to the system search path sys.path. (inpackage is used ! internally to search for a submodule of a package.) ! The return value is a dictionary. The keys of the dictionary are ! the names of the classes defined in the module (including classes ! that are defined via the from XXX import YYY construct). The values ! are class instances of the class Class defined here. A class is described by the class Class in this module. Instances --- 1,18 ---- ! """Parse a Python module and describe its classes and methods. ! Parse enough of a Python file to recognize imports and class and ! method definitions, and to find out the superclasses of a class. The interface consists of a single function: ! readmodule_ex(module [, path]) ! where module is the name of a Python module, and path is an optional ! list of directories where the module is to be searched. If present, ! path is prepended to the system search path sys.path. The return ! value is a dictionary. The keys of the dictionary are the names of ! the classes defined in the module (including classes that are defined ! via the from XXX import YYY construct). The values are class ! instances of the class Class defined here. One special key/value pair ! is present for packages: the key '__path__' has a list as its value ! which contains the package search path. A class is described by the class Class in this module. Instances *************** *** 37,49 **** file -- the file in which the class was defined lineno -- the line in the file on which the class statement occurred - - - BUGS - - Nested classes and functions can confuse it. - - PACKAGE CAVEAT - - When you call readmodule_ex for a package, dict['__path__'] is a - list, which may confuse older class browsers. (readmodule filters - these out though.) """ --- 38,41 ---- *************** *** 51,55 **** import imp import tokenize # Python tokenizer ! from token import NAME __all__ = ["readmodule", "readmodule_ex", "Class", "Function"] --- 43,47 ---- import imp import tokenize # Python tokenizer ! from token import NAME, DEDENT, NEWLINE __all__ = ["readmodule", "readmodule_ex", "Class", "Function"] *************** *** 87,91 **** resulting dictionary.''' ! dict = readmodule_ex(module, path) res = {} for key, value in dict.items(): --- 79,83 ---- resulting dictionary.''' ! dict = _readmodule(module, path) res = {} for key, value in dict.items(): *************** *** 94,98 **** return res ! def readmodule_ex(module, path=[], inpackage=None): '''Read a module file and return a dictionary of classes. --- 86,90 ---- return res ! def readmodule_ex(module, path=[]): '''Read a module file and return a dictionary of classes. *************** *** 106,110 **** --- 98,105 ---- module, and PATH is combined with sys.path. ''' + return _readmodule(module, path) + def _readmodule(module, path, inpackage=None): + '''Do the hard work for readmodule[_ex].''' # Compute the full module name (prepending inpackage if set) if inpackage: *************** *** 130,137 **** package = module[:i] submodule = module[i+1:] ! parent = readmodule_ex(package, path, inpackage) if inpackage: package = "%s.%s" % (inpackage, package) ! return readmodule_ex(submodule, parent['__path__'], package) # Search the path for the module --- 125,132 ---- package = module[:i] submodule = module[i+1:] ! parent = _readmodule(package, path, inpackage) if inpackage: package = "%s.%s" % (inpackage, package) ! return _readmodule(submodule, parent['__path__'], package) # Search the path for the module *************** *** 151,184 **** return dict ! classstack = [] # stack of (class, indent) pairs g = tokenize.generate_tokens(f.readline) try: for tokentype, token, start, end, line in g: ! if token == 'def': lineno, thisindent = start tokentype, meth_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error ! # close all classes indented at least as much ! while classstack and \ ! classstack[-1][1] >= thisindent: ! del classstack[-1] ! if classstack: ! # it's a class method ! cur_class = classstack[-1][0] ! cur_class._addmethod(meth_name, lineno) else: # it's a function dict[meth_name] = Function(module, meth_name, file, lineno) elif token == 'class': lineno, thisindent = start tokentype, class_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error - # close all classes indented at least as much - while classstack and \ - classstack[-1][1] >= thisindent: - del classstack[-1] # parse what follows the class name tokentype, token, start, end, line = g.next() --- 146,185 ---- return dict ! stack = [] # stack of (class, indent) pairs g = tokenize.generate_tokens(f.readline) try: for tokentype, token, start, end, line in g: ! if tokentype == DEDENT: ! lineno, thisindent = start ! # close nested classes and defs ! while stack and stack[-1][1] >= thisindent: ! del stack[-1] ! elif token == 'def': lineno, thisindent = start + # close previous nested classes and defs + while stack and stack[-1][1] >= thisindent: + del stack[-1] tokentype, meth_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error ! if stack: ! cur_class = stack[-1][0] ! if isinstance(cur_class, Class): ! # it's a method ! cur_class._addmethod(meth_name, lineno) ! # else it's a nested def else: # it's a function dict[meth_name] = Function(module, meth_name, file, lineno) + stack.append((None, thisindent)) # Marker for nested fns elif token == 'class': lineno, thisindent = start + # close previous nested classes and defs + while stack and stack[-1][1] >= thisindent: + del stack[-1] tokentype, class_name, start, end, line = g.next() if tokentype != NAME: continue # Syntax error # parse what follows the class name tokentype, token, start, end, line = g.next() *************** *** 209,212 **** --- 210,214 ---- n = d[c] names.append(n) + super = [] if token == '(': level += 1 *************** *** 221,226 **** inherit = names cur_class = Class(module, class_name, inherit, file, lineno) ! dict[class_name] = cur_class ! classstack.append((cur_class, thisindent)) elif token == 'import' and start[1] == 0: modules = _getnamelist(g) --- 223,229 ---- inherit = names cur_class = Class(module, class_name, inherit, file, lineno) ! if not stack: ! dict[class_name] = cur_class ! stack.append((cur_class, thisindent)) elif token == 'import' and start[1] == 0: modules = _getnamelist(g) *************** *** 229,238 **** # Recursively read the imported module if not inpackage: ! readmodule_ex(mod, path) else: try: ! readmodule_ex(mod, path, inpackage) except ImportError: ! readmodule_ex(mod) except: # If we can't find or parse the imported module, --- 232,241 ---- # Recursively read the imported module if not inpackage: ! _readmodule(mod, path) else: try: ! _readmodule(mod, path, inpackage) except ImportError: ! _readmodule(mod, []) except: # If we can't find or parse the imported module, *************** *** 246,250 **** try: # Recursively read the imported module ! d = readmodule_ex(mod, path, inpackage) except: # If we can't find or parse the imported module, --- 249,253 ---- try: # Recursively read the imported module ! d = _readmodule(mod, path, inpackage) except: # If we can't find or parse the imported module, *************** *** 257,265 **** dict[n2 or n] = d[n] elif n == '*': ! # only add a name if not already there (to mimic ! # what Python does internally) also don't add ! # names that start with _ for n in d: ! if n[0] != '_' and not n in dict: dict[n] = d[n] except StopIteration: --- 260,266 ---- dict[n2 or n] = d[n] elif n == '*': ! # don't add names that start with _ for n in d: ! if n[0] != '_': dict[n] = d[n] except StopIteration: *************** *** 307,308 **** --- 308,338 ---- parts.append(token) return (".".join(parts), token) + + def _main(): + # Main program for testing. + import os + mod = sys.argv[1] + if os.path.exists(mod): + path = [os.path.dirname(mod)] + mod = os.path.basename(mod) + if mod.lower().endswith(".py"): + mod = mod[:-3] + else: + path = [] + dict = readmodule_ex(mod, path) + objs = dict.values() + objs.sort(lambda a, b: cmp(getattr(a, 'lineno', 0), + getattr(b, 'lineno', 0))) + for obj in objs: + if isinstance(obj, Class): + print "class", obj.name, obj.super, obj.lineno + methods = obj.methods.items() + methods.sort(lambda a, b: cmp(a[1], b[1])) + for name, lineno in methods: + if name != "__path__": + print " def", name, lineno + elif isinstance(obj, Function): + print "def", obj.name, obj.lineno + + if __name__ == "__main__": + _main() From gvanrossum@users.sourceforge.net Tue Dec 3 08:16:53 2002 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 03 Dec 2002 00:16:53 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_pyclbr.py,1.13,1.14 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv6788 Modified Files: test_pyclbr.py Log Message: Add more sophistication to the comparison between pyclbr output and real module, by filtering out aliased methods. This, combined with the recent fixes to pyclbr, make it possible to enable more tests with fewer exceptions. Index: test_pyclbr.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_pyclbr.py,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** test_pyclbr.py 2 Dec 2002 14:54:20 -0000 1.13 --- test_pyclbr.py 3 Dec 2002 08:16:50 -0000 1.14 *************** *** 24,27 **** --- 24,29 ---- def assertListEq(self, l1, l2, ignore): ''' succeed iff {l1} - {ignore} == {l2} - {ignore} ''' + l1.sort() + l2.sort() try: for p1, p2 in (l1, l2), (l2, l1): *************** *** 31,35 **** self.fail("%r missing" % item) except: ! print >>sys.stderr, "l1=%r, l2=%r, ignore=%r" % (l1, l2, ignore) raise --- 33,37 ---- self.fail("%r missing" % item) except: ! print >>sys.stderr, "l1=%r\nl2=%r\nignore=%r" % (l1, l2, ignore) raise *************** *** 68,71 **** --- 70,83 ---- dict = pyclbr.readmodule_ex(moduleName) + def ismethod(obj, name): + if not isinstance(obj, MethodType): + return False + if obj.im_self is not None: + return False + objname = obj.__name__ + if objname.startswith("__") and not objname.endswith("__"): + objname = "_%s%s" % (obj.im_class.__name__, objname) + return objname == name + # Make sure the toplevel functions and classes are the same. for name, value in dict.items(): *************** *** 90,94 **** actualMethods = [] for m in py_item.__dict__.keys(): ! if type(getattr(py_item, m)) == MethodType: actualMethods.append(m) foundMethods = [] --- 102,106 ---- actualMethods = [] for m in py_item.__dict__.keys(): ! if ismethod(getattr(py_item, m), m): actualMethods.append(m) foundMethods = [] *************** *** 99,107 **** foundMethods.append(m) ! self.assertListEq(foundMethods, actualMethods, ignore) ! self.assertEquals(py_item.__module__, value.module) ! self.assertEquals(py_item.__name__, value.name, ignore) ! # can't check file or lineno # Now check for missing stuff. --- 111,123 ---- foundMethods.append(m) ! try: ! self.assertListEq(foundMethods, actualMethods, ignore) ! self.assertEquals(py_item.__module__, value.module) ! self.assertEquals(py_item.__name__, value.name, ignore) ! # can't check file or lineno ! except: ! print >>sys.stderr, "class=%s" % py_item ! raise # Now check for missing stuff. *************** *** 120,129 **** def test_easy(self): self.checkModule('pyclbr') ! self.checkModule('doctest', ! ignore=['_isclass', ! '_isfunction', ! '_ismodule', ! '_classify_class_attrs']) ! self.checkModule('rfc822', ignore=["get"]) self.checkModule('difflib') --- 136,141 ---- def test_easy(self): self.checkModule('pyclbr') ! self.checkModule('doctest') ! self.checkModule('rfc822') self.checkModule('difflib') *************** *** 131,168 **** cm = self.checkModule ! # these are about the 20 longest modules. ! cm('random', ignore=('_verify',)) # deleted ! ! cm('cgi', ignore=('f', 'g', # nested declarations ! 'log')) # set with =, not def ! ! cm('mhlib', ignore=('do', # nested declaration ! 'bisect')) # imported method, set with = ! ! cm('urllib', ignore=('getproxies_environment', # set with = ! 'getproxies_registry', # set with = ! 'open_https')) # not on all platforms ! ! cm('pickle', ignore=('g',)) # deleted declaration ! ! cm('aifc', ignore=('openfp',)) # set with = ! ! cm('Cookie', ignore=('__str__', 'Cookie')) # set with = ! ! cm('sre_parse', ignore=('literal', # nested def ! 'makedict', 'dump' # from sre_constants ! )) # Tests for modules inside packages cm('email.Parser') ! ! cm('test.test_pyclbr', ignore=('defined_in',)) ! ! # pydoc doesn't work because of string issues ! # cm('pydoc', pydoc) ! ! # pdb plays too many dynamic games ! # cm('pdb', pdb) --- 143,162 ---- cm = self.checkModule ! # These were once about the 10 longest modules cm('random', ignore=('_verify',)) # deleted ! cm('cgi', ignore=('log',)) # set with = in module ! cm('mhlib') ! cm('urllib', ignore=('getproxies_registry', ! 'open_https')) # not on all platforms ! cm('pickle', ignore=('g',)) # from types import * ! cm('aifc', ignore=('openfp',)) # set with = in module ! cm('Cookie') ! cm('sre_parse', ignore=('dump',)) # from sre_constants import * ! cm('pdb') ! cm('pydoc') # Tests for modules inside packages cm('email.Parser') ! cm('test.test_pyclbr') From lemburg@users.sourceforge.net Tue Dec 3 08:45:14 2002 From: lemburg@users.sourceforge.net (lemburg@users.sourceforge.net) Date: Tue, 03 Dec 2002 00:45:14 -0800 Subject: [Python-checkins] python/dist/src/Lib/distutils util.py,1.71,1.72 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/distutils In directory sc8-pr-cvs1:/tmp/cvs-serv14903 Modified Files: util.py Log Message: Adding Python <= 2.2 support back in. Index: util.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/distutils/util.py,v retrieving revision 1.71 retrieving revision 1.72 diff -C2 -d -r1.71 -r1.72 *** util.py 14 Nov 2002 02:25:42 -0000 1.71 --- util.py 3 Dec 2002 08:45:11 -0000 1.72 *************** *** 360,368 **** # run it with the appropriate flags. if not direct: ! from tempfile import mkstemp ! (script_fd, script_name) = mkstemp(".py") log.info("writing byte-compilation script '%s'", script_name) if not dry_run: ! script = os.fdopen(script_fd, "w") script.write("""\ --- 360,375 ---- # run it with the appropriate flags. if not direct: ! try: ! from tempfile import mkstemp ! (script_fd, script_name) = mkstemp(".py") ! except ImportError: ! from tempfile import mktemp ! (script_fd, script_name) = None, mktemp(".py") log.info("writing byte-compilation script '%s'", script_name) if not dry_run: ! if script_fd is not None: ! script = os.fdopen(script_fd, "w") ! else: ! script = open(script_name, "w") script.write("""\ From gvanrossum@users.sourceforge.net Tue Dec 3 09:28:38 2002 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 03 Dec 2002 01:28:38 -0800 Subject: [Python-checkins] python/dist/src/Tools/idle ClassBrowser.py,1.13,1.14 Message-ID: Update of /cvsroot/python/python/dist/src/Tools/idle In directory sc8-pr-cvs1:/tmp/cvs-serv27460 Modified Files: ClassBrowser.py Log Message: Get rid of 1.5.2 compatibility hack. :-) Index: ClassBrowser.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Tools/idle/ClassBrowser.py,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** ClassBrowser.py 11 Sep 2002 20:36:01 -0000 1.13 --- ClassBrowser.py 3 Dec 2002 09:28:36 -0000 1.14 *************** *** 15,26 **** import pyclbr - # XXX Patch pyclbr with dummies if it's vintage Python 1.5.2: - if not hasattr(pyclbr, "readmodule_ex"): - pyclbr.readmodule_ex = pyclbr.readmodule - if not hasattr(pyclbr, "Function"): - class Function(pyclbr.Class): - pass - pyclbr.Function = Function - import PyShell from WindowList import ListedToplevel --- 15,18 ---- From gvanrossum@users.sourceforge.net Tue Dec 3 09:34:56 2002 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 03 Dec 2002 01:34:56 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_sundry.py,1.11,1.12 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv28923 Modified Files: test_sundry.py Log Message: Lose references to knee (no longer exists) and pyclbr (has its own test suite now). Index: test_sundry.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_sundry.py,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** test_sundry.py 23 Jul 2002 19:04:05 -0000 1.11 --- test_sundry.py 3 Dec 2002 09:34:54 -0000 1.12 *************** *** 52,56 **** import imputil import keyword - #import knee import macpath import macurl2path --- 52,55 ---- *************** *** 71,75 **** import pstats import py_compile - import pyclbr #import reconvert import repr --- 70,73 ---- From gvanrossum@users.sourceforge.net Tue Dec 3 10:24:58 2002 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Tue, 03 Dec 2002 02:24:58 -0800 Subject: [Python-checkins] python/dist/src/Lib/test regrtest.py,1.108,1.109 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv19106 Modified Files: regrtest.py Log Message: Some more expected skips on OSX. Index: regrtest.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/regrtest.py,v retrieving revision 1.108 retrieving revision 1.109 diff -C2 -d -r1.108 -r1.109 *** regrtest.py 2 Dec 2002 09:56:21 -0000 1.108 --- regrtest.py 3 Dec 2002 10:24:56 -0000 1.109 *************** *** 754,761 **** --- 754,763 ---- """ test_al + test_bsddb3 test_cd test_cl test_curses test_dl + test_email_codecs test_gdbm test_gl *************** *** 764,767 **** --- 766,770 ---- test_linuxaudiodev test_minidom + test_mpz test_nis test_ntpath From akuchling@users.sourceforge.net Tue Dec 3 13:35:20 2002 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Tue, 03 Dec 2002 05:35:20 -0800 Subject: [Python-checkins] python/dist/src/Doc/whatsnew whatsnew23.tex,1.82,1.83 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/whatsnew In directory sc8-pr-cvs1:/tmp/cvs-serv7641 Modified Files: whatsnew23.tex Log Message: Bug #647387: corrections to the logging section by Vinay Sanjip Index: whatsnew23.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/whatsnew/whatsnew23.tex,v retrieving revision 1.82 retrieving revision 1.83 diff -C2 -d -r1.82 -r1.83 *** whatsnew23.tex 3 Dec 2002 06:13:35 -0000 1.82 --- whatsnew23.tex 3 Dec 2002 13:35:17 -0000 1.83 *************** *** 434,439 **** \samp{server} or direct \samp{server} messages to a different handler, the changes will also apply to records logged to \samp{server.auth} ! and \samp{server.network}. There's also a root \class{Logger} with ! the name \samp{root} that's the parent of all other loggers. For simple uses, the \module{logging} package contains some --- 434,439 ---- \samp{server} or direct \samp{server} messages to a different handler, the changes will also apply to records logged to \samp{server.auth} ! and \samp{server.network}. There's also a root \class{Logger} that's ! the parent of all other loggers. For simple uses, the \module{logging} package contains some *************** *** 445,449 **** logging.debug('Debugging information') logging.info('Informational message') ! logging.warn('Warning: config file %s not found', 'server.conf') logging.error('Error occurred') logging.critical('Critical error -- shutting down') --- 445,449 ---- logging.debug('Debugging information') logging.info('Informational message') ! logging.warn('Warning:config file %s not found', 'server.conf') logging.error('Error occurred') logging.critical('Critical error -- shutting down') *************** *** 453,457 **** \begin{verbatim} ! WARN:root:Warning: config file not found ERROR:root:Error occurred CRITICAL:root:Critical error -- shutting down --- 453,457 ---- \begin{verbatim} ! WARN:root:Warning:config file server.conf not found ERROR:root:Error occurred CRITICAL:root:Critical error -- shutting down *************** *** 493,497 **** Slightly more advanced programs will use a logger other than the root logger. The \function{getLogger(\var{name})} is used to get a ! particular log, creating it if it doesn't exist yet. \begin{verbatim} --- 493,499 ---- Slightly more advanced programs will use a logger other than the root logger. The \function{getLogger(\var{name})} is used to get a ! particular log, creating it if it doesn't exist yet; ! \function{getLogger(None)} returns the root logger. ! \begin{verbatim} *************** *** 1711,1715 **** Fred~L. Drake, Jr., Michael Hudson, Detlef Lannert, Martin von L\"owis, Andrew MacIntyre, Lalo Martins, Gustavo Niemeyer, Neal ! Norwitz, Chris Reedy, Neil Schemenauer, Jason Tishler. \end{document} --- 1713,1717 ---- Fred~L. Drake, Jr., Michael Hudson, Detlef Lannert, Martin von L\"owis, Andrew MacIntyre, Lalo Martins, Gustavo Niemeyer, Neal ! Norwitz, Chris Reedy, Vinay Sajip, Neil Schemenauer, Jason Tishler. \end{document} From tim_one@users.sourceforge.net Tue Dec 3 16:28:11 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 03 Dec 2002 08:28:11 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.py,1.70,1.71 test_both.py,1.24,1.25 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv17593 Modified Files: datetime.py test_both.py Log Message: The comments claimed that timedeltas can by multiplied by floats, but neither the Python nor the C implementations supported that. It's possible to allow it, but doesn't seem worth the bother now. So changed the comments, and added tests to ensure that mixing datetime with a float via * / // raises TypeError. Also refactored the timedelta tests a little more (this started as one huge timedelta test; I've been breaking it into smaller test pieces all along). Index: datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.py,v retrieving revision 1.70 retrieving revision 1.71 diff -C2 -d -r1.70 -r1.71 *** datetime.py 2 Dec 2002 06:42:28 -0000 1.70 --- datetime.py 3 Dec 2002 16:27:51 -0000 1.71 *************** *** 256,260 **** - unary plus, minus, abs - compare to timedelta ! - multiply, divide by int/long/float In addition, datetime supports subtraction of two datetime objects --- 256,260 ---- - unary plus, minus, abs - compare to timedelta ! - multiply, divide by int/long In addition, datetime supports subtraction of two datetime objects Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.24 retrieving revision 1.25 diff -C2 -d -r1.24 -r1.25 *** test_both.py 2 Dec 2002 23:47:20 -0000 1.24 --- test_both.py 3 Dec 2002 16:27:57 -0000 1.25 *************** *** 41,44 **** --- 41,69 ---- class TestTimeDelta(unittest.TestCase): + def test_constructor(self): + eq = self.assertEqual + td = timedelta + + # Check keyword args to constructor + eq(td(), td(weeks=0, days=0, hours=0, minutes=0, seconds=0, + milliseconds=0, microseconds=0)) + eq(td(1), td(days=1)) + eq(td(0, 1), td(seconds=1)) + eq(td(0, 0, 1), td(microseconds=1)) + eq(td(weeks=1), td(days=7)) + eq(td(days=1), td(hours=24)) + eq(td(hours=1), td(minutes=60)) + eq(td(minutes=1), td(seconds=60)) + eq(td(seconds=1), td(milliseconds=1000)) + eq(td(milliseconds=1), td(microseconds=1000)) + + # Check float args to constructor + eq(td(weeks=1.0/7), td(days=1)) + eq(td(days=1.0/24), td(hours=1)) + eq(td(hours=1.0/60), td(minutes=1)) + eq(td(minutes=1.0/60), td(seconds=1)) + eq(td(seconds=0.001), td(milliseconds=1)) + eq(td(milliseconds=0.001), td(microseconds=1)) + def test_computations(self): eq = self.assertEqual *************** *** 80,83 **** --- 105,111 ---- eq(a//3600000, td(0, 0, 7*24*1000)) + def test_disallowed_computations(self): + a = timedelta(42) + # Add/sub ints, longs, floats should be illegal for i in 1, 1L, 1.0: *************** *** 87,108 **** self.assertRaises(TypeError, lambda: i-a) ! # Check keyword args to constructor ! eq(td(1), td(days=1)) ! eq(td(0, 1), td(seconds=1)) ! eq(td(0, 0, 1), td(microseconds=1)) ! eq(td(weeks=1), td(days=7)) ! eq(td(days=1), td(hours=24)) ! eq(td(hours=1), td(minutes=60)) ! eq(td(minutes=1), td(seconds=60)) ! eq(td(seconds=1), td(milliseconds=1000)) ! eq(td(milliseconds=1), td(microseconds=1000)) ! ! # Check float args to constructor ! eq(td(weeks=1.0/7), td(days=1)) ! eq(td(days=1.0/24), td(hours=1)) ! eq(td(hours=1.0/60), td(minutes=1)) ! eq(td(minutes=1.0/60), td(seconds=1)) ! eq(td(seconds=0.001), td(milliseconds=1)) ! eq(td(milliseconds=0.001), td(microseconds=1)) def test_basic_attributes(self): --- 115,126 ---- self.assertRaises(TypeError, lambda: i-a) ! # Mul/div by float isn't supported. ! x = 2.3 ! self.assertRaises(TypeError, lambda: a*x) ! self.assertRaises(TypeError, lambda: x*a) ! self.assertRaises(TypeError, lambda: a/x) ! self.assertRaises(TypeError, lambda: x/a) ! self.assertRaises(TypeError, lambda: a // x) ! self.assertRaises(TypeError, lambda: x // a) def test_basic_attributes(self): From tim_one@users.sourceforge.net Tue Dec 3 17:50:12 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 03 Dec 2002 09:50:12 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime picklesize.py,NONE,1.1 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv26946 Added Files: picklesize.py Log Message: New program just to display pickle sizes. This makes clear that the copy_reg based C implementation is much more space-efficient in the end than the __getstate__/__setstate__ based Python implementation, but that 4-byte date objects still suffer > 10 bytes of overhead each no matter how many of them you pickle in one gulp. It also makes clear a bug in timedelta: str() doesn't work the same across the implementations. --- NEW FILE: picklesize.py --- import datetime, _datetime if 1: import cPickle as pickle else: import pickle cases = (datetime, "Python"), (_datetime, "C") def pickleit(thing): s = pickle.dumps(thing, 1) return len(s) typenames = "date", "datetime", "timedelta" for typename in typenames: for mod, way in cases: obj = getattr(mod, typename)(2000, 12, 13) print "pickling", obj, "via", way, "-- pickle length", pickleit(obj) for typename in typenames: for i in range(1, 11): for mod, way in cases: ctor = getattr(mod, typename) objs = [ctor(j+1, 3, 4) for j in range(i**2)] plen = pickleit(objs) print "list of %3d %ss via %6s -- %4d bytes, %5.2f bytes/obj" % ( len(objs), typename, way, plen, float(plen)/len(objs)) From loewis@users.sourceforge.net Tue Dec 3 18:09:10 2002 From: loewis@users.sourceforge.net (loewis@users.sourceforge.net) Date: Tue, 03 Dec 2002 10:09:10 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libstdtypes.tex,1.111,1.112 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv16561 Modified Files: libstdtypes.tex Log Message: Patch #646824: Remove extra \end. Index: libstdtypes.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libstdtypes.tex,v retrieving revision 1.111 retrieving revision 1.112 diff -C2 -d -r1.111 -r1.112 *** libstdtypes.tex 27 Nov 2002 07:29:33 -0000 1.111 --- libstdtypes.tex 3 Dec 2002 18:09:02 -0000 1.112 *************** *** 1118,1122 **** \item[(6)] \function{popitem()} is useful to destructively iterate over a dictionary, as often used in set algorithms. - \end{description} \item[(7)] \function{fromkeys()} is a class method that returns a --- 1118,1121 ---- From fdrake@users.sourceforge.net Tue Dec 3 18:49:23 2002 From: fdrake@users.sourceforge.net (fdrake@users.sourceforge.net) Date: Tue, 03 Dec 2002 10:49:23 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libre.tex,1.92,1.93 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv20529/lib Modified Files: libre.tex Log Message: Fix example regular expressions that simulate scanf() constructs. Index: libre.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libre.tex,v retrieving revision 1.92 retrieving revision 1.93 diff -C2 -d -r1.92 -r1.93 *** libre.tex 13 Nov 2002 17:48:15 -0000 1.92 --- libre.tex 3 Dec 2002 18:49:17 -0000 1.93 *************** *** 861,869 **** {\regexp{.\{5\}}} \lineii{\code{\%d}} ! {\regexp{[-+]\e d+}} \lineii{\code{\%e}, \code{\%E}, \code{\%f}, \code{\%g}} ! {\regexp{[-+](\e d+(\e.\e d*)?|\e d*\e.\e d+)([eE]\e d+)?}} \lineii{\code{\%i}} ! {\regexp{[-+](0[xX][\e dA-Fa-f]+|0[0-7]*|\e d+)}} \lineii{\code{\%o}} {\regexp{0[0-7]*}} --- 861,869 ---- {\regexp{.\{5\}}} \lineii{\code{\%d}} ! {\regexp{[-+]?\e d+}} \lineii{\code{\%e}, \code{\%E}, \code{\%f}, \code{\%g}} ! {\regexp{[-+]?(\e d+(\e.\e d*)?|\e d*\e.\e d+)([eE]\e d+)?}} \lineii{\code{\%i}} ! {\regexp{[-+]?(0[xX][\e dA-Fa-f]+|0[0-7]*|\e d+)}} \lineii{\code{\%o}} {\regexp{0[0-7]*}} From fdrake@users.sourceforge.net Tue Dec 3 18:49:49 2002 From: fdrake@users.sourceforge.net (fdrake@users.sourceforge.net) Date: Tue, 03 Dec 2002 10:49:49 -0800 Subject: [Python-checkins] python/dist/src/Doc ACKS,1.37,1.38 Message-ID: Update of /cvsroot/python/python/dist/src/Doc In directory sc8-pr-cvs1:/tmp/cvs-serv20529 Modified Files: ACKS Log Message: Fix example regular expressions that simulate scanf() constructs. Index: ACKS =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/ACKS,v retrieving revision 1.37 retrieving revision 1.38 diff -C2 -d -r1.37 -r1.38 *** ACKS 2 Jul 2002 20:32:50 -0000 1.37 --- ACKS 3 Dec 2002 18:49:16 -0000 1.38 *************** *** 131,134 **** --- 131,135 ---- Ng Pheng Siong Koray Oner + Tomas Oppelstrup Denis S. Otkidach Zooko O'Whielacronx From fdrake@users.sourceforge.net Tue Dec 3 18:50:47 2002 From: fdrake@users.sourceforge.net (fdrake@users.sourceforge.net) Date: Tue, 03 Dec 2002 10:50:47 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libre.tex,1.73.6.13,1.73.6.14 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv21830/lib Modified Files: Tag: release22-maint libre.tex Log Message: Fix example regular expressions that simulate scanf() constructs. Index: libre.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libre.tex,v retrieving revision 1.73.6.13 retrieving revision 1.73.6.14 diff -C2 -d -r1.73.6.13 -r1.73.6.14 *** libre.tex 13 Nov 2002 17:47:53 -0000 1.73.6.13 --- libre.tex 3 Dec 2002 18:50:42 -0000 1.73.6.14 *************** *** 876,884 **** {\regexp{.\{5\}}} \lineii{\code{\%d}} ! {\regexp{[-+]\e d+}} \lineii{\code{\%e}, \code{\%E}, \code{\%f}, \code{\%g}} ! {\regexp{[-+](\e d+(\e.\e d*)?|\e d*\e.\e d+)([eE]\e d+)?}} \lineii{\code{\%i}} ! {\regexp{[-+](0[xX][\e dA-Fa-f]+|0[0-7]*|\e d+)}} \lineii{\code{\%o}} {\regexp{0[0-7]*}} --- 876,884 ---- {\regexp{.\{5\}}} \lineii{\code{\%d}} ! {\regexp{[-+]?\e d+}} \lineii{\code{\%e}, \code{\%E}, \code{\%f}, \code{\%g}} ! {\regexp{[-+]?(\e d+(\e.\e d*)?|\e d*\e.\e d+)([eE]\e d+)?}} \lineii{\code{\%i}} ! {\regexp{[-+]?(0[xX][\e dA-Fa-f]+|0[0-7]*|\e d+)}} \lineii{\code{\%o}} {\regexp{0[0-7]*}} From fdrake@users.sourceforge.net Tue Dec 3 18:51:14 2002 From: fdrake@users.sourceforge.net (fdrake@users.sourceforge.net) Date: Tue, 03 Dec 2002 10:51:14 -0800 Subject: [Python-checkins] python/dist/src/Doc ACKS,1.33.6.1,1.33.6.2 Message-ID: Update of /cvsroot/python/python/dist/src/Doc In directory sc8-pr-cvs1:/tmp/cvs-serv21830 Modified Files: Tag: release22-maint ACKS Log Message: Fix example regular expressions that simulate scanf() constructs. Index: ACKS =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/ACKS,v retrieving revision 1.33.6.1 retrieving revision 1.33.6.2 diff -C2 -d -r1.33.6.1 -r1.33.6.2 *** ACKS 28 Dec 2001 04:29:22 -0000 1.33.6.1 --- ACKS 3 Dec 2002 18:50:41 -0000 1.33.6.2 *************** *** 130,133 **** --- 130,134 ---- Ng Pheng Siong Koray Oner + Tomas Oppelstrup Denis S. Otkidach Zooko O'Whielacronx From tim_one@users.sourceforge.net Tue Dec 3 19:18:18 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 03 Dec 2002 11:18:18 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.c,1.36,1.37 obj_date.c,1.17,1.18 obj_datetime.c,1.12,1.13 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv14760 Modified Files: datetime.c obj_date.c obj_datetime.c Log Message: Removed all traces of the __reduce__-based pickling support. It's not size-competitive with Fred's copy_reg-based approach. Added some sanity checks to the pickling functions. Index: datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.c,v retrieving revision 1.36 retrieving revision 1.37 diff -C2 -d -r1.36 -r1.37 *** datetime.c 3 Dec 2002 02:27:01 -0000 1.36 --- datetime.c 3 Dec 2002 19:18:15 -0000 1.37 *************** *** 536,543 **** } - #if 0 - static PyObject *three_ones = NULL; /* an argument tuple for __reduce__ */ - #endif - static PyObject *date_unpickler_object = NULL; static PyObject *datetime_unpickler_object = NULL; --- 536,539 ---- *************** *** 731,753 **** Py_DECREF(copyreg_pickle); } - #if 0 - { - /* Build (1, 1, 1) so __reduce__ for date-like objects - * has something to pass to the type. - */ - int i; - PyObject *one = PyInt_FromLong(1); - - if (one == NULL) - return; - three_ones = PyTuple_New(3); - if (three_ones == NULL) - return; - for (i = 0; i < 3; ++i) { - Py_INCREF(one); - PyTuple_SetItem(three_ones, i, one); - } - Py_DECREF(one); - } - #endif } --- 727,729 ---- Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.17 retrieving revision 1.18 diff -C2 -d -r1.17 -r1.18 *** obj_date.c 3 Dec 2002 02:27:01 -0000 1.17 --- obj_date.c 3 Dec 2002 19:18:15 -0000 1.18 *************** *** 406,436 **** } - #if 0 - static PyObject * - date_reduce(PyDateTime_Date* self) - { - PyObject* result = NULL; - PyObject* state; - - state = date_getstate(self); - if (state != NULL) { - result = Py_BuildValue("OOO", - self->ob_type, - three_ones, - state); - Py_DECREF(state); - } - return result; - } - #endif - /* XXX This seems a ridiculously inefficient way to pickle a short string. */ static PyObject * date_pickler(PyObject *module, PyDateTime_Date *date) { ! PyObject *state = date_getstate(date); ! PyObject *tuple = Py_BuildValue("O(O)", ! date_unpickler_object, state); ! return tuple; } --- 406,420 ---- } /* XXX This seems a ridiculously inefficient way to pickle a short string. */ static PyObject * date_pickler(PyObject *module, PyDateTime_Date *date) { ! PyObject *state; ! PyObject *result = NULL; ! ! state = date_getstate(date); ! if (state) ! result = Py_BuildValue("O(O)", date_unpickler_object, state); ! return result; } *************** *** 477,484 **** {"__setstate__", (PyCFunction)date_setstate, METH_O, PyDoc_STR("__setstate__(state)")}, - #if 0 - {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS, - NULL}, - #endif {"__getstate__", (PyCFunction)date_getstate, METH_NOARGS, PyDoc_STR("__getstate__() -> state")}, --- 461,464 ---- Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** obj_datetime.c 3 Dec 2002 02:27:01 -0000 1.12 --- obj_datetime.c 3 Dec 2002 19:18:15 -0000 1.13 *************** *** 420,451 **** } ! #if 0 static PyObject * ! datetime_reduce(PyDateTime_DateTime* self) { ! PyObject* result = NULL; ! PyObject* state; ! state = datetime_getstate(self); ! if (state != NULL) { ! result = Py_BuildValue("OOO", ! self->ob_type, ! three_ones, state); - Py_DECREF(state); - } return result; } - #endif - - /* XXX This seems a ridiculously inefficient way to pickle a short string. */ - static PyObject * - datetime_pickler(PyObject *module, PyDateTime_DateTime *datetime) - { - PyObject *state = datetime_getstate(datetime); - PyObject *tuple = Py_BuildValue("O(O)", - datetime_unpickler_object, state); - return tuple; - } static PyObject * --- 420,437 ---- } ! /* XXX This seems a ridiculously inefficient way to pickle a short string. */ static PyObject * ! datetime_pickler(PyObject *module, PyDateTime_DateTime *datetime) { ! PyObject *state; ! PyObject *result = NULL; ! state = datetime_getstate(datetime); ! if (state) ! result = Py_BuildValue("O(O)", ! datetime_unpickler_object, state); return result; } static PyObject * *************** *** 478,485 **** {"__setstate__", (PyCFunction)datetime_setstate, METH_O, PyDoc_STR("__setstate__(state)")}, - #if 0 - {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS, - NULL}, - #endif {"__getstate__", (PyCFunction)datetime_getstate, METH_NOARGS, PyDoc_STR("__getstate__() -> state")}, --- 464,467 ---- From tim_one@users.sourceforge.net Tue Dec 3 19:32:29 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 03 Dec 2002 11:32:29 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_date.c,1.18,1.19 obj_datetime.c,1.13,1.14 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv28261 Modified Files: obj_date.c obj_datetime.c Log Message: Some cosmetic improvements, and more error-checking, in the pickle/ unpickle functions. Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** obj_date.c 3 Dec 2002 19:18:15 -0000 1.18 --- obj_date.c 3 Dec 2002 19:32:27 -0000 1.19 *************** *** 380,387 **** } ! /* Pickle support. Quite a maze! While __getstate__/__setstate__ sufficed ! * in the Python implementation, the C implementation also requires ! * __reduce__, and a __safe_for_unpickling__ attr in the type object. ! */ static PyObject * date_getstate(PyDateTime_Date *self) --- 380,384 ---- } ! /* Pickle support. Quite a maze! */ static PyObject * date_getstate(PyDateTime_Date *self) *************** *** 413,416 **** --- 410,414 ---- PyObject *result = NULL; + assert(date->ob_type == &PyDateTime_DateType); state = date_getstate(date); if (state) *************** *** 423,431 **** { PyDateTime_Date *self; - PyObject *res; self = PyObject_New(PyDateTime_Date, &PyDateTime_DateType); if (self != NULL) { ! res = date_setstate(self, arg); Py_XDECREF(res); } --- 421,432 ---- { PyDateTime_Date *self; + if (! PyString_CheckExact(arg)) { + PyErr_BadInternalCall(); + return NULL; + } self = PyObject_New(PyDateTime_Date, &PyDateTime_DateType); if (self != NULL) { ! PyObject *res = date_setstate(self, arg); Py_XDECREF(res); } Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** obj_datetime.c 3 Dec 2002 19:18:15 -0000 1.13 --- obj_datetime.c 3 Dec 2002 19:32:27 -0000 1.14 *************** *** 1,7 **** ! /* imp_datetime.c * * PyDateTime_DateTime implementation. */ static int normalize_datetime(long *year, long *month, long *day, --- 1,10 ---- ! /* obj_datetime.c * * PyDateTime_DateTime implementation. */ + /* Force all the datetime fields into range. The parameters are both + * inputs and outputs. Returns < 0 on error. + */ static int normalize_datetime(long *year, long *month, long *day, *************** *** 394,401 **** } ! /* Pickle support. Quite a maze! While __getstate__/__setstate__ sufficed ! * in the Python implementation, the C implementation also requires ! * __reduce__, and a __safe_for_unpickling__ attr in the type object. ! */ static PyObject * datetime_getstate(PyDateTime_DateTime *self) --- 397,401 ---- } ! /* Pickle support. Quite a maze! */ static PyObject * datetime_getstate(PyDateTime_DateTime *self) *************** *** 427,430 **** --- 427,431 ---- PyObject *result = NULL; + assert(datetime->ob_type == &PyDateTime_DateTimeType); state = datetime_getstate(datetime); if (state) *************** *** 439,447 **** { PyDateTime_DateTime *self; - PyObject *res; self = PyObject_New(PyDateTime_DateTime, &PyDateTime_DateTimeType); if (self != NULL) { ! res = datetime_setstate(self, arg); Py_XDECREF(res); } --- 440,451 ---- { PyDateTime_DateTime *self; + if (! PyString_CheckExact(arg)) { + PyErr_BadInternalCall(); + return NULL; + } self = PyObject_New(PyDateTime_DateTime, &PyDateTime_DateTimeType); if (self != NULL) { ! PyObject *res = datetime_setstate(self, arg); Py_XDECREF(res); } From tim_one@users.sourceforge.net Tue Dec 3 19:41:56 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 03 Dec 2002 11:41:56 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.c,1.37,1.38 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv3228 Modified Files: datetime.c Log Message: More pickle cleanups, and since date and datetime no longer participate in the __reduce__ protocol, stopped adding a __safe_for_unpickling__ attr to their type dicts. Index: datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.c,v retrieving revision 1.37 retrieving revision 1.38 diff -C2 -d -r1.37 -r1.38 *** datetime.c 3 Dec 2002 19:18:15 -0000 1.37 --- datetime.c 3 Dec 2002 19:41:54 -0000 1.38 *************** *** 568,572 **** --- 568,576 ---- #include "obj_datetime.c" + static PyMethodDef module_methods[] = { + /* Private functions for pickling support, registered with the + * copy_reg module by the module init function. + */ {"_date_pickler", (PyCFunction)date_pickler, METH_O, NULL}, {"_date_unpickler", (PyCFunction)date_unpickler, METH_O, NULL}, *************** *** 581,584 **** --- 585,591 ---- PyObject *m; PyObject *d, *dt; + /* Types that use __reduce__ for pickling need to set the following + * magical attr in the type dict, with a true value. + */ PyObject *safepickle = PyString_FromString("__safe_for_unpickling__"); *************** *** 595,598 **** --- 602,606 ---- /* timedelta values */ d = PyDateTime_DeltaType.tp_dict; + if (PyDict_SetItem(d, safepickle, Py_True) < 0) return; *************** *** 600,605 **** /* date values */ d = PyDateTime_DateType.tp_dict; - if (PyDict_SetItem(d, safepickle, Py_True) < 0) - return; dt = new_date(1, 1, 1); --- 608,611 ---- *************** *** 620,625 **** /* datetime values */ d = PyDateTime_DateTimeType.tp_dict; - if (PyDict_SetItem(d, safepickle, Py_True) < 0) - return; dt = new_datetime(1, 1, 1, 0, 0, 0, 0); --- 626,629 ---- From tim_one@users.sourceforge.net Tue Dec 3 20:43:47 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 03 Dec 2002 12:43:47 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.py,1.71,1.72 obj_delta.c,1.19,1.20 test_both.py,1.25,1.26 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv18194 Modified Files: datetime.py obj_delta.c test_both.py Log Message: Implemented tp_str for the C timedelta type. Repaired a buglet in the Python timedelta.__str__ (it was pluralizing days=-1). Added a test function for timedelta.__str__. I believe the timedelta C implementation is wholly complete now, although it's unclear to me why we never defined class-level min, max and resolution constants for it. Index: datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.py,v retrieving revision 1.71 retrieving revision 1.72 diff -C2 -d -r1.71 -r1.72 *** datetime.py 3 Dec 2002 16:27:51 -0000 1.71 --- datetime.py 3 Dec 2002 20:43:44 -0000 1.72 *************** *** 391,395 **** if self.__days: def plural(n): ! return n, n != 1 and "s" or "" s = ("%d day%s, " % plural(self.__days)) + s if self.__microseconds: --- 391,395 ---- if self.__days: def plural(n): ! return n, abs(n) != 1 and "s" or "" s = ("%d day%s, " % plural(self.__days)) + s if self.__microseconds: Index: obj_delta.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_delta.c,v retrieving revision 1.19 retrieving revision 1.20 diff -C2 -d -r1.19 -r1.20 *** obj_delta.c 2 Dec 2002 21:50:59 -0000 1.19 --- obj_delta.c 3 Dec 2002 20:43:44 -0000 1.20 *************** *** 538,541 **** --- 538,572 ---- } + static PyObject * + delta_str(PyDateTime_Delta *self) + { + long days = GET_TD_DAYS(self); + long seconds = GET_TD_SECONDS(self); + long us = GET_TD_MICROSECONDS(self); + long hours; + long minutes; + char buf[500]; + int i = 0; + + minutes = divmod(seconds, 60, &seconds); + hours = divmod(minutes, 60, &minutes); + + if (days) { + i += sprintf(buf + i, "%d day%s, ", days, + (days == 1 || days == -1) ? "" : "s"); + assert(i < sizeof(buf)); + } + + i += sprintf(buf + i, "%d:%02d:%02d", hours, minutes, seconds); + assert(i < sizeof(buf)); + + if (us) { + i += sprintf(buf + i, ".%06d", us); + assert(i < sizeof(buf)); + } + + return PyString_FromStringAndSize(buf, i); + } + /* Pickle support. Quite a maze! While __getstate__/__setstate__ sufficed * in the Python implementation, the C implementation also requires *************** *** 668,672 **** (hashfunc)delta_hash, /* tp_hash */ 0, /* tp_call */ ! 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ --- 699,703 ---- (hashfunc)delta_hash, /* tp_hash */ 0, /* tp_call */ ! (reprfunc)delta_str, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.25 retrieving revision 1.26 diff -C2 -d -r1.25 -r1.26 *** test_both.py 3 Dec 2002 16:27:57 -0000 1.25 --- test_both.py 3 Dec 2002 20:43:45 -0000 1.26 *************** *** 219,222 **** --- 219,243 ---- self.assertRaises(TypeError, lambda: badarg >= t1) + def test_str(self): + td = timedelta + eq = self.assertEqual + + eq(str(td(1)), "1 day, 0:00:00") + eq(str(td(-1)), "-1 day, 0:00:00") + eq(str(td(2)), "2 days, 0:00:00") + eq(str(td(-2)), "-2 days, 0:00:00") + + eq(str(td(hours=12, minutes=58, seconds=59)), "12:58:59") + eq(str(td(hours=2, minutes=3, seconds=4)), "2:03:04") + eq(str(td(weeks=-30, hours=23, minutes=12, seconds=34)), + "-210 days, 23:12:34") + + eq(str(td(milliseconds=1)), "0:00:00.001000") + eq(str(td(microseconds=3)), "0:00:00.000003") + + eq(str(td(days=999999999, hours=23, minutes=59, seconds=59, + microseconds=999999)), + "999999999 days, 23:59:59.999999") + ############################################################################# # date tests From mhammond@users.sourceforge.net Tue Dec 3 20:59:51 2002 From: mhammond@users.sourceforge.net (mhammond@users.sourceforge.net) Date: Tue, 03 Dec 2002 12:59:51 -0800 Subject: [Python-checkins] python/dist/src/PCbuild _ssl.mak,1.2,1.3 Message-ID: Update of /cvsroot/python/python/dist/src/PCbuild In directory sc8-pr-cvs1:/tmp/cvs-serv1327 Modified Files: _ssl.mak Log Message: Add the SSL libraries as dependencies. Index: _ssl.mak =================================================================== RCS file: /cvsroot/python/python/dist/src/PCbuild/_ssl.mak,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** _ssl.mak 3 Dec 2002 06:29:48 -0000 1.2 --- _ssl.mak 3 Dec 2002 20:59:46 -0000 1.3 *************** *** 15,19 **** LIBS=gdi32.lib wsock32.lib /libpath:$(SSL_LIB_DIR) libeay32.lib ssleay32.lib ! SOURCE=../Modules/_ssl.c $(MODULE): $(SOURCE) ../PC/*.h ../Include/*.h --- 15,19 ---- LIBS=gdi32.lib wsock32.lib /libpath:$(SSL_LIB_DIR) libeay32.lib ssleay32.lib ! SOURCE=../Modules/_ssl.c $(SSL_LIB_DIR)/libeay32.lib $(SSL_LIB_DIR)/ssleay32.lib $(MODULE): $(SOURCE) ../PC/*.h ../Include/*.h From mhammond@users.sourceforge.net Tue Dec 3 21:00:35 2002 From: mhammond@users.sourceforge.net (mhammond@users.sourceforge.net) Date: Tue, 03 Dec 2002 13:00:35 -0800 Subject: [Python-checkins] python/dist/src/PCbuild build_ssl.py,1.1,1.2 Message-ID: Update of /cvsroot/python/python/dist/src/PCbuild In directory sc8-pr-cvs1:/tmp/cvs-serv1764 Modified Files: build_ssl.py Log Message: Don't make all the OpenSSL executables, just the library we need. Contributed by David Bolen. Index: build_ssl.py =================================================================== RCS file: /cvsroot/python/python/dist/src/PCbuild/build_ssl.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** build_ssl.py 3 Dec 2002 05:47:26 -0000 1.1 --- build_ssl.py 3 Dec 2002 21:00:29 -0000 1.2 *************** *** 115,119 **** os.pathsep + \ os.environ["PATH"] ! rc = os.system("ms\\32all.bat") # Now run make. --- 115,139 ---- os.pathsep + \ os.environ["PATH"] ! # ms\32all.bat will reconfigure OpenSSL and then try to build ! # all outputs (debug/nondebug/dll/lib). So we filter the file ! # to exclude any "nmake" commands and then execute. ! tempname = "ms\\32all_py.bat" ! ! in_bat = open("ms\\32all.bat") ! temp_bat = open(tempname,"w") ! while 1: ! cmd = in_bat.readline() ! print 'cmd', repr(cmd) ! if not cmd: break ! if cmd.strip()[:5].lower() == "nmake": ! continue ! temp_bat.write(cmd) ! in_bat.close() ! temp_bat.close() ! os.system(tempname) ! try: ! os.remove(tempname) ! except: ! pass # Now run make. From tim_one@users.sourceforge.net Tue Dec 3 21:17:09 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 03 Dec 2002 13:17:09 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime test_both.py,1.26,1.27 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv16932 Modified Files: test_both.py Log Message: The timedelta type lacked a roundtrip test; added one. Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.26 retrieving revision 1.27 diff -C2 -d -r1.26 -r1.27 *** test_both.py 3 Dec 2002 20:43:45 -0000 1.26 --- test_both.py 3 Dec 2002 21:17:04 -0000 1.27 *************** *** 240,243 **** --- 240,258 ---- "999999999 days, 23:59:59.999999") + def test_roundtrip(self): + for td in (timedelta(days=999999999, hours=23, minutes=59, + seconds=59, microseconds=999999), + timedelta(days=-999999999), + timedelta(days=1, seconds=2, microseconds=3)): + + # Verify td -> string -> td identity. + s = repr(td) + td2 = eval(s) + self.assertEqual(td, td2) + + # Verify identity via reconstructing from pieces. + td2 = timedelta(td.days, td.seconds, td.microseconds) + self.assertEqual(td, td2) + ############################################################################# # date tests From tim_one@users.sourceforge.net Tue Dec 3 21:42:06 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 03 Dec 2002 13:42:06 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.c,1.38,1.39 datetime.py,1.72,1.73 test_both.py,1.27,1.28 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv1023 Modified Files: datetime.c datetime.py test_both.py Log Message: Gave the timedelta class .min, .max, and .resolution attributes, like the other classes here. Added a test case. .min and .max don't currently make sense for the Python implementation, since that's happy to use unbounded longs for the # of days. Sometime last week I silently introduced the limitation that a timedelta object must have a (after normalization) number of days expressible in no more than 9 decimal digits (abs(timedeltaobj.days) < a billion). This was to make the C implementation feasible with finite pain. It's a curious consequence that -timedelta.max overflows, since we constrain the internal microsecond and second members to be >= 0. Index: datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.c,v retrieving revision 1.38 retrieving revision 1.39 diff -C2 -d -r1.38 -r1.39 *** datetime.c 3 Dec 2002 19:41:54 -0000 1.38 --- datetime.c 3 Dec 2002 21:42:00 -0000 1.39 *************** *** 606,609 **** --- 606,624 ---- return; + dt = new_delta(0, 0, 1); + if (dt == NULL || PyDict_SetItemString(d, "resolution", dt) < 0) + return; + Py_DECREF(dt); + + dt = new_delta(1-TOOBIG_INPUT, 0, 0); + if (dt == NULL || PyDict_SetItemString(d, "min", dt) < 0) + return; + Py_DECREF(dt); + + dt = new_delta(TOOBIG_INPUT-1, 24*3600-1, 1000000-1); + if (dt == NULL || PyDict_SetItemString(d, "max", dt) < 0) + return; + Py_DECREF(dt); + /* date values */ d = PyDateTime_DateType.tp_dict; Index: datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.py,v retrieving revision 1.72 retrieving revision 1.73 diff -C2 -d -r1.72 -r1.73 *** datetime.py 3 Dec 2002 20:43:44 -0000 1.72 --- datetime.py 3 Dec 2002 21:42:02 -0000 1.73 *************** *** 474,477 **** --- 474,482 ---- self.__days, self.__seconds, self.__microseconds = tup + timedelta.min = timedelta(-999999999) + timedelta.max = timedelta(days=999999999, hours=23, minutes=59, seconds=59, + microseconds=999999) + timedelta.resolution = timedelta(microseconds=1) + class date(object): """Concrete date type. Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.27 retrieving revision 1.28 diff -C2 -d -r1.27 -r1.28 *** test_both.py 3 Dec 2002 21:17:04 -0000 1.27 --- test_both.py 3 Dec 2002 21:42:03 -0000 1.28 *************** *** 255,258 **** --- 255,267 ---- self.assertEqual(td, td2) + def test_resolution_info(self): + self.assert_(isinstance(timedelta.min, timedelta)) + self.assert_(isinstance(timedelta.max, timedelta)) + self.assert_(isinstance(timedelta.resolution, timedelta)) + self.assert_(timedelta.max > timedelta.min) + self.assertEqual(timedelta.min, timedelta(-999999999)) + self.assertEqual(timedelta.max, timedelta(999999999, 24*3600-1, 1e6-1)) + self.assertEqual(timedelta.resolution, timedelta(0, 0, 1)) + ############################################################################# # date tests From tim_one@users.sourceforge.net Tue Dec 3 21:50:24 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 03 Dec 2002 13:50:24 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.py,1.73,1.74 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv9869 Modified Files: datetime.py Log Message: Gave the Python timedelta implementation a 9-digit limitation on # of days too. This in turn required reimplementing its __cmp__ method, as subtraction of Python timedeltas can overflow now. Index: datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.py,v retrieving revision 1.73 retrieving revision 1.74 diff -C2 -d -r1.73 -r1.74 *** datetime.py 3 Dec 2002 21:42:02 -0000 1.73 --- datetime.py 3 Dec 2002 21:50:20 -0000 1.74 *************** *** 372,375 **** --- 372,377 ---- self.__seconds = s self.__microseconds = us + if abs(d) > 999999999: + raise OverflowError("timedelta # of days is too large: %d" % d) def __repr__(self): *************** *** 458,467 **** raise TypeError, ("can't compare timedelta to %s instance" % type(other).__name__) ! diff = self - other ! if diff.__days < 0: ! return -1 ! if diff.__days == 0 == diff.__seconds == diff.__microseconds: ! return 0 ! return 1 def __hash__(self): --- 460,464 ---- raise TypeError, ("can't compare timedelta to %s instance" % type(other).__name__) ! return cmp(self.__getstate__(), other.__getstate__()) def __hash__(self): From tim_one@users.sourceforge.net Tue Dec 3 21:52:59 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 03 Dec 2002 13:52:59 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime test_both.py,1.28,1.29 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv12653 Modified Files: test_both.py Log Message: Added a timedelta overflow test. Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.28 retrieving revision 1.29 diff -C2 -d -r1.28 -r1.29 *** test_both.py 3 Dec 2002 21:42:03 -0000 1.28 --- test_both.py 3 Dec 2002 21:52:56 -0000 1.29 *************** *** 264,267 **** --- 264,281 ---- self.assertEqual(timedelta.resolution, timedelta(0, 0, 1)) + def test_overflow(self): + tiny = timedelta.resolution + + td = timedelta.min + tiny + td -= tiny # no problem + self.assertRaises(OverflowError, td.__sub__, tiny) + self.assertRaises(OverflowError, td.__add__, -tiny) + + td = timedelta.max - tiny + td += tiny # no problem + self.assertRaises(OverflowError, td.__add__, tiny) + self.assertRaises(OverflowError, td.__sub__, -tiny) + + self.assertRaises(OverflowError, lambda: -timedelta.max) ############################################################################# # date tests From tim_one@users.sourceforge.net Tue Dec 3 21:54:40 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 03 Dec 2002 13:54:40 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime test_both.py,1.29,1.30 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv13661 Modified Files: test_both.py Log Message: Restored blank line deleted by mistake. Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.29 retrieving revision 1.30 diff -C2 -d -r1.29 -r1.30 *** test_both.py 3 Dec 2002 21:52:56 -0000 1.29 --- test_both.py 3 Dec 2002 21:54:36 -0000 1.30 *************** *** 278,281 **** --- 278,282 ---- self.assertRaises(OverflowError, lambda: -timedelta.max) + ############################################################################# # date tests From tim_one@users.sourceforge.net Tue Dec 3 22:54:25 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 03 Dec 2002 14:54:25 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime doc.txt,NONE,1.1 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv18468 Added Files: doc.txt Log Message: Started writing some docs. This is intended to be definitive, so if something here isn't clear, or is wrong, change it. --- NEW FILE: doc.txt --- The datetime module supplies a number of classes for manipulating dates and times, in both simple and complex ways. class date year, month, and day This is an idealized date, assuming the current Gregorian calendar always was, and always will be, in effect. class time hour, minute, second, and microsecond This is independent of any particular day. class datetime year, month, day, hour, minute, second, and microsecond This has no concept of timezone or daylight savings time. You can think of a datetime object as representing UTC time, or local time, or whatever else is convenient. class datetimetz Like datetime, but also supports a customizable notion of time adjustment (for timezones, or daylight savings time, or any other computable adjustment) class timetz Like time, but also supports a customizable notion of time adjustment. class timedelta A duration, the difference between two datetimes, to microsecond resolution. Objects of these types are immutable. class timedelta =============== A timedelta object represents a duration, the difference between two datetimes. Constructor: timedelta(days=0, seconds=0, microseconds=0, # The following should only be used as keyword args: milliseconds=0, minutes=0, hours=0, weeks=0) All arguments are optional. Arguments may be ints, longs, or floats, and may be positive or negative. Only days, seconds and microseconds are stored internally. Arguments are converted to those units: A millisecond is converted 1000 microseconds. A minute is converted to 60 seconds. An hour is converted to 3600 seconds. A week is converted to 7 days. and days, seconds and microseconds are normalized so that 0 <= microseconds < 1000000 0 <= seconds < 3600*24 (the number of seconds in one day) -999999999 <= days <= 999999999 If any argument is a float, and there are fractional microseconds, the value retained is rounded to the nearest microsecond. If the normalized value of days lies outside the indicated range, OverflowError is raised. Class attributes: .min The most negative timedelta object, timedelta(-999999999). .max The most positive timedelta object, timedelta(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999) .resolution The smallest possible difference between non-equal timedelta objects, timedelta(microseconds=1). Instance attributes (read-only): .days between -999999999 and 999999999 inclusive .seconds between 0 and 86399 inclusive .microseconds between 0 and 999999 inclusive Supported operations: - timedelta + timedelta -> timedelta This is exact, but may overflow. - timedelta - timedelta -> timedelta This is exact, but may overflow. - timedelta * (int or long) -> timedelta This is exact, but may overflow. - timedelta // (int or long) -> timedelta The floor is computed and the remainder (if any) is thrown away. Division by 0 raises ZeroDivisionError. - unary plus, minus, abs These are exact, but unary minus and abs may overflow. - comparison of timedelta to timedelta - hash, use as dict key - pickling In addition, subtraction of two datetime objects returns a timedelta, and addition or subtraction of a datetime and a timedelta returns a datetime. class date ========== class datetime ============== class datetimetz ================ class time ========== class timetz ============ From fdrake@users.sourceforge.net Tue Dec 3 22:57:39 2002 From: fdrake@users.sourceforge.net (fdrake@users.sourceforge.net) Date: Tue, 03 Dec 2002 14:57:39 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libpyexpat.tex,1.19,1.20 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv20495 Modified Files: libpyexpat.tex Log Message: Fix problem in example code. It's minor in this particular example, but can lead to mysterious problems in real applications. Index: libpyexpat.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libpyexpat.tex,v retrieving revision 1.19 retrieving revision 1.20 diff -C2 -d -r1.19 -r1.20 *** libpyexpat.tex 17 Jul 2002 20:31:52 -0000 1.19 --- libpyexpat.tex 3 Dec 2002 22:57:37 -0000 1.20 *************** *** 481,485 **** Text goes here More text ! """) \end{verbatim} --- 481,485 ---- Text goes here More text ! """, 1) \end{verbatim} From fdrake@users.sourceforge.net Tue Dec 3 22:58:06 2002 From: fdrake@users.sourceforge.net (fdrake@users.sourceforge.net) Date: Tue, 03 Dec 2002 14:58:06 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libpyexpat.tex,1.17,1.17.8.1 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv20769 Modified Files: Tag: release22-maint libpyexpat.tex Log Message: Fix problem in example code. It's minor in this particular example, but can lead to mysterious problems in real applications. Index: libpyexpat.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libpyexpat.tex,v retrieving revision 1.17 retrieving revision 1.17.8.1 diff -C2 -d -r1.17 -r1.17.8.1 *** libpyexpat.tex 5 Nov 2001 21:31:15 -0000 1.17 --- libpyexpat.tex 3 Dec 2002 22:58:04 -0000 1.17.8.1 *************** *** 452,456 **** Text goes here More text ! """) \end{verbatim} --- 452,456 ---- Text goes here More text ! """, 1) \end{verbatim} From tim_one@users.sourceforge.net Tue Dec 3 23:07:30 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 03 Dec 2002 15:07:30 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime test_both.py,1.30,1.31 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv25519 Modified Files: test_both.py Log Message: Added tests to confirm claims in the docs: int // timedelta not supported timedelta // int raises ZeroDivisionError Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.30 retrieving revision 1.31 diff -C2 -d -r1.30 -r1.31 *** test_both.py 3 Dec 2002 21:54:36 -0000 1.30 --- test_both.py 3 Dec 2002 23:07:28 -0000 1.31 *************** *** 124,127 **** --- 124,133 ---- self.assertRaises(TypeError, lambda: x // a) + # Divison of int by timedelta doesn't make sense. + # Division by zero doesn't make sense. + for zero in 0, 0L: + self.assertRaises(TypeError, lambda: zero // a) + self.assertRaises(ZeroDivisionError, lambda: a // zero) + def test_basic_attributes(self): days, seconds, us = 1, 7, 31 From jackjansen@users.sourceforge.net Tue Dec 3 23:35:24 2002 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 03 Dec 2002 15:35:24 -0800 Subject: [Python-checkins] python/dist/src/Tools/bgen/bgen bgenObjectDefinition.py,1.19,1.20 Message-ID: Update of /cvsroot/python/python/dist/src/Tools/bgen/bgen In directory sc8-pr-cvs1:/tmp/cvs-serv10163 Modified Files: bgenObjectDefinition.py Log Message: Added PEP253 support. Index: bgenObjectDefinition.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Tools/bgen/bgen/bgenObjectDefinition.py,v retrieving revision 1.19 retrieving revision 1.20 diff -C2 -d -r1.19 -r1.20 *** bgenObjectDefinition.py 28 Nov 2002 23:23:14 -0000 1.19 --- bgenObjectDefinition.py 3 Dec 2002 23:35:22 -0000 1.20 *************** *** 5,8 **** --- 5,10 ---- "Spit out code that together defines a new Python object type" basechain = "NULL" + tp_flags = "Py_TPFLAGS_DEFAULT" + basetype = None def __init__(self, name, prefix, itselftype): *************** *** 46,50 **** Output("%sPyTypeObject %s;", sf, self.typename) Output() ! Output("#define %s_Check(x) ((x)->ob_type == &%s)", self.prefix, self.typename) Output() --- 48,56 ---- Output("%sPyTypeObject %s;", sf, self.typename) Output() ! if self.basetype: ! Output("#define %s_Check(x) ((x)->ob_type == &%s || PyObject_TypeCheck((x), %s)", ! self.prefix, self.typename, self.typename) ! else: ! Output("#define %s_Check(x) ((x)->ob_type == &%s)", self.prefix, self.typename) Output() *************** *** 77,80 **** --- 83,88 ---- self.outputHash() + self.outputPEP253Hooks() + self.outputTypeObject() *************** *** 97,100 **** --- 105,110 ---- Output("it = PyObject_NEW(%s, &%s);", self.objecttype, self.typename) Output("if (it == NULL) return NULL;") + if self.basetype: + Output("/* XXXX Should we tp_init or tp_new our basetype? */") self.outputInitStructMembers() Output("return (PyObject *)it;") *************** *** 129,133 **** OutLbrace() self.outputCleanupStructMembers() ! Output("PyObject_Del(self);") OutRbrace() --- 139,146 ---- OutLbrace() self.outputCleanupStructMembers() ! if self.basetype: ! Output("%s.tp_dealloc(self)", self.basetype) ! else: ! Output("PyObject_Del(self);") OutRbrace() *************** *** 198,209 **** def outputTypeObjectInitializer(self): Output("""%s.ob_type = &PyType_Type;""", self.typename); Output("""Py_INCREF(&%s);""", self.typename); ! Output("""if (PyDict_SetItemString(d, "%sType", (PyObject *)&%s) != 0)""", ! self.name, self.typename); ! IndentLevel() ! Output("""Py_FatalError("can\'t initialize %sType");""", ! self.name) ! DedentLevel() class PEP252Mixin: getsetlist = [] --- 211,225 ---- def outputTypeObjectInitializer(self): Output("""%s.ob_type = &PyType_Type;""", self.typename); + if self.basetype: + Output("%s.tp_base = %s;", self.typename, self.basetype) + Output("""Py_INCREF(&%s);""", self.typename) + Output("PyModule_AddObject(m, \"%s\", (PyObject *)&%s);", self.name, self.typename); + Output("/* Backward-compatible name */") Output("""Py_INCREF(&%s);""", self.typename); ! Output("PyModule_AddObject(m, \"%sType\", (PyObject *)&%s);", self.name, self.typename); + def outputPEP253Hooks(self): + pass + class PEP252Mixin: getsetlist = [] *************** *** 238,242 **** func() else: ! Output("0, /*%s*/", methodname) def outputTypeObject(self): --- 254,258 ---- func() else: ! Output("0, /*%s*/", name) def outputTypeObject(self): *************** *** 267,271 **** Output("(hashfunc) %s_hash, /*tp_hash*/", self.prefix) ! Output("0, /*tp_call*/") Output("0, /*tp_str*/") Output("PyObject_GenericGetAttr, /*tp_getattro*/") --- 283,287 ---- Output("(hashfunc) %s_hash, /*tp_hash*/", self.prefix) ! self.outputHook("tp_call") Output("0, /*tp_str*/") Output("PyObject_GenericGetAttr, /*tp_getattro*/") *************** *** 273,277 **** self.outputHook("tp_as_buffer") ! self.outputHook("tp_flags") self.outputHook("tp_doc") self.outputHook("tp_traverse") --- 289,293 ---- self.outputHook("tp_as_buffer") ! Output("%s, /* tp_flags */", self.tp_flags) self.outputHook("tp_doc") self.outputHook("tp_traverse") *************** *** 285,288 **** --- 301,312 ---- Output("%s_getsetlist, /*tp_getset*/", self.prefix) self.outputHook("tp_base") + self.outputHook("tp_dict") + self.outputHook("tp_descr_get") + self.outputHook("tp_descr_set") + self.outputHook("tp_dictoffset") + self.outputHook("tp_init") + self.outputHook("tp_alloc") + self.outputHook("tp_new") + self.outputHook("tp_free") DedentLevel() Output("};") *************** *** 334,337 **** --- 358,440 ---- OutRbrace() Output() + + class PEP253Mixin(PEP252Mixin): + tp_flags = "Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE" + + def outputHook_tp_init(self): + Output("%s_tp_init, /* tp_init */", self.prefix) + + def outputHook_tp_alloc(self): + Output("%s_tp_alloc, /* tp_alloc */", self.prefix) + + def outputHook_tp_new(self): + Output("%s_tp_new, /* tp_new */", self.prefix) + + def outputHook_tp_free(self): + Output("%s_tp_free, /* tp_free */", self.prefix) + + output_tp_initBody = None + + def output_tp_init(self): + if self.output_tp_initBody: + Output("static int %s_init(PyObject *self, PyObject *args, PyObject *kwds)", self.prefix) + OutLbrace() + self.output_tp_initBody() + OutRbrace() + else: + Output("#define %s_tp_init 0", self.prefix) + Output() + + output_tp_allocBody = None + + def output_tp_alloc(self): + if self.output_tp_allocBody: + Output("static PyObject *%s_tp_alloc(PyTypeObject *type, int nitems)", + self.prefix) + OutLbrace() + self.output_tp_allocBody() + OutRbrace() + else: + Output("#define %s_tp_alloc PyType_GenericAlloc", self.prefix) + Output() + + def output_tp_newBody(self): + Output("PyObject *self;"); + Output("%s itself;", self.itselftype); + Output("char *kw[] = {\"itself\", 0};") + Output() + Output("if (!PyArg_ParseTupleAndKeywords(args, kwds, \"O&\", kw, %s_Convert, &itself)) return NULL;", + self.prefix); + Output("if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;") + Output("((%s *)self)->ob_itself = itself;", self.objecttype) + Output("return self;") + + def output_tp_new(self): + if self.output_tp_newBody: + Output("static PyObject *%s_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)", self.prefix) + OutLbrace() + self.output_tp_newBody() + OutRbrace() + else: + Output("#define %s_tp_new PyType_GenericNew", self.prefix) + Output() + + output_tp_freeBody = None + + def output_tp_free(self): + if self.output_tp_freeBody: + Output("static void %s_tp_free(PyObject *self)", self.prefix) + OutLbrace() + self.output_tp_freeBody() + OutRbrace() + else: + Output("#define %s_tp_free PyObject_Del", self.prefix) + Output() + + def outputPEP253Hooks(self): + self.output_tp_init() + self.output_tp_alloc() + self.output_tp_new() + self.output_tp_free() class GlobalObjectDefinition(ObjectDefinition): From jackjansen@users.sourceforge.net Tue Dec 3 23:40:50 2002 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 03 Dec 2002 15:40:50 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules/alias _Aliasmodule.c,1.2,1.3 aliassupport.py,1.2,1.3 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules/alias In directory sc8-pr-cvs1:/tmp/cvs-serv10318/alias Modified Files: _Aliasmodule.c aliassupport.py Log Message: Added PEP253 support to most Carbon modules. This isn't complete yet: some of the more compilcated cases (CF, Res) haven't been done yet. Also, various types should inherit from each other (anything with an as_Resource method should be a Resource subtype, the CF types should become one family). Index: _Aliasmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/alias/_Aliasmodule.c,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** _Aliasmodule.c 29 Nov 2002 23:40:41 -0000 1.2 --- _Aliasmodule.c 3 Dec 2002 23:40:18 -0000 1.3 *************** *** 98,101 **** --- 98,102 ---- #define AliasObj_getsetlist NULL + #define AliasObj_compare NULL *************** *** 103,106 **** --- 104,125 ---- #define AliasObj_hash NULL + #define AliasObj_tp_init 0 + + #define AliasObj_tp_alloc PyType_GenericAlloc + + static PyObject *AliasObj_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + AliasHandle itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, AliasObj_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((AliasObject *)self)->ob_itself = itself; + return self; + } + + #define AliasObj_tp_free PyObject_Del + PyTypeObject Alias_Type = { *************** *** 125,141 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ AliasObj_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ AliasObj_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 144,168 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ AliasObj_methods, /* tp_methods */ ! 0, /*tp_members*/ AliasObj_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! AliasObj_tp_init, /* tp_init */ ! AliasObj_tp_alloc, /* tp_alloc */ ! AliasObj_tp_new, /* tp_new */ ! AliasObj_tp_free, /* tp_free */ }; *************** *** 666,671 **** Alias_Type.ob_type = &PyType_Type; Py_INCREF(&Alias_Type); ! if (PyDict_SetItemString(d, "AliasType", (PyObject *)&Alias_Type) != 0) ! Py_FatalError("can't initialize AliasType"); } --- 693,700 ---- Alias_Type.ob_type = &PyType_Type; Py_INCREF(&Alias_Type); ! PyModule_AddObject(m, "Alias", (PyObject *)&Alias_Type); ! /* Backward-compatible name */ ! Py_INCREF(&Alias_Type); ! PyModule_AddObject(m, "AliasType", (PyObject *)&Alias_Type); } Index: aliassupport.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/alias/aliassupport.py,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** aliassupport.py 29 Nov 2002 23:40:41 -0000 1.2 --- aliassupport.py 3 Dec 2002 23:40:18 -0000 1.3 *************** *** 73,77 **** module = MacModule(MODNAME, MODPREFIX, includestuff, finalstuff, initstuff) ! class AliasDefinition(PEP252Mixin, GlobalObjectDefinition): def outputCheckNewArg(self): --- 73,78 ---- module = MacModule(MODNAME, MODPREFIX, includestuff, finalstuff, initstuff) ! class AliasDefinition(PEP253Mixin, GlobalObjectDefinition): ! # XXXX Should inherit from resource? def outputCheckNewArg(self): From jackjansen@users.sourceforge.net Tue Dec 3 23:40:50 2002 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 03 Dec 2002 15:40:50 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules/ae _AEmodule.c,1.13,1.14 aesupport.py,1.27,1.28 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules/ae In directory sc8-pr-cvs1:/tmp/cvs-serv10318/ae Modified Files: _AEmodule.c aesupport.py Log Message: Added PEP253 support to most Carbon modules. This isn't complete yet: some of the more compilcated cases (CF, Res) haven't been done yet. Also, various types should inherit from each other (anything with an as_Resource method should be a Resource subtype, the CF types should become one family). Index: _AEmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/ae/_AEmodule.c,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** _AEmodule.c 29 Nov 2002 23:40:41 -0000 1.13 --- _AEmodule.c 3 Dec 2002 23:40:18 -0000 1.14 *************** *** 870,873 **** --- 870,891 ---- #define AEDesc_hash NULL + #define AEDesc_tp_init 0 + + #define AEDesc_tp_alloc PyType_GenericAlloc + + static PyObject *AEDesc_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + AEDesc itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, AEDesc_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((AEDescObject *)self)->ob_itself = itself; + return self; + } + + #define AEDesc_tp_free PyObject_Del + PyTypeObject AEDesc_Type = { *************** *** 892,908 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ AEDesc_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ AEDesc_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 910,934 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ AEDesc_methods, /* tp_methods */ ! 0, /*tp_members*/ AEDesc_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! AEDesc_tp_init, /* tp_init */ ! AEDesc_tp_alloc, /* tp_alloc */ ! AEDesc_tp_new, /* tp_new */ ! AEDesc_tp_free, /* tp_free */ }; *************** *** 1430,1435 **** AEDesc_Type.ob_type = &PyType_Type; Py_INCREF(&AEDesc_Type); ! if (PyDict_SetItemString(d, "AEDescType", (PyObject *)&AEDesc_Type) != 0) ! Py_FatalError("can't initialize AEDescType"); } --- 1456,1463 ---- AEDesc_Type.ob_type = &PyType_Type; Py_INCREF(&AEDesc_Type); ! PyModule_AddObject(m, "AEDesc", (PyObject *)&AEDesc_Type); ! /* Backward-compatible name */ ! Py_INCREF(&AEDesc_Type); ! PyModule_AddObject(m, "AEDescType", (PyObject *)&AEDesc_Type); } Index: aesupport.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/ae/aesupport.py,v retrieving revision 1.27 retrieving revision 1.28 diff -C2 -d -r1.27 -r1.28 *** aesupport.py 29 Nov 2002 23:40:41 -0000 1.27 --- aesupport.py 3 Dec 2002 23:40:18 -0000 1.28 *************** *** 175,179 **** module = MacModule('_AE', 'AE', includestuff, finalstuff, initstuff) ! class AEDescDefinition(PEP252Mixin, GlobalObjectDefinition): getsetlist = [( 'type', --- 175,179 ---- module = MacModule('_AE', 'AE', includestuff, finalstuff, initstuff) ! class AEDescDefinition(PEP253Mixin, GlobalObjectDefinition): getsetlist = [( 'type', From jackjansen@users.sourceforge.net Tue Dec 3 23:40:51 2002 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 03 Dec 2002 15:40:51 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules/app _Appmodule.c,1.13,1.14 appsupport.py,1.16,1.17 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules/app In directory sc8-pr-cvs1:/tmp/cvs-serv10318/app Modified Files: _Appmodule.c appsupport.py Log Message: Added PEP253 support to most Carbon modules. This isn't complete yet: some of the more compilcated cases (CF, Res) haven't been done yet. Also, various types should inherit from each other (anything with an as_Resource method should be a Resource subtype, the CF types should become one family). Index: _Appmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/app/_Appmodule.c,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** _Appmodule.c 29 Nov 2002 23:40:41 -0000 1.13 --- _Appmodule.c 3 Dec 2002 23:40:18 -0000 1.14 *************** *** 116,119 **** --- 116,120 ---- #define ThemeDrawingStateObj_getsetlist NULL + #define ThemeDrawingStateObj_compare NULL *************** *** 121,124 **** --- 122,143 ---- #define ThemeDrawingStateObj_hash NULL + #define ThemeDrawingStateObj_tp_init 0 + + #define ThemeDrawingStateObj_tp_alloc PyType_GenericAlloc + + static PyObject *ThemeDrawingStateObj_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + ThemeDrawingState itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, ThemeDrawingStateObj_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((ThemeDrawingStateObject *)self)->ob_itself = itself; + return self; + } + + #define ThemeDrawingStateObj_tp_free PyObject_Del + PyTypeObject ThemeDrawingState_Type = { *************** *** 143,159 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ ThemeDrawingStateObj_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ ThemeDrawingStateObj_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 162,186 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ ThemeDrawingStateObj_methods, /* tp_methods */ ! 0, /*tp_members*/ ThemeDrawingStateObj_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! ThemeDrawingStateObj_tp_init, /* tp_init */ ! ThemeDrawingStateObj_tp_alloc, /* tp_alloc */ ! ThemeDrawingStateObj_tp_new, /* tp_new */ ! ThemeDrawingStateObj_tp_free, /* tp_free */ }; *************** *** 1823,1828 **** ThemeDrawingState_Type.ob_type = &PyType_Type; Py_INCREF(&ThemeDrawingState_Type); ! if (PyDict_SetItemString(d, "ThemeDrawingStateType", (PyObject *)&ThemeDrawingState_Type) != 0) ! Py_FatalError("can't initialize ThemeDrawingStateType"); } --- 1850,1857 ---- ThemeDrawingState_Type.ob_type = &PyType_Type; Py_INCREF(&ThemeDrawingState_Type); ! PyModule_AddObject(m, "ThemeDrawingState", (PyObject *)&ThemeDrawingState_Type); ! /* Backward-compatible name */ ! Py_INCREF(&ThemeDrawingState_Type); ! PyModule_AddObject(m, "ThemeDrawingStateType", (PyObject *)&ThemeDrawingState_Type); } Index: appsupport.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/app/appsupport.py,v retrieving revision 1.16 retrieving revision 1.17 diff -C2 -d -r1.16 -r1.17 *** appsupport.py 29 Nov 2002 23:40:41 -0000 1.16 --- appsupport.py 3 Dec 2002 23:40:19 -0000 1.17 *************** *** 95,99 **** """ ! class MyObjectDefinition(PEP252Mixin, GlobalObjectDefinition): pass ## def outputCheckNewArg(self): --- 95,99 ---- """ ! class MyObjectDefinition(PEP253Mixin, GlobalObjectDefinition): pass ## def outputCheckNewArg(self): From jackjansen@users.sourceforge.net Tue Dec 3 23:40:52 2002 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 03 Dec 2002 15:40:52 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules/help helpsupport.py,1.8,1.9 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules/help In directory sc8-pr-cvs1:/tmp/cvs-serv10318/help Modified Files: helpsupport.py Log Message: Added PEP253 support to most Carbon modules. This isn't complete yet: some of the more compilcated cases (CF, Res) haven't been done yet. Also, various types should inherit from each other (anything with an as_Resource method should be a Resource subtype, the CF types should become one family). Index: helpsupport.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/help/helpsupport.py,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** helpsupport.py 29 Nov 2002 23:40:43 -0000 1.8 --- helpsupport.py 3 Dec 2002 23:40:20 -0000 1.9 *************** *** 47,51 **** """ ! class MyObjectDefinition(PEP252Mixin, GlobalObjectDefinition): def outputCheckNewArg(self): Output("if (itself == NULL) return PyMac_Error(resNotFound);") --- 47,51 ---- """ ! class MyObjectDefinition(PEP253Mixin, GlobalObjectDefinition): def outputCheckNewArg(self): Output("if (itself == NULL) return PyMac_Error(resNotFound);") From jackjansen@users.sourceforge.net Tue Dec 3 23:40:51 2002 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 03 Dec 2002 15:40:51 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules/cg _CGmodule.c,1.8,1.9 cgsupport.py,1.5,1.6 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules/cg In directory sc8-pr-cvs1:/tmp/cvs-serv10318/cg Modified Files: _CGmodule.c cgsupport.py Log Message: Added PEP253 support to most Carbon modules. This isn't complete yet: some of the more compilcated cases (CF, Res) haven't been done yet. Also, various types should inherit from each other (anything with an as_Resource method should be a Resource subtype, the CF types should become one family). Index: _CGmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/cg/_CGmodule.c,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** _CGmodule.c 29 Nov 2002 23:40:42 -0000 1.8 --- _CGmodule.c 3 Dec 2002 23:40:19 -0000 1.9 *************** *** 1269,1272 **** --- 1269,1273 ---- #define CGContextRefObj_getsetlist NULL + #define CGContextRefObj_compare NULL *************** *** 1274,1277 **** --- 1275,1296 ---- #define CGContextRefObj_hash NULL + #define CGContextRefObj_tp_init 0 + + #define CGContextRefObj_tp_alloc PyType_GenericAlloc + + static PyObject *CGContextRefObj_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + CGContextRef itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, CGContextRefObj_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((CGContextRefObject *)self)->ob_itself = itself; + return self; + } + + #define CGContextRefObj_tp_free PyObject_Del + PyTypeObject CGContextRef_Type = { *************** *** 1296,1312 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ CGContextRefObj_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ CGContextRefObj_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 1315,1339 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ CGContextRefObj_methods, /* tp_methods */ ! 0, /*tp_members*/ CGContextRefObj_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! CGContextRefObj_tp_init, /* tp_init */ ! CGContextRefObj_tp_alloc, /* tp_alloc */ ! CGContextRefObj_tp_new, /* tp_new */ ! CGContextRefObj_tp_free, /* tp_free */ }; *************** *** 1374,1379 **** CGContextRef_Type.ob_type = &PyType_Type; Py_INCREF(&CGContextRef_Type); ! if (PyDict_SetItemString(d, "CGContextRefType", (PyObject *)&CGContextRef_Type) != 0) ! Py_FatalError("can't initialize CGContextRefType"); } --- 1401,1408 ---- CGContextRef_Type.ob_type = &PyType_Type; Py_INCREF(&CGContextRef_Type); ! PyModule_AddObject(m, "CGContextRef", (PyObject *)&CGContextRef_Type); ! /* Backward-compatible name */ ! Py_INCREF(&CGContextRef_Type); ! PyModule_AddObject(m, "CGContextRefType", (PyObject *)&CGContextRef_Type); } Index: cgsupport.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/cg/cgsupport.py,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** cgsupport.py 29 Nov 2002 23:40:42 -0000 1.5 --- cgsupport.py 3 Dec 2002 23:40:19 -0000 1.6 *************** *** 251,255 **** ! class MyObjectDefinition(PEP252Mixin, GlobalObjectDefinition): def outputStructMembers(self): ObjectDefinition.outputStructMembers(self) --- 251,255 ---- ! class MyObjectDefinition(PEP253Mixin, GlobalObjectDefinition): def outputStructMembers(self): ObjectDefinition.outputStructMembers(self) From jackjansen@users.sourceforge.net Tue Dec 3 23:40:52 2002 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 03 Dec 2002 15:40:52 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules/drag _Dragmodule.c,1.11,1.12 dragsupport.py,1.11,1.12 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules/drag In directory sc8-pr-cvs1:/tmp/cvs-serv10318/drag Modified Files: _Dragmodule.c dragsupport.py Log Message: Added PEP253 support to most Carbon modules. This isn't complete yet: some of the more compilcated cases (CF, Res) haven't been done yet. Also, various types should inherit from each other (anything with an as_Resource method should be a Resource subtype, the CF types should become one family). Index: _Dragmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/drag/_Dragmodule.c,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** _Dragmodule.c 29 Nov 2002 23:40:43 -0000 1.11 --- _Dragmodule.c 3 Dec 2002 23:40:20 -0000 1.12 *************** *** 743,746 **** --- 743,747 ---- #define DragObj_getsetlist NULL + #define DragObj_compare NULL *************** *** 748,751 **** --- 749,770 ---- #define DragObj_hash NULL + #define DragObj_tp_init 0 + + #define DragObj_tp_alloc PyType_GenericAlloc + + static PyObject *DragObj_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + DragRef itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, DragObj_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((DragObjObject *)self)->ob_itself = itself; + return self; + } + + #define DragObj_tp_free PyObject_Del + PyTypeObject DragObj_Type = { *************** *** 770,786 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ DragObj_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ DragObj_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 789,813 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ DragObj_methods, /* tp_methods */ ! 0, /*tp_members*/ DragObj_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! DragObj_tp_init, /* tp_init */ ! DragObj_tp_alloc, /* tp_alloc */ ! DragObj_tp_new, /* tp_new */ ! DragObj_tp_free, /* tp_free */ }; *************** *** 1110,1115 **** DragObj_Type.ob_type = &PyType_Type; Py_INCREF(&DragObj_Type); ! if (PyDict_SetItemString(d, "DragObjType", (PyObject *)&DragObj_Type) != 0) ! Py_FatalError("can't initialize DragObjType"); dragglue_TrackingHandlerUPP = NewDragTrackingHandlerUPP(dragglue_TrackingHandler); --- 1137,1144 ---- DragObj_Type.ob_type = &PyType_Type; Py_INCREF(&DragObj_Type); ! PyModule_AddObject(m, "DragObj", (PyObject *)&DragObj_Type); ! /* Backward-compatible name */ ! Py_INCREF(&DragObj_Type); ! PyModule_AddObject(m, "DragObjType", (PyObject *)&DragObj_Type); dragglue_TrackingHandlerUPP = NewDragTrackingHandlerUPP(dragglue_TrackingHandler); Index: dragsupport.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/drag/dragsupport.py,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** dragsupport.py 29 Nov 2002 23:40:43 -0000 1.11 --- dragsupport.py 3 Dec 2002 23:40:20 -0000 1.12 *************** *** 184,188 **** """ ! class MyObjectDefinition(PEP252Mixin, GlobalObjectDefinition): def outputCheckNewArg(self): Output("""if (itself == NULL) { --- 184,188 ---- """ ! class MyObjectDefinition(PEP253Mixin, GlobalObjectDefinition): def outputCheckNewArg(self): Output("""if (itself == NULL) { From jackjansen@users.sourceforge.net Tue Dec 3 23:40:51 2002 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 03 Dec 2002 15:40:51 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules/cf _CFmodule.c,1.16,1.17 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules/cf In directory sc8-pr-cvs1:/tmp/cvs-serv10318/cf Modified Files: _CFmodule.c Log Message: Added PEP253 support to most Carbon modules. This isn't complete yet: some of the more compilcated cases (CF, Res) haven't been done yet. Also, various types should inherit from each other (anything with an as_Resource method should be a Resource subtype, the CF types should become one family). Index: _CFmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/cf/_CFmodule.c,v retrieving revision 1.16 retrieving revision 1.17 diff -C2 -d -r1.16 -r1.17 *** _CFmodule.c 16 Aug 2002 09:09:16 -0000 1.16 --- _CFmodule.c 3 Dec 2002 23:40:19 -0000 1.17 *************** *** 4326,4367 **** CFTypeRef_Type.ob_type = &PyType_Type; Py_INCREF(&CFTypeRef_Type); ! if (PyDict_SetItemString(d, "CFTypeRefType", (PyObject *)&CFTypeRef_Type) != 0) ! Py_FatalError("can't initialize CFTypeRefType"); CFArrayRef_Type.ob_type = &PyType_Type; Py_INCREF(&CFArrayRef_Type); ! if (PyDict_SetItemString(d, "CFArrayRefType", (PyObject *)&CFArrayRef_Type) != 0) ! Py_FatalError("can't initialize CFArrayRefType"); CFMutableArrayRef_Type.ob_type = &PyType_Type; Py_INCREF(&CFMutableArrayRef_Type); ! if (PyDict_SetItemString(d, "CFMutableArrayRefType", (PyObject *)&CFMutableArrayRef_Type) != 0) ! Py_FatalError("can't initialize CFMutableArrayRefType"); CFDictionaryRef_Type.ob_type = &PyType_Type; Py_INCREF(&CFDictionaryRef_Type); ! if (PyDict_SetItemString(d, "CFDictionaryRefType", (PyObject *)&CFDictionaryRef_Type) != 0) ! Py_FatalError("can't initialize CFDictionaryRefType"); CFMutableDictionaryRef_Type.ob_type = &PyType_Type; Py_INCREF(&CFMutableDictionaryRef_Type); ! if (PyDict_SetItemString(d, "CFMutableDictionaryRefType", (PyObject *)&CFMutableDictionaryRef_Type) != 0) ! Py_FatalError("can't initialize CFMutableDictionaryRefType"); CFDataRef_Type.ob_type = &PyType_Type; Py_INCREF(&CFDataRef_Type); ! if (PyDict_SetItemString(d, "CFDataRefType", (PyObject *)&CFDataRef_Type) != 0) ! Py_FatalError("can't initialize CFDataRefType"); CFMutableDataRef_Type.ob_type = &PyType_Type; Py_INCREF(&CFMutableDataRef_Type); ! if (PyDict_SetItemString(d, "CFMutableDataRefType", (PyObject *)&CFMutableDataRef_Type) != 0) ! Py_FatalError("can't initialize CFMutableDataRefType"); CFStringRef_Type.ob_type = &PyType_Type; Py_INCREF(&CFStringRef_Type); ! if (PyDict_SetItemString(d, "CFStringRefType", (PyObject *)&CFStringRef_Type) != 0) ! Py_FatalError("can't initialize CFStringRefType"); CFMutableStringRef_Type.ob_type = &PyType_Type; Py_INCREF(&CFMutableStringRef_Type); ! if (PyDict_SetItemString(d, "CFMutableStringRefType", (PyObject *)&CFMutableStringRef_Type) != 0) ! Py_FatalError("can't initialize CFMutableStringRefType"); CFURLRef_Type.ob_type = &PyType_Type; Py_INCREF(&CFURLRef_Type); ! if (PyDict_SetItemString(d, "CFURLRefType", (PyObject *)&CFURLRef_Type) != 0) ! Py_FatalError("can't initialize CFURLRefType"); #define _STRINGCONST(name) PyModule_AddObject(m, #name, CFStringRefObj_New(name)) --- 4326,4387 ---- CFTypeRef_Type.ob_type = &PyType_Type; Py_INCREF(&CFTypeRef_Type); ! PyModule_AddObject(m, "CFTypeRef", (PyObject *)&CFTypeRef_Type); ! /* Backward-compatible name */ ! Py_INCREF(&CFTypeRef_Type); ! PyModule_AddObject(m, "CFTypeRefType", (PyObject *)&CFTypeRef_Type); CFArrayRef_Type.ob_type = &PyType_Type; Py_INCREF(&CFArrayRef_Type); ! PyModule_AddObject(m, "CFArrayRef", (PyObject *)&CFArrayRef_Type); ! /* Backward-compatible name */ ! Py_INCREF(&CFArrayRef_Type); ! PyModule_AddObject(m, "CFArrayRefType", (PyObject *)&CFArrayRef_Type); CFMutableArrayRef_Type.ob_type = &PyType_Type; Py_INCREF(&CFMutableArrayRef_Type); ! PyModule_AddObject(m, "CFMutableArrayRef", (PyObject *)&CFMutableArrayRef_Type); ! /* Backward-compatible name */ ! Py_INCREF(&CFMutableArrayRef_Type); ! PyModule_AddObject(m, "CFMutableArrayRefType", (PyObject *)&CFMutableArrayRef_Type); CFDictionaryRef_Type.ob_type = &PyType_Type; Py_INCREF(&CFDictionaryRef_Type); ! PyModule_AddObject(m, "CFDictionaryRef", (PyObject *)&CFDictionaryRef_Type); ! /* Backward-compatible name */ ! Py_INCREF(&CFDictionaryRef_Type); ! PyModule_AddObject(m, "CFDictionaryRefType", (PyObject *)&CFDictionaryRef_Type); CFMutableDictionaryRef_Type.ob_type = &PyType_Type; Py_INCREF(&CFMutableDictionaryRef_Type); ! PyModule_AddObject(m, "CFMutableDictionaryRef", (PyObject *)&CFMutableDictionaryRef_Type); ! /* Backward-compatible name */ ! Py_INCREF(&CFMutableDictionaryRef_Type); ! PyModule_AddObject(m, "CFMutableDictionaryRefType", (PyObject *)&CFMutableDictionaryRef_Type); CFDataRef_Type.ob_type = &PyType_Type; Py_INCREF(&CFDataRef_Type); ! PyModule_AddObject(m, "CFDataRef", (PyObject *)&CFDataRef_Type); ! /* Backward-compatible name */ ! Py_INCREF(&CFDataRef_Type); ! PyModule_AddObject(m, "CFDataRefType", (PyObject *)&CFDataRef_Type); CFMutableDataRef_Type.ob_type = &PyType_Type; Py_INCREF(&CFMutableDataRef_Type); ! PyModule_AddObject(m, "CFMutableDataRef", (PyObject *)&CFMutableDataRef_Type); ! /* Backward-compatible name */ ! Py_INCREF(&CFMutableDataRef_Type); ! PyModule_AddObject(m, "CFMutableDataRefType", (PyObject *)&CFMutableDataRef_Type); CFStringRef_Type.ob_type = &PyType_Type; Py_INCREF(&CFStringRef_Type); ! PyModule_AddObject(m, "CFStringRef", (PyObject *)&CFStringRef_Type); ! /* Backward-compatible name */ ! Py_INCREF(&CFStringRef_Type); ! PyModule_AddObject(m, "CFStringRefType", (PyObject *)&CFStringRef_Type); CFMutableStringRef_Type.ob_type = &PyType_Type; Py_INCREF(&CFMutableStringRef_Type); ! PyModule_AddObject(m, "CFMutableStringRef", (PyObject *)&CFMutableStringRef_Type); ! /* Backward-compatible name */ ! Py_INCREF(&CFMutableStringRef_Type); ! PyModule_AddObject(m, "CFMutableStringRefType", (PyObject *)&CFMutableStringRef_Type); CFURLRef_Type.ob_type = &PyType_Type; Py_INCREF(&CFURLRef_Type); ! PyModule_AddObject(m, "CFURLRef", (PyObject *)&CFURLRef_Type); ! /* Backward-compatible name */ ! Py_INCREF(&CFURLRef_Type); ! PyModule_AddObject(m, "CFURLRefType", (PyObject *)&CFURLRef_Type); #define _STRINGCONST(name) PyModule_AddObject(m, #name, CFStringRefObj_New(name)) From jackjansen@users.sourceforge.net Tue Dec 3 23:40:51 2002 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 03 Dec 2002 15:40:51 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules/cm _Cmmodule.c,1.11,1.12 cmsupport.py,1.7,1.8 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules/cm In directory sc8-pr-cvs1:/tmp/cvs-serv10318/cm Modified Files: _Cmmodule.c cmsupport.py Log Message: Added PEP253 support to most Carbon modules. This isn't complete yet: some of the more compilcated cases (CF, Res) haven't been done yet. Also, various types should inherit from each other (anything with an as_Resource method should be a Resource subtype, the CF types should become one family). Index: _Cmmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/cm/_Cmmodule.c,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** _Cmmodule.c 29 Nov 2002 23:40:42 -0000 1.11 --- _Cmmodule.c 3 Dec 2002 23:40:19 -0000 1.12 *************** *** 308,311 **** --- 308,312 ---- #define CmpInstObj_getsetlist NULL + #define CmpInstObj_compare NULL *************** *** 313,316 **** --- 314,335 ---- #define CmpInstObj_hash NULL + #define CmpInstObj_tp_init 0 + + #define CmpInstObj_tp_alloc PyType_GenericAlloc + + static PyObject *CmpInstObj_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + ComponentInstance itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, CmpInstObj_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((ComponentInstanceObject *)self)->ob_itself = itself; + return self; + } + + #define CmpInstObj_tp_free PyObject_Del + PyTypeObject ComponentInstance_Type = { *************** *** 335,351 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ CmpInstObj_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ CmpInstObj_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 354,378 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ CmpInstObj_methods, /* tp_methods */ ! 0, /*tp_members*/ CmpInstObj_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! CmpInstObj_tp_init, /* tp_init */ ! CmpInstObj_tp_alloc, /* tp_alloc */ ! CmpInstObj_tp_new, /* tp_new */ ! CmpInstObj_tp_free, /* tp_free */ }; *************** *** 714,717 **** --- 741,745 ---- #define CmpObj_getsetlist NULL + #define CmpObj_compare NULL *************** *** 719,722 **** --- 747,768 ---- #define CmpObj_hash NULL + #define CmpObj_tp_init 0 + + #define CmpObj_tp_alloc PyType_GenericAlloc + + static PyObject *CmpObj_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + Component itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, CmpObj_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((ComponentObject *)self)->ob_itself = itself; + return self; + } + + #define CmpObj_tp_free PyObject_Del + PyTypeObject Component_Type = { *************** *** 741,757 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ CmpObj_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ CmpObj_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 787,811 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ CmpObj_methods, /* tp_methods */ ! 0, /*tp_members*/ CmpObj_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! CmpObj_tp_init, /* tp_init */ ! CmpObj_tp_alloc, /* tp_alloc */ ! CmpObj_tp_new, /* tp_new */ ! CmpObj_tp_free, /* tp_free */ }; *************** *** 931,940 **** ComponentInstance_Type.ob_type = &PyType_Type; Py_INCREF(&ComponentInstance_Type); ! if (PyDict_SetItemString(d, "ComponentInstanceType", (PyObject *)&ComponentInstance_Type) != 0) ! Py_FatalError("can't initialize ComponentInstanceType"); Component_Type.ob_type = &PyType_Type; Py_INCREF(&Component_Type); ! if (PyDict_SetItemString(d, "ComponentType", (PyObject *)&Component_Type) != 0) ! Py_FatalError("can't initialize ComponentType"); } --- 985,998 ---- ComponentInstance_Type.ob_type = &PyType_Type; Py_INCREF(&ComponentInstance_Type); ! PyModule_AddObject(m, "ComponentInstance", (PyObject *)&ComponentInstance_Type); ! /* Backward-compatible name */ ! Py_INCREF(&ComponentInstance_Type); ! PyModule_AddObject(m, "ComponentInstanceType", (PyObject *)&ComponentInstance_Type); Component_Type.ob_type = &PyType_Type; Py_INCREF(&Component_Type); ! PyModule_AddObject(m, "Component", (PyObject *)&Component_Type); ! /* Backward-compatible name */ ! Py_INCREF(&Component_Type); ! PyModule_AddObject(m, "ComponentType", (PyObject *)&Component_Type); } Index: cmsupport.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/cm/cmsupport.py,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** cmsupport.py 29 Nov 2002 23:40:42 -0000 1.7 --- cmsupport.py 3 Dec 2002 23:40:19 -0000 1.8 *************** *** 80,84 **** ComponentResourceHandle = OpaqueByValueType("ComponentResourceHandle", "ResObj") ! class MyCIObjectDefinition(PEP252Mixin, GlobalObjectDefinition): def outputCheckNewArg(self): Output("""if (itself == NULL) { --- 80,84 ---- ComponentResourceHandle = OpaqueByValueType("ComponentResourceHandle", "ResObj") ! class MyCIObjectDefinition(PEP253Mixin, GlobalObjectDefinition): def outputCheckNewArg(self): Output("""if (itself == NULL) { *************** *** 87,91 **** }""") ! class MyCObjectDefinition(PEP252Mixin, GlobalObjectDefinition): def outputCheckNewArg(self): Output("""if (itself == NULL) { --- 87,91 ---- }""") ! class MyCObjectDefinition(PEP253Mixin, GlobalObjectDefinition): def outputCheckNewArg(self): Output("""if (itself == NULL) { From jackjansen@users.sourceforge.net Tue Dec 3 23:40:52 2002 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 03 Dec 2002 15:40:52 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules/ctl _Ctlmodule.c,1.20,1.21 ctlsupport.py,1.51,1.52 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules/ctl In directory sc8-pr-cvs1:/tmp/cvs-serv10318/ctl Modified Files: _Ctlmodule.c ctlsupport.py Log Message: Added PEP253 support to most Carbon modules. This isn't complete yet: some of the more compilcated cases (CF, Res) haven't been done yet. Also, various types should inherit from each other (anything with an as_Resource method should be a Resource subtype, the CF types should become one family). Index: _Ctlmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/ctl/_Ctlmodule.c,v retrieving revision 1.20 retrieving revision 1.21 diff -C2 -d -r1.20 -r1.21 *** _Ctlmodule.c 29 Nov 2002 23:40:42 -0000 1.20 --- _Ctlmodule.c 3 Dec 2002 23:40:19 -0000 1.21 *************** *** 4546,4549 **** --- 4546,4550 ---- #define CtlObj_getsetlist NULL + static int CtlObj_compare(ControlObject *self, ControlObject *other) { *************** *** 4571,4574 **** --- 4572,4593 ---- return (long)self->ob_itself; } + #define CtlObj_tp_init 0 + + #define CtlObj_tp_alloc PyType_GenericAlloc + + static PyObject *CtlObj_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + ControlHandle itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, CtlObj_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((ControlObject *)self)->ob_itself = itself; + return self; + } + + #define CtlObj_tp_free PyObject_Del + PyTypeObject Control_Type = { *************** *** 4593,4609 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ CtlObj_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ CtlObj_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 4612,4636 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ CtlObj_methods, /* tp_methods */ ! 0, /*tp_members*/ CtlObj_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! CtlObj_tp_init, /* tp_init */ ! CtlObj_tp_alloc, /* tp_alloc */ ! CtlObj_tp_new, /* tp_new */ ! CtlObj_tp_free, /* tp_free */ }; *************** *** 6715,6720 **** Control_Type.ob_type = &PyType_Type; Py_INCREF(&Control_Type); ! if (PyDict_SetItemString(d, "ControlType", (PyObject *)&Control_Type) != 0) ! Py_FatalError("can't initialize ControlType"); } --- 6742,6749 ---- Control_Type.ob_type = &PyType_Type; Py_INCREF(&Control_Type); ! PyModule_AddObject(m, "Control", (PyObject *)&Control_Type); ! /* Backward-compatible name */ ! Py_INCREF(&Control_Type); ! PyModule_AddObject(m, "ControlType", (PyObject *)&Control_Type); } Index: ctlsupport.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/ctl/ctlsupport.py,v retrieving revision 1.51 retrieving revision 1.52 diff -C2 -d -r1.51 -r1.52 *** ctlsupport.py 29 Nov 2002 23:40:42 -0000 1.51 --- ctlsupport.py 3 Dec 2002 23:40:19 -0000 1.52 *************** *** 491,495 **** """ ! class MyObjectDefinition(PEP252Mixin, ObjectIdentityMixin, GlobalObjectDefinition): def outputStructMembers(self): GlobalObjectDefinition.outputStructMembers(self) --- 491,495 ---- """ ! class MyObjectDefinition(PEP253Mixin, ObjectIdentityMixin, GlobalObjectDefinition): def outputStructMembers(self): GlobalObjectDefinition.outputStructMembers(self) From jackjansen@users.sourceforge.net Tue Dec 3 23:40:52 2002 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 03 Dec 2002 15:40:52 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules/icn icnsupport.py,1.8,1.9 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules/icn In directory sc8-pr-cvs1:/tmp/cvs-serv10318/icn Modified Files: icnsupport.py Log Message: Added PEP253 support to most Carbon modules. This isn't complete yet: some of the more compilcated cases (CF, Res) haven't been done yet. Also, various types should inherit from each other (anything with an as_Resource method should be a Resource subtype, the CF types should become one family). Index: icnsupport.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/icn/icnsupport.py,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** icnsupport.py 29 Nov 2002 23:40:43 -0000 1.8 --- icnsupport.py 3 Dec 2002 23:40:20 -0000 1.9 *************** *** 55,59 **** """ ! class MyObjectDefinition(PEP252Mixin, GlobalObjectDefinition): def outputCheckNewArg(self): Output("if (itself == NULL) return PyMac_Error(resNotFound);") --- 55,59 ---- """ ! class MyObjectDefinition(PEP253Mixin, GlobalObjectDefinition): def outputCheckNewArg(self): Output("if (itself == NULL) return PyMac_Error(resNotFound);") From jackjansen@users.sourceforge.net Tue Dec 3 23:40:52 2002 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 03 Dec 2002 15:40:52 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules/dlg _Dlgmodule.c,1.12,1.13 dlgsupport.py,1.29,1.30 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules/dlg In directory sc8-pr-cvs1:/tmp/cvs-serv10318/dlg Modified Files: _Dlgmodule.c dlgsupport.py Log Message: Added PEP253 support to most Carbon modules. This isn't complete yet: some of the more compilcated cases (CF, Res) haven't been done yet. Also, various types should inherit from each other (anything with an as_Resource method should be a Resource subtype, the CF types should become one family). Index: _Dlgmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/dlg/_Dlgmodule.c,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** _Dlgmodule.c 29 Nov 2002 23:40:42 -0000 1.12 --- _Dlgmodule.c 3 Dec 2002 23:40:20 -0000 1.13 *************** *** 967,970 **** --- 967,971 ---- #define DlgObj_getsetlist NULL + static int DlgObj_compare(DialogObject *self, DialogObject *other) { *************** *** 980,983 **** --- 981,1002 ---- return (int)self->ob_itself; } + #define DlgObj_tp_init 0 + + #define DlgObj_tp_alloc PyType_GenericAlloc + + static PyObject *DlgObj_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + DialogPtr itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, DlgObj_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((DialogObject *)self)->ob_itself = itself; + return self; + } + + #define DlgObj_tp_free PyObject_Del + PyTypeObject Dialog_Type = { *************** *** 1002,1018 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ DlgObj_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ DlgObj_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 1021,1045 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ DlgObj_methods, /* tp_methods */ ! 0, /*tp_members*/ DlgObj_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! DlgObj_tp_init, /* tp_init */ ! DlgObj_tp_alloc, /* tp_alloc */ ! DlgObj_tp_new, /* tp_new */ ! DlgObj_tp_free, /* tp_free */ }; *************** *** 1590,1595 **** Dialog_Type.ob_type = &PyType_Type; Py_INCREF(&Dialog_Type); ! if (PyDict_SetItemString(d, "DialogType", (PyObject *)&Dialog_Type) != 0) ! Py_FatalError("can't initialize DialogType"); } --- 1617,1624 ---- Dialog_Type.ob_type = &PyType_Type; Py_INCREF(&Dialog_Type); ! PyModule_AddObject(m, "Dialog", (PyObject *)&Dialog_Type); ! /* Backward-compatible name */ ! Py_INCREF(&Dialog_Type); ! PyModule_AddObject(m, "DialogType", (PyObject *)&Dialog_Type); } Index: dlgsupport.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/dlg/dlgsupport.py,v retrieving revision 1.29 retrieving revision 1.30 diff -C2 -d -r1.29 -r1.30 *** dlgsupport.py 29 Nov 2002 23:40:42 -0000 1.29 --- dlgsupport.py 3 Dec 2002 23:40:20 -0000 1.30 *************** *** 202,206 **** # Define a class which specializes our object definition ! class MyObjectDefinition(PEP252Mixin, GlobalObjectDefinition): def __init__(self, name, prefix = None, itselftype = None): GlobalObjectDefinition.__init__(self, name, prefix, itselftype) --- 202,206 ---- # Define a class which specializes our object definition ! class MyObjectDefinition(PEP253Mixin, GlobalObjectDefinition): def __init__(self, name, prefix = None, itselftype = None): GlobalObjectDefinition.__init__(self, name, prefix, itselftype) From jackjansen@users.sourceforge.net Tue Dec 3 23:40:52 2002 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 03 Dec 2002 15:40:52 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules/list _Listmodule.c,1.12,1.13 listsupport.py,1.15,1.16 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules/list In directory sc8-pr-cvs1:/tmp/cvs-serv10318/list Modified Files: _Listmodule.c listsupport.py Log Message: Added PEP253 support to most Carbon modules. This isn't complete yet: some of the more compilcated cases (CF, Res) haven't been done yet. Also, various types should inherit from each other (anything with an as_Resource method should be a Resource subtype, the CF types should become one family). Index: _Listmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/list/_Listmodule.c,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** _Listmodule.c 29 Nov 2002 23:40:44 -0000 1.12 --- _Listmodule.c 3 Dec 2002 23:40:20 -0000 1.13 *************** *** 807,810 **** --- 807,828 ---- #define ListObj_hash NULL + #define ListObj_tp_init 0 + + #define ListObj_tp_alloc PyType_GenericAlloc + + static PyObject *ListObj_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + ListHandle itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, ListObj_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((ListObject *)self)->ob_itself = itself; + return self; + } + + #define ListObj_tp_free PyObject_Del + PyTypeObject List_Type = { *************** *** 829,845 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ ListObj_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ ListObj_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 847,871 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ ListObj_methods, /* tp_methods */ ! 0, /*tp_members*/ ListObj_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! ListObj_tp_init, /* tp_init */ ! ListObj_tp_alloc, /* tp_alloc */ ! ListObj_tp_new, /* tp_new */ ! ListObj_tp_free, /* tp_free */ }; *************** *** 1187,1192 **** List_Type.ob_type = &PyType_Type; Py_INCREF(&List_Type); ! if (PyDict_SetItemString(d, "ListType", (PyObject *)&List_Type) != 0) ! Py_FatalError("can't initialize ListType"); } --- 1213,1220 ---- List_Type.ob_type = &PyType_Type; Py_INCREF(&List_Type); ! PyModule_AddObject(m, "List", (PyObject *)&List_Type); ! /* Backward-compatible name */ ! Py_INCREF(&List_Type); ! PyModule_AddObject(m, "ListType", (PyObject *)&List_Type); } Index: listsupport.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/list/listsupport.py,v retrieving revision 1.15 retrieving revision 1.16 diff -C2 -d -r1.15 -r1.16 *** listsupport.py 29 Nov 2002 23:40:44 -0000 1.15 --- listsupport.py 3 Dec 2002 23:40:20 -0000 1.16 *************** *** 138,142 **** self.argumentList.append(self.itself) ! class MyObjectDefinition(PEP252Mixin, GlobalObjectDefinition): getsetlist = [( 'listFlags', --- 138,143 ---- self.argumentList.append(self.itself) ! class MyObjectDefinition(PEP253Mixin, GlobalObjectDefinition): ! # XXXX Should inherit from Resource getsetlist = [( 'listFlags', From jackjansen@users.sourceforge.net Tue Dec 3 23:40:52 2002 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 03 Dec 2002 15:40:52 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules/ibcarbon IBCarbonsupport.py,1.3,1.4 _IBCarbon.c,1.4,1.5 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules/ibcarbon In directory sc8-pr-cvs1:/tmp/cvs-serv10318/ibcarbon Modified Files: IBCarbonsupport.py _IBCarbon.c Log Message: Added PEP253 support to most Carbon modules. This isn't complete yet: some of the more compilcated cases (CF, Res) haven't been done yet. Also, various types should inherit from each other (anything with an as_Resource method should be a Resource subtype, the CF types should become one family). Index: IBCarbonsupport.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/ibcarbon/IBCarbonsupport.py,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** IBCarbonsupport.py 29 Nov 2002 23:40:43 -0000 1.3 --- IBCarbonsupport.py 3 Dec 2002 23:40:20 -0000 1.4 *************** *** 32,40 **** module = MacModule('_IBCarbon', 'IBCarbon', includestuff, finalstuff, initstuff) ! class CFReleaserObject(PEP252Mixin, GlobalObjectDefinition): def outputFreeIt(self, name): Output("CFRelease(%s);" % name) ! class CFNibDesc(PEP252Mixin, GlobalObjectDefinition): def outputFreeIt(self, name): Output("DisposeNibReference(%s);" % name) --- 32,40 ---- module = MacModule('_IBCarbon', 'IBCarbon', includestuff, finalstuff, initstuff) ! class CFReleaserObject(PEP253Mixin, GlobalObjectDefinition): def outputFreeIt(self, name): Output("CFRelease(%s);" % name) ! class CFNibDesc(PEP253Mixin, GlobalObjectDefinition): def outputFreeIt(self, name): Output("DisposeNibReference(%s);" % name) Index: _IBCarbon.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/ibcarbon/_IBCarbon.c,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** _IBCarbon.c 29 Nov 2002 23:40:43 -0000 1.4 --- _IBCarbon.c 3 Dec 2002 23:40:20 -0000 1.5 *************** *** 143,146 **** --- 143,147 ---- #define IBNibRefObj_getsetlist NULL + #define IBNibRefObj_compare NULL *************** *** 148,151 **** --- 149,170 ---- #define IBNibRefObj_hash NULL + #define IBNibRefObj_tp_init 0 + + #define IBNibRefObj_tp_alloc PyType_GenericAlloc + + static PyObject *IBNibRefObj_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + IBNibRef itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, IBNibRefObj_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((IBNibRefObject *)self)->ob_itself = itself; + return self; + } + + #define IBNibRefObj_tp_free PyObject_Del + PyTypeObject IBNibRef_Type = { *************** *** 170,186 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ IBNibRefObj_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ IBNibRefObj_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 189,213 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ IBNibRefObj_methods, /* tp_methods */ ! 0, /*tp_members*/ IBNibRefObj_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! IBNibRefObj_tp_init, /* tp_init */ ! IBNibRefObj_tp_alloc, /* tp_alloc */ ! IBNibRefObj_tp_new, /* tp_new */ ! IBNibRefObj_tp_free, /* tp_free */ }; *************** *** 231,236 **** IBNibRef_Type.ob_type = &PyType_Type; Py_INCREF(&IBNibRef_Type); ! if (PyDict_SetItemString(d, "IBNibRefType", (PyObject *)&IBNibRef_Type) != 0) ! Py_FatalError("can't initialize IBNibRefType"); } --- 258,265 ---- IBNibRef_Type.ob_type = &PyType_Type; Py_INCREF(&IBNibRef_Type); ! PyModule_AddObject(m, "IBNibRef", (PyObject *)&IBNibRef_Type); ! /* Backward-compatible name */ ! Py_INCREF(&IBNibRef_Type); ! PyModule_AddObject(m, "IBNibRefType", (PyObject *)&IBNibRef_Type); } From jackjansen@users.sourceforge.net Tue Dec 3 23:40:53 2002 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 03 Dec 2002 15:40:53 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules/menu _Menumodule.c,1.13,1.14 menusupport.py,1.18,1.19 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules/menu In directory sc8-pr-cvs1:/tmp/cvs-serv10318/menu Modified Files: _Menumodule.c menusupport.py Log Message: Added PEP253 support to most Carbon modules. This isn't complete yet: some of the more compilcated cases (CF, Res) haven't been done yet. Also, various types should inherit from each other (anything with an as_Resource method should be a Resource subtype, the CF types should become one family). Index: _Menumodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/menu/_Menumodule.c,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** _Menumodule.c 29 Nov 2002 23:40:44 -0000 1.13 --- _Menumodule.c 3 Dec 2002 23:40:20 -0000 1.14 *************** *** 3003,3006 **** --- 3003,3007 ---- #define MenuObj_getsetlist NULL + #define MenuObj_compare NULL *************** *** 3008,3011 **** --- 3009,3030 ---- #define MenuObj_hash NULL + #define MenuObj_tp_init 0 + + #define MenuObj_tp_alloc PyType_GenericAlloc + + static PyObject *MenuObj_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + MenuHandle itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, MenuObj_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((MenuObject *)self)->ob_itself = itself; + return self; + } + + #define MenuObj_tp_free PyObject_Del + PyTypeObject Menu_Type = { *************** *** 3030,3046 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ MenuObj_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ MenuObj_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 3049,3073 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ MenuObj_methods, /* tp_methods */ ! 0, /*tp_members*/ MenuObj_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! MenuObj_tp_init, /* tp_init */ ! MenuObj_tp_alloc, /* tp_alloc */ ! MenuObj_tp_new, /* tp_new */ ! MenuObj_tp_free, /* tp_free */ }; *************** *** 4128,4133 **** Menu_Type.ob_type = &PyType_Type; Py_INCREF(&Menu_Type); ! if (PyDict_SetItemString(d, "MenuType", (PyObject *)&Menu_Type) != 0) ! Py_FatalError("can't initialize MenuType"); } --- 4155,4162 ---- Menu_Type.ob_type = &PyType_Type; Py_INCREF(&Menu_Type); ! PyModule_AddObject(m, "Menu", (PyObject *)&Menu_Type); ! /* Backward-compatible name */ ! Py_INCREF(&Menu_Type); ! PyModule_AddObject(m, "MenuType", (PyObject *)&Menu_Type); } Index: menusupport.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/menu/menusupport.py,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** menusupport.py 29 Nov 2002 23:40:44 -0000 1.18 --- menusupport.py 3 Dec 2002 23:40:20 -0000 1.19 *************** *** 99,103 **** """ ! class MyObjectDefinition(PEP252Mixin, GlobalObjectDefinition): pass --- 99,103 ---- """ ! class MyObjectDefinition(PEP253Mixin, GlobalObjectDefinition): pass From jackjansen@users.sourceforge.net Tue Dec 3 23:40:51 2002 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 03 Dec 2002 15:40:51 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules/carbonevt CarbonEvtsupport.py,1.11,1.12 _CarbonEvtmodule.c,1.11,1.12 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules/carbonevt In directory sc8-pr-cvs1:/tmp/cvs-serv10318/carbonevt Modified Files: CarbonEvtsupport.py _CarbonEvtmodule.c Log Message: Added PEP253 support to most Carbon modules. This isn't complete yet: some of the more compilcated cases (CF, Res) haven't been done yet. Also, various types should inherit from each other (anything with an as_Resource method should be a Resource subtype, the CF types should become one family). Index: CarbonEvtsupport.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/carbonevt/CarbonEvtsupport.py,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** CarbonEvtsupport.py 29 Nov 2002 23:40:42 -0000 1.11 --- CarbonEvtsupport.py 3 Dec 2002 23:40:19 -0000 1.12 *************** *** 216,220 **** ! class EventHandlerRefObjectDefinition(PEP252Mixin, GlobalObjectDefinition): def outputStructMembers(self): Output("%s ob_itself;", self.itselftype) --- 216,220 ---- ! class EventHandlerRefObjectDefinition(PEP253Mixin, GlobalObjectDefinition): def outputStructMembers(self): Output("%s ob_itself;", self.itselftype) *************** *** 229,233 **** OutRbrace() ! class MyGlobalObjectDefinition(PEP252Mixin, GlobalObjectDefinition): pass --- 229,233 ---- OutRbrace() ! class MyGlobalObjectDefinition(PEP253Mixin, GlobalObjectDefinition): pass Index: _CarbonEvtmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/carbonevt/_CarbonEvtmodule.c,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** _CarbonEvtmodule.c 29 Nov 2002 23:40:42 -0000 1.11 --- _CarbonEvtmodule.c 3 Dec 2002 23:40:19 -0000 1.12 *************** *** 411,414 **** --- 411,415 ---- #define EventRef_getsetlist NULL + #define EventRef_compare NULL *************** *** 416,419 **** --- 417,438 ---- #define EventRef_hash NULL + #define EventRef_tp_init 0 + + #define EventRef_tp_alloc PyType_GenericAlloc + + static PyObject *EventRef_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + EventRef itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, EventRef_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((EventRefObject *)self)->ob_itself = itself; + return self; + } + + #define EventRef_tp_free PyObject_Del + PyTypeObject EventRef_Type = { *************** *** 438,454 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ EventRef_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ EventRef_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 457,481 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ EventRef_methods, /* tp_methods */ ! 0, /*tp_members*/ EventRef_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! EventRef_tp_init, /* tp_init */ ! EventRef_tp_alloc, /* tp_alloc */ ! EventRef_tp_new, /* tp_new */ ! EventRef_tp_free, /* tp_free */ }; *************** *** 604,607 **** --- 631,635 ---- #define EventQueueRef_getsetlist NULL + #define EventQueueRef_compare NULL *************** *** 609,612 **** --- 637,658 ---- #define EventQueueRef_hash NULL + #define EventQueueRef_tp_init 0 + + #define EventQueueRef_tp_alloc PyType_GenericAlloc + + static PyObject *EventQueueRef_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + EventQueueRef itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, EventQueueRef_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((EventQueueRefObject *)self)->ob_itself = itself; + return self; + } + + #define EventQueueRef_tp_free PyObject_Del + PyTypeObject EventQueueRef_Type = { *************** *** 631,647 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ EventQueueRef_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ EventQueueRef_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 677,701 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ EventQueueRef_methods, /* tp_methods */ ! 0, /*tp_members*/ EventQueueRef_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! EventQueueRef_tp_init, /* tp_init */ ! EventQueueRef_tp_alloc, /* tp_alloc */ ! EventQueueRef_tp_new, /* tp_new */ ! EventQueueRef_tp_free, /* tp_free */ }; *************** *** 706,709 **** --- 760,764 ---- #define EventLoopRef_getsetlist NULL + #define EventLoopRef_compare NULL *************** *** 711,714 **** --- 766,787 ---- #define EventLoopRef_hash NULL + #define EventLoopRef_tp_init 0 + + #define EventLoopRef_tp_alloc PyType_GenericAlloc + + static PyObject *EventLoopRef_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + EventLoopRef itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, EventLoopRef_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((EventLoopRefObject *)self)->ob_itself = itself; + return self; + } + + #define EventLoopRef_tp_free PyObject_Del + PyTypeObject EventLoopRef_Type = { *************** *** 733,749 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ EventLoopRef_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ EventLoopRef_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 806,830 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ EventLoopRef_methods, /* tp_methods */ ! 0, /*tp_members*/ EventLoopRef_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! EventLoopRef_tp_init, /* tp_init */ ! EventLoopRef_tp_alloc, /* tp_alloc */ ! EventLoopRef_tp_new, /* tp_new */ ! EventLoopRef_tp_free, /* tp_free */ }; *************** *** 826,829 **** --- 907,911 ---- #define EventLoopTimerRef_getsetlist NULL + #define EventLoopTimerRef_compare NULL *************** *** 831,834 **** --- 913,934 ---- #define EventLoopTimerRef_hash NULL + #define EventLoopTimerRef_tp_init 0 + + #define EventLoopTimerRef_tp_alloc PyType_GenericAlloc + + static PyObject *EventLoopTimerRef_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + EventLoopTimerRef itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, EventLoopTimerRef_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((EventLoopTimerRefObject *)self)->ob_itself = itself; + return self; + } + + #define EventLoopTimerRef_tp_free PyObject_Del + PyTypeObject EventLoopTimerRef_Type = { *************** *** 853,869 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ EventLoopTimerRef_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ EventLoopTimerRef_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 953,977 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ EventLoopTimerRef_methods, /* tp_methods */ ! 0, /*tp_members*/ EventLoopTimerRef_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! EventLoopTimerRef_tp_init, /* tp_init */ ! EventLoopTimerRef_tp_alloc, /* tp_alloc */ ! EventLoopTimerRef_tp_new, /* tp_new */ ! EventLoopTimerRef_tp_free, /* tp_free */ }; *************** *** 991,994 **** --- 1099,1103 ---- #define EventHandlerRef_getsetlist NULL + #define EventHandlerRef_compare NULL *************** *** 996,999 **** --- 1105,1126 ---- #define EventHandlerRef_hash NULL + #define EventHandlerRef_tp_init 0 + + #define EventHandlerRef_tp_alloc PyType_GenericAlloc + + static PyObject *EventHandlerRef_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + EventHandlerRef itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, EventHandlerRef_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((EventHandlerRefObject *)self)->ob_itself = itself; + return self; + } + + #define EventHandlerRef_tp_free PyObject_Del + PyTypeObject EventHandlerRef_Type = { *************** *** 1018,1034 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ EventHandlerRef_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ EventHandlerRef_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 1145,1169 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ EventHandlerRef_methods, /* tp_methods */ ! 0, /*tp_members*/ EventHandlerRef_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! EventHandlerRef_tp_init, /* tp_init */ ! EventHandlerRef_tp_alloc, /* tp_alloc */ ! EventHandlerRef_tp_new, /* tp_new */ ! EventHandlerRef_tp_free, /* tp_free */ }; *************** *** 1096,1099 **** --- 1231,1235 ---- #define EventHandlerCallRef_getsetlist NULL + #define EventHandlerCallRef_compare NULL *************** *** 1101,1104 **** --- 1237,1258 ---- #define EventHandlerCallRef_hash NULL + #define EventHandlerCallRef_tp_init 0 + + #define EventHandlerCallRef_tp_alloc PyType_GenericAlloc + + static PyObject *EventHandlerCallRef_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + EventHandlerCallRef itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, EventHandlerCallRef_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((EventHandlerCallRefObject *)self)->ob_itself = itself; + return self; + } + + #define EventHandlerCallRef_tp_free PyObject_Del + PyTypeObject EventHandlerCallRef_Type = { *************** *** 1123,1139 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ EventHandlerCallRef_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ EventHandlerCallRef_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 1277,1301 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ EventHandlerCallRef_methods, /* tp_methods */ ! 0, /*tp_members*/ EventHandlerCallRef_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! EventHandlerCallRef_tp_init, /* tp_init */ ! EventHandlerCallRef_tp_alloc, /* tp_alloc */ ! EventHandlerCallRef_tp_new, /* tp_new */ ! EventHandlerCallRef_tp_free, /* tp_free */ }; *************** *** 1223,1226 **** --- 1385,1389 ---- #define EventTargetRef_getsetlist NULL + #define EventTargetRef_compare NULL *************** *** 1228,1231 **** --- 1391,1412 ---- #define EventTargetRef_hash NULL + #define EventTargetRef_tp_init 0 + + #define EventTargetRef_tp_alloc PyType_GenericAlloc + + static PyObject *EventTargetRef_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + EventTargetRef itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, EventTargetRef_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((EventTargetRefObject *)self)->ob_itself = itself; + return self; + } + + #define EventTargetRef_tp_free PyObject_Del + PyTypeObject EventTargetRef_Type = { *************** *** 1250,1266 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ EventTargetRef_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ EventTargetRef_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 1431,1455 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ EventTargetRef_methods, /* tp_methods */ ! 0, /*tp_members*/ EventTargetRef_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! EventTargetRef_tp_init, /* tp_init */ ! EventTargetRef_tp_alloc, /* tp_alloc */ ! EventTargetRef_tp_new, /* tp_new */ ! EventTargetRef_tp_free, /* tp_free */ }; *************** *** 1325,1328 **** --- 1514,1518 ---- #define EventHotKeyRef_getsetlist NULL + #define EventHotKeyRef_compare NULL *************** *** 1330,1333 **** --- 1520,1541 ---- #define EventHotKeyRef_hash NULL + #define EventHotKeyRef_tp_init 0 + + #define EventHotKeyRef_tp_alloc PyType_GenericAlloc + + static PyObject *EventHotKeyRef_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + EventHotKeyRef itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, EventHotKeyRef_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((EventHotKeyRefObject *)self)->ob_itself = itself; + return self; + } + + #define EventHotKeyRef_tp_free PyObject_Del + PyTypeObject EventHotKeyRef_Type = { *************** *** 1352,1368 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ EventHotKeyRef_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ EventHotKeyRef_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 1560,1584 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ EventHotKeyRef_methods, /* tp_methods */ ! 0, /*tp_members*/ EventHotKeyRef_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! EventHotKeyRef_tp_init, /* tp_init */ ! EventHotKeyRef_tp_alloc, /* tp_alloc */ ! EventHotKeyRef_tp_new, /* tp_new */ ! EventHotKeyRef_tp_free, /* tp_free */ }; *************** *** 1943,1976 **** EventRef_Type.ob_type = &PyType_Type; Py_INCREF(&EventRef_Type); ! if (PyDict_SetItemString(d, "EventRefType", (PyObject *)&EventRef_Type) != 0) ! Py_FatalError("can't initialize EventRefType"); EventQueueRef_Type.ob_type = &PyType_Type; Py_INCREF(&EventQueueRef_Type); ! if (PyDict_SetItemString(d, "EventQueueRefType", (PyObject *)&EventQueueRef_Type) != 0) ! Py_FatalError("can't initialize EventQueueRefType"); EventLoopRef_Type.ob_type = &PyType_Type; Py_INCREF(&EventLoopRef_Type); ! if (PyDict_SetItemString(d, "EventLoopRefType", (PyObject *)&EventLoopRef_Type) != 0) ! Py_FatalError("can't initialize EventLoopRefType"); EventLoopTimerRef_Type.ob_type = &PyType_Type; Py_INCREF(&EventLoopTimerRef_Type); ! if (PyDict_SetItemString(d, "EventLoopTimerRefType", (PyObject *)&EventLoopTimerRef_Type) != 0) ! Py_FatalError("can't initialize EventLoopTimerRefType"); EventHandlerRef_Type.ob_type = &PyType_Type; Py_INCREF(&EventHandlerRef_Type); ! if (PyDict_SetItemString(d, "EventHandlerRefType", (PyObject *)&EventHandlerRef_Type) != 0) ! Py_FatalError("can't initialize EventHandlerRefType"); EventHandlerCallRef_Type.ob_type = &PyType_Type; Py_INCREF(&EventHandlerCallRef_Type); ! if (PyDict_SetItemString(d, "EventHandlerCallRefType", (PyObject *)&EventHandlerCallRef_Type) != 0) ! Py_FatalError("can't initialize EventHandlerCallRefType"); EventTargetRef_Type.ob_type = &PyType_Type; Py_INCREF(&EventTargetRef_Type); ! if (PyDict_SetItemString(d, "EventTargetRefType", (PyObject *)&EventTargetRef_Type) != 0) ! Py_FatalError("can't initialize EventTargetRefType"); EventHotKeyRef_Type.ob_type = &PyType_Type; Py_INCREF(&EventHotKeyRef_Type); ! if (PyDict_SetItemString(d, "EventHotKeyRefType", (PyObject *)&EventHotKeyRef_Type) != 0) ! Py_FatalError("can't initialize EventHotKeyRefType"); } --- 2159,2208 ---- EventRef_Type.ob_type = &PyType_Type; Py_INCREF(&EventRef_Type); ! PyModule_AddObject(m, "EventRef", (PyObject *)&EventRef_Type); ! /* Backward-compatible name */ ! Py_INCREF(&EventRef_Type); ! PyModule_AddObject(m, "EventRefType", (PyObject *)&EventRef_Type); EventQueueRef_Type.ob_type = &PyType_Type; Py_INCREF(&EventQueueRef_Type); ! PyModule_AddObject(m, "EventQueueRef", (PyObject *)&EventQueueRef_Type); ! /* Backward-compatible name */ ! Py_INCREF(&EventQueueRef_Type); ! PyModule_AddObject(m, "EventQueueRefType", (PyObject *)&EventQueueRef_Type); EventLoopRef_Type.ob_type = &PyType_Type; Py_INCREF(&EventLoopRef_Type); ! PyModule_AddObject(m, "EventLoopRef", (PyObject *)&EventLoopRef_Type); ! /* Backward-compatible name */ ! Py_INCREF(&EventLoopRef_Type); ! PyModule_AddObject(m, "EventLoopRefType", (PyObject *)&EventLoopRef_Type); EventLoopTimerRef_Type.ob_type = &PyType_Type; Py_INCREF(&EventLoopTimerRef_Type); ! PyModule_AddObject(m, "EventLoopTimerRef", (PyObject *)&EventLoopTimerRef_Type); ! /* Backward-compatible name */ ! Py_INCREF(&EventLoopTimerRef_Type); ! PyModule_AddObject(m, "EventLoopTimerRefType", (PyObject *)&EventLoopTimerRef_Type); EventHandlerRef_Type.ob_type = &PyType_Type; Py_INCREF(&EventHandlerRef_Type); ! PyModule_AddObject(m, "EventHandlerRef", (PyObject *)&EventHandlerRef_Type); ! /* Backward-compatible name */ ! Py_INCREF(&EventHandlerRef_Type); ! PyModule_AddObject(m, "EventHandlerRefType", (PyObject *)&EventHandlerRef_Type); EventHandlerCallRef_Type.ob_type = &PyType_Type; Py_INCREF(&EventHandlerCallRef_Type); ! PyModule_AddObject(m, "EventHandlerCallRef", (PyObject *)&EventHandlerCallRef_Type); ! /* Backward-compatible name */ ! Py_INCREF(&EventHandlerCallRef_Type); ! PyModule_AddObject(m, "EventHandlerCallRefType", (PyObject *)&EventHandlerCallRef_Type); EventTargetRef_Type.ob_type = &PyType_Type; Py_INCREF(&EventTargetRef_Type); ! PyModule_AddObject(m, "EventTargetRef", (PyObject *)&EventTargetRef_Type); ! /* Backward-compatible name */ ! Py_INCREF(&EventTargetRef_Type); ! PyModule_AddObject(m, "EventTargetRefType", (PyObject *)&EventTargetRef_Type); EventHotKeyRef_Type.ob_type = &PyType_Type; Py_INCREF(&EventHotKeyRef_Type); ! PyModule_AddObject(m, "EventHotKeyRef", (PyObject *)&EventHotKeyRef_Type); ! /* Backward-compatible name */ ! Py_INCREF(&EventHotKeyRef_Type); ! PyModule_AddObject(m, "EventHotKeyRefType", (PyObject *)&EventHotKeyRef_Type); } From jackjansen@users.sourceforge.net Tue Dec 3 23:40:24 2002 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 03 Dec 2002 15:40:24 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules/scrap scrapsupport.py,1.7,1.8 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules/scrap In directory sc8-pr-cvs1:/tmp/cvs-serv10318/scrap Modified Files: scrapsupport.py Log Message: Added PEP253 support to most Carbon modules. This isn't complete yet: some of the more compilcated cases (CF, Res) haven't been done yet. Also, various types should inherit from each other (anything with an as_Resource method should be a Resource subtype, the CF types should become one family). Index: scrapsupport.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/scrap/scrapsupport.py,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** scrapsupport.py 29 Nov 2002 23:40:47 -0000 1.7 --- scrapsupport.py 3 Dec 2002 23:40:21 -0000 1.8 *************** *** 56,60 **** putscrapbuffer = FixedInputBufferType('void *') ! class MyObjectDefinition(PEP252Mixin, GlobalObjectDefinition): pass --- 56,60 ---- putscrapbuffer = FixedInputBufferType('void *') ! class MyObjectDefinition(PEP253Mixin, GlobalObjectDefinition): pass From jackjansen@users.sourceforge.net Tue Dec 3 23:40:23 2002 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 03 Dec 2002 15:40:23 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules/mlte _Mltemodule.c,1.13,1.14 mltesupport.py,1.11,1.12 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules/mlte In directory sc8-pr-cvs1:/tmp/cvs-serv10318/mlte Modified Files: _Mltemodule.c mltesupport.py Log Message: Added PEP253 support to most Carbon modules. This isn't complete yet: some of the more compilcated cases (CF, Res) haven't been done yet. Also, various types should inherit from each other (anything with an as_Resource method should be a Resource subtype, the CF types should become one family). Index: _Mltemodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/mlte/_Mltemodule.c,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** _Mltemodule.c 29 Nov 2002 23:40:44 -0000 1.13 --- _Mltemodule.c 3 Dec 2002 23:40:21 -0000 1.14 *************** *** 1298,1301 **** --- 1298,1302 ---- #define TXNObj_getsetlist NULL + #define TXNObj_compare NULL *************** *** 1303,1306 **** --- 1304,1325 ---- #define TXNObj_hash NULL + #define TXNObj_tp_init 0 + + #define TXNObj_tp_alloc PyType_GenericAlloc + + static PyObject *TXNObj_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + TXNObject itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, TXNObj_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((TXNObjectObject *)self)->ob_itself = itself; + return self; + } + + #define TXNObj_tp_free PyObject_Del + PyTypeObject TXNObject_Type = { *************** *** 1325,1341 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ TXNObj_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ TXNObj_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 1344,1368 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ TXNObj_methods, /* tp_methods */ ! 0, /*tp_members*/ TXNObj_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! TXNObj_tp_init, /* tp_init */ ! TXNObj_tp_alloc, /* tp_alloc */ ! TXNObj_tp_new, /* tp_new */ ! TXNObj_tp_free, /* tp_free */ }; *************** *** 1424,1427 **** --- 1451,1455 ---- #define TXNFontMenuObj_getsetlist NULL + #define TXNFontMenuObj_compare NULL *************** *** 1429,1432 **** --- 1457,1478 ---- #define TXNFontMenuObj_hash NULL + #define TXNFontMenuObj_tp_init 0 + + #define TXNFontMenuObj_tp_alloc PyType_GenericAlloc + + static PyObject *TXNFontMenuObj_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + TXNFontMenuObject itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, TXNFontMenuObj_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((TXNFontMenuObjectObject *)self)->ob_itself = itself; + return self; + } + + #define TXNFontMenuObj_tp_free PyObject_Del + PyTypeObject TXNFontMenuObject_Type = { *************** *** 1451,1467 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ TXNFontMenuObj_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ TXNFontMenuObj_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 1497,1521 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ TXNFontMenuObj_methods, /* tp_methods */ ! 0, /*tp_members*/ TXNFontMenuObj_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! TXNFontMenuObj_tp_init, /* tp_init */ ! TXNFontMenuObj_tp_alloc, /* tp_alloc */ ! TXNFontMenuObj_tp_new, /* tp_new */ ! TXNFontMenuObj_tp_free, /* tp_free */ }; *************** *** 1677,1686 **** TXNObject_Type.ob_type = &PyType_Type; Py_INCREF(&TXNObject_Type); ! if (PyDict_SetItemString(d, "TXNObjectType", (PyObject *)&TXNObject_Type) != 0) ! Py_FatalError("can't initialize TXNObjectType"); TXNFontMenuObject_Type.ob_type = &PyType_Type; Py_INCREF(&TXNFontMenuObject_Type); ! if (PyDict_SetItemString(d, "TXNFontMenuObjectType", (PyObject *)&TXNFontMenuObject_Type) != 0) ! Py_FatalError("can't initialize TXNFontMenuObjectType"); } --- 1731,1744 ---- TXNObject_Type.ob_type = &PyType_Type; Py_INCREF(&TXNObject_Type); ! PyModule_AddObject(m, "TXNObject", (PyObject *)&TXNObject_Type); ! /* Backward-compatible name */ ! Py_INCREF(&TXNObject_Type); ! PyModule_AddObject(m, "TXNObjectType", (PyObject *)&TXNObject_Type); TXNFontMenuObject_Type.ob_type = &PyType_Type; Py_INCREF(&TXNFontMenuObject_Type); ! PyModule_AddObject(m, "TXNFontMenuObject", (PyObject *)&TXNFontMenuObject_Type); ! /* Backward-compatible name */ ! Py_INCREF(&TXNFontMenuObject_Type); ! PyModule_AddObject(m, "TXNFontMenuObjectType", (PyObject *)&TXNFontMenuObject_Type); } Index: mltesupport.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/mlte/mltesupport.py,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** mltesupport.py 29 Nov 2002 23:40:44 -0000 1.11 --- mltesupport.py 3 Dec 2002 23:40:21 -0000 1.12 *************** *** 137,145 **** # Our (opaque) objects ! class TXNObjDefinition(PEP252Mixin, GlobalObjectDefinition): def outputCheckNewArg(self): Output("if (itself == NULL) return PyMac_Error(resNotFound);") ! class TXNFontMenuObjDefinition(PEP252Mixin, GlobalObjectDefinition): def outputCheckNewArg(self): Output("if (itself == NULL) return PyMac_Error(resNotFound);") --- 137,145 ---- # Our (opaque) objects ! class TXNObjDefinition(PEP253Mixin, GlobalObjectDefinition): def outputCheckNewArg(self): Output("if (itself == NULL) return PyMac_Error(resNotFound);") ! class TXNFontMenuObjDefinition(PEP253Mixin, GlobalObjectDefinition): def outputCheckNewArg(self): Output("if (itself == NULL) return PyMac_Error(resNotFound);") From jackjansen@users.sourceforge.net Tue Dec 3 23:40:25 2002 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 03 Dec 2002 15:40:25 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules/win _Winmodule.c,1.12,1.13 winsupport.py,1.32,1.33 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules/win In directory sc8-pr-cvs1:/tmp/cvs-serv10318/win Modified Files: _Winmodule.c winsupport.py Log Message: Added PEP253 support to most Carbon modules. This isn't complete yet: some of the more compilcated cases (CF, Res) haven't been done yet. Also, various types should inherit from each other (anything with an as_Resource method should be a Resource subtype, the CF types should become one family). Index: _Winmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/win/_Winmodule.c,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** _Winmodule.c 29 Nov 2002 23:40:47 -0000 1.12 --- _Winmodule.c 3 Dec 2002 23:40:22 -0000 1.13 *************** *** 78,81 **** --- 78,82 ---- WindowObject *it; if (itself == NULL) return PyMac_Error(resNotFound); + /* XXXX Or should we use WhichWindow code here? */ it = PyObject_NEW(WindowObject, &Window_Type); if (it == NULL) return NULL; *************** *** 2929,2932 **** --- 2930,2934 ---- #define WinObj_getsetlist NULL + static int WinObj_compare(WindowObject *self, WindowObject *other) { *************** *** 2947,2950 **** --- 2949,2970 ---- return (int)self->ob_itself; } + #define WinObj_tp_init 0 + + #define WinObj_tp_alloc PyType_GenericAlloc + + static PyObject *WinObj_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + WindowPtr itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, WinObj_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((WindowObject *)self)->ob_itself = itself; + return self; + } + + #define WinObj_tp_free PyObject_Del + PyTypeObject Window_Type = { *************** *** 2969,2985 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ WinObj_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ WinObj_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 2989,3013 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ WinObj_methods, /* tp_methods */ ! 0, /*tp_members*/ WinObj_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! WinObj_tp_init, /* tp_init */ ! WinObj_tp_alloc, /* tp_alloc */ ! WinObj_tp_new, /* tp_new */ ! WinObj_tp_free, /* tp_free */ }; *************** *** 3829,3834 **** Window_Type.ob_type = &PyType_Type; Py_INCREF(&Window_Type); ! if (PyDict_SetItemString(d, "WindowType", (PyObject *)&Window_Type) != 0) ! Py_FatalError("can't initialize WindowType"); } --- 3857,3864 ---- Window_Type.ob_type = &PyType_Type; Py_INCREF(&Window_Type); ! PyModule_AddObject(m, "Window", (PyObject *)&Window_Type); ! /* Backward-compatible name */ ! Py_INCREF(&Window_Type); ! PyModule_AddObject(m, "WindowType", (PyObject *)&Window_Type); } Index: winsupport.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/win/winsupport.py,v retrieving revision 1.32 retrieving revision 1.33 diff -C2 -d -r1.32 -r1.33 *** winsupport.py 29 Nov 2002 23:40:48 -0000 1.32 --- winsupport.py 3 Dec 2002 23:40:22 -0000 1.33 *************** *** 129,135 **** """ ! class MyObjectDefinition(PEP252Mixin, GlobalObjectDefinition): def outputCheckNewArg(self): Output("if (itself == NULL) return PyMac_Error(resNotFound);") def outputStructMembers(self): GlobalObjectDefinition.outputStructMembers(self) --- 129,136 ---- """ ! class MyObjectDefinition(PEP253Mixin, GlobalObjectDefinition): def outputCheckNewArg(self): Output("if (itself == NULL) return PyMac_Error(resNotFound);") + Output("/* XXXX Or should we use WhichWindow code here? */") def outputStructMembers(self): GlobalObjectDefinition.outputStructMembers(self) From jackjansen@users.sourceforge.net Tue Dec 3 23:40:23 2002 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 03 Dec 2002 15:40:23 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules/qd _Qdmodule.c,1.12,1.13 qdsupport.py,1.40,1.41 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules/qd In directory sc8-pr-cvs1:/tmp/cvs-serv10318/qd Modified Files: _Qdmodule.c qdsupport.py Log Message: Added PEP253 support to most Carbon modules. This isn't complete yet: some of the more compilcated cases (CF, Res) haven't been done yet. Also, various types should inherit from each other (anything with an as_Resource method should be a Resource subtype, the CF types should become one family). Index: _Qdmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/qd/_Qdmodule.c,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** _Qdmodule.c 29 Nov 2002 23:40:44 -0000 1.12 --- _Qdmodule.c 3 Dec 2002 23:40:21 -0000 1.13 *************** *** 1116,1119 **** --- 1116,1137 ---- #define GrafObj_hash NULL + #define GrafObj_tp_init 0 + + #define GrafObj_tp_alloc PyType_GenericAlloc + + static PyObject *GrafObj_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + GrafPtr itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, GrafObj_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((GrafPortObject *)self)->ob_itself = itself; + return self; + } + + #define GrafObj_tp_free PyObject_Del + PyTypeObject GrafPort_Type = { *************** *** 1138,1154 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ GrafObj_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ GrafObj_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 1156,1180 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ GrafObj_methods, /* tp_methods */ ! 0, /*tp_members*/ GrafObj_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! GrafObj_tp_init, /* tp_init */ ! GrafObj_tp_alloc, /* tp_alloc */ ! GrafObj_tp_new, /* tp_new */ ! GrafObj_tp_free, /* tp_free */ }; *************** *** 1288,1291 **** --- 1314,1335 ---- #define BMObj_hash NULL + #define BMObj_tp_init 0 + + #define BMObj_tp_alloc PyType_GenericAlloc + + static PyObject *BMObj_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + BitMapPtr itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, BMObj_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((BitMapObject *)self)->ob_itself = itself; + return self; + } + + #define BMObj_tp_free PyObject_Del + PyTypeObject BitMap_Type = { *************** *** 1310,1326 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ BMObj_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ BMObj_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 1354,1378 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ BMObj_methods, /* tp_methods */ ! 0, /*tp_members*/ BMObj_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! BMObj_tp_init, /* tp_init */ ! BMObj_tp_alloc, /* tp_alloc */ ! BMObj_tp_new, /* tp_new */ ! BMObj_tp_free, /* tp_free */ }; *************** *** 6873,6882 **** GrafPort_Type.ob_type = &PyType_Type; Py_INCREF(&GrafPort_Type); ! if (PyDict_SetItemString(d, "GrafPortType", (PyObject *)&GrafPort_Type) != 0) ! Py_FatalError("can't initialize GrafPortType"); BitMap_Type.ob_type = &PyType_Type; Py_INCREF(&BitMap_Type); ! if (PyDict_SetItemString(d, "BitMapType", (PyObject *)&BitMap_Type) != 0) ! Py_FatalError("can't initialize BitMapType"); } --- 6925,6938 ---- GrafPort_Type.ob_type = &PyType_Type; Py_INCREF(&GrafPort_Type); ! PyModule_AddObject(m, "GrafPort", (PyObject *)&GrafPort_Type); ! /* Backward-compatible name */ ! Py_INCREF(&GrafPort_Type); ! PyModule_AddObject(m, "GrafPortType", (PyObject *)&GrafPort_Type); BitMap_Type.ob_type = &PyType_Type; Py_INCREF(&BitMap_Type); ! PyModule_AddObject(m, "BitMap", (PyObject *)&BitMap_Type); ! /* Backward-compatible name */ ! Py_INCREF(&BitMap_Type); ! PyModule_AddObject(m, "BitMapType", (PyObject *)&BitMap_Type); } Index: qdsupport.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/qd/qdsupport.py,v retrieving revision 1.40 retrieving revision 1.41 diff -C2 -d -r1.40 -r1.41 *** qdsupport.py 29 Nov 2002 23:40:46 -0000 1.40 --- qdsupport.py 3 Dec 2002 23:40:21 -0000 1.41 *************** *** 237,241 **** ## Output("KillPoly(%s);", itselfname) ! class MyGRObjectDefinition(PEP252Mixin, GlobalObjectDefinition): getsetlist = [ ('visRgn', --- 237,241 ---- ## Output("KillPoly(%s);", itselfname) ! class MyGRObjectDefinition(PEP253Mixin, GlobalObjectDefinition): getsetlist = [ ('visRgn', *************** *** 278,282 **** Output("#endif") ! class MyBMObjectDefinition(PEP252Mixin, GlobalObjectDefinition): getsetlist = [ ( --- 278,282 ---- Output("#endif") ! class MyBMObjectDefinition(PEP253Mixin, GlobalObjectDefinition): getsetlist = [ ( From jackjansen@users.sourceforge.net Tue Dec 3 23:40:24 2002 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 03 Dec 2002 15:40:24 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules/snd _Sndmodule.c,1.11,1.12 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules/snd In directory sc8-pr-cvs1:/tmp/cvs-serv10318/snd Modified Files: _Sndmodule.c Log Message: Added PEP253 support to most Carbon modules. This isn't complete yet: some of the more compilcated cases (CF, Res) haven't been done yet. Also, various types should inherit from each other (anything with an as_Resource method should be a Resource subtype, the CF types should become one family). Index: _Sndmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/snd/_Sndmodule.c,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** _Sndmodule.c 29 Nov 2002 23:40:47 -0000 1.11 --- _Sndmodule.c 3 Dec 2002 23:40:21 -0000 1.12 *************** *** 331,347 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ SndCh_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ SndCh_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 331,355 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ SndCh_methods, /* tp_methods */ ! 0, /*tp_members*/ SndCh_getsetlist, /*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*/ ! 0, /*tp_new*/ ! 0, /*tp_free*/ }; *************** *** 460,463 **** --- 468,472 ---- {"error", (getter)SPBObj_get_error, (setter)SPBObj_set_error, NULL}, {"completionRoutine", (getter)SPBObj_get_completionRoutine, (setter)SPBObj_set_completionRoutine, NULL}, + {NULL, NULL, NULL, NULL}, }; *************** *** 490,506 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ SPBObj_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ SPBObj_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 499,523 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ SPBObj_methods, /* tp_methods */ ! 0, /*tp_members*/ SPBObj_getsetlist, /*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*/ ! 0, /*tp_new*/ ! 0, /*tp_free*/ }; *************** *** 1538,1547 **** SndChannel_Type.ob_type = &PyType_Type; Py_INCREF(&SndChannel_Type); ! if (PyDict_SetItemString(d, "SndChannelType", (PyObject *)&SndChannel_Type) != 0) ! Py_FatalError("can't initialize SndChannelType"); SPB_Type.ob_type = &PyType_Type; Py_INCREF(&SPB_Type); ! if (PyDict_SetItemString(d, "SPBType", (PyObject *)&SPB_Type) != 0) ! Py_FatalError("can't initialize SPBType"); } --- 1555,1568 ---- SndChannel_Type.ob_type = &PyType_Type; Py_INCREF(&SndChannel_Type); ! PyModule_AddObject(m, "SndChannel", (PyObject *)&SndChannel_Type); ! /* Backward-compatible name */ ! Py_INCREF(&SndChannel_Type); ! PyModule_AddObject(m, "SndChannelType", (PyObject *)&SndChannel_Type); SPB_Type.ob_type = &PyType_Type; Py_INCREF(&SPB_Type); ! PyModule_AddObject(m, "SPB", (PyObject *)&SPB_Type); ! /* Backward-compatible name */ ! Py_INCREF(&SPB_Type); ! PyModule_AddObject(m, "SPBType", (PyObject *)&SPB_Type); } From jackjansen@users.sourceforge.net Tue Dec 3 23:40:24 2002 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 03 Dec 2002 15:40:24 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules/waste wastemodule.c,1.27,1.28 wastesupport.py,1.18,1.19 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules/waste In directory sc8-pr-cvs1:/tmp/cvs-serv10318/waste Modified Files: wastemodule.c wastesupport.py Log Message: Added PEP253 support to most Carbon modules. This isn't complete yet: some of the more compilcated cases (CF, Res) haven't been done yet. Also, various types should inherit from each other (anything with an as_Resource method should be a Resource subtype, the CF types should become one family). Index: wastemodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/waste/wastemodule.c,v retrieving revision 1.27 retrieving revision 1.28 diff -C2 -d -r1.27 -r1.28 *** wastemodule.c 29 Nov 2002 23:40:47 -0000 1.27 --- wastemodule.c 3 Dec 2002 23:40:22 -0000 1.28 *************** *** 387,390 **** --- 387,391 ---- #define WEOObj_getsetlist NULL + #define WEOObj_compare NULL *************** *** 392,395 **** --- 393,414 ---- #define WEOObj_hash NULL + #define WEOObj_tp_init 0 + + #define WEOObj_tp_alloc PyType_GenericAlloc + + static PyObject *WEOObj_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + WEObjectReference itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, WEOObj_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((WEOObject *)self)->ob_itself = itself; + return self; + } + + #define WEOObj_tp_free PyObject_Del + PyTypeObject WEO_Type = { *************** *** 414,430 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ WEOObj_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ WEOObj_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 433,457 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ WEOObj_methods, /* tp_methods */ ! 0, /*tp_members*/ WEOObj_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! WEOObj_tp_init, /* tp_init */ ! WEOObj_tp_alloc, /* tp_alloc */ ! WEOObj_tp_new, /* tp_new */ ! WEOObj_tp_free, /* tp_free */ }; *************** *** 2109,2112 **** --- 2136,2140 ---- #define wasteObj_getsetlist NULL + #define wasteObj_compare NULL *************** *** 2114,2117 **** --- 2142,2163 ---- #define wasteObj_hash NULL + #define wasteObj_tp_init 0 + + #define wasteObj_tp_alloc PyType_GenericAlloc + + static PyObject *wasteObj_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + WEReference itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, wasteObj_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((wasteObject *)self)->ob_itself = itself; + return self; + } + + #define wasteObj_tp_free PyObject_Del + PyTypeObject waste_Type = { *************** *** 2136,2152 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ wasteObj_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ wasteObj_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 2182,2206 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ wasteObj_methods, /* tp_methods */ ! 0, /*tp_members*/ wasteObj_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! wasteObj_tp_init, /* tp_init */ ! wasteObj_tp_alloc, /* tp_alloc */ ! wasteObj_tp_new, /* tp_new */ ! wasteObj_tp_free, /* tp_free */ }; *************** *** 2507,2516 **** WEO_Type.ob_type = &PyType_Type; Py_INCREF(&WEO_Type); ! if (PyDict_SetItemString(d, "WEOType", (PyObject *)&WEO_Type) != 0) ! Py_FatalError("can't initialize WEOType"); waste_Type.ob_type = &PyType_Type; Py_INCREF(&waste_Type); ! if (PyDict_SetItemString(d, "wasteType", (PyObject *)&waste_Type) != 0) ! Py_FatalError("can't initialize wasteType"); callbackdict = PyDict_New(); --- 2561,2574 ---- WEO_Type.ob_type = &PyType_Type; Py_INCREF(&WEO_Type); ! PyModule_AddObject(m, "WEO", (PyObject *)&WEO_Type); ! /* Backward-compatible name */ ! Py_INCREF(&WEO_Type); ! PyModule_AddObject(m, "WEOType", (PyObject *)&WEO_Type); waste_Type.ob_type = &PyType_Type; Py_INCREF(&waste_Type); ! PyModule_AddObject(m, "waste", (PyObject *)&waste_Type); ! /* Backward-compatible name */ ! Py_INCREF(&waste_Type); ! PyModule_AddObject(m, "wasteType", (PyObject *)&waste_Type); callbackdict = PyDict_New(); Index: wastesupport.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/waste/wastesupport.py,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** wastesupport.py 29 Nov 2002 23:40:47 -0000 1.18 --- wastesupport.py 3 Dec 2002 23:40:22 -0000 1.19 *************** *** 278,282 **** ! class WEObjectDefinition(PEP252Mixin, GlobalObjectDefinition): def outputCheckNewArg(self): Output("""if (itself == NULL) { --- 278,282 ---- ! class WEObjectDefinition(PEP253Mixin, GlobalObjectDefinition): def outputCheckNewArg(self): Output("""if (itself == NULL) { *************** *** 290,294 **** Output("WEDispose(%s);", itselfname) ! class WEOObjectDefinition(PEP252Mixin, GlobalObjectDefinition): def outputCheckNewArg(self): Output("""if (itself == NULL) { --- 290,294 ---- Output("WEDispose(%s);", itselfname) ! class WEOObjectDefinition(PEP253Mixin, GlobalObjectDefinition): def outputCheckNewArg(self): Output("""if (itself == NULL) { From jackjansen@users.sourceforge.net Tue Dec 3 23:40:24 2002 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 03 Dec 2002 15:40:24 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules/te _TEmodule.c,1.11,1.12 tesupport.py,1.11,1.12 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules/te In directory sc8-pr-cvs1:/tmp/cvs-serv10318/te Modified Files: _TEmodule.c tesupport.py Log Message: Added PEP253 support to most Carbon modules. This isn't complete yet: some of the more compilcated cases (CF, Res) haven't been done yet. Also, various types should inherit from each other (anything with an as_Resource method should be a Resource subtype, the CF types should become one family). Index: _TEmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/te/_TEmodule.c,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** _TEmodule.c 29 Nov 2002 23:40:47 -0000 1.11 --- _TEmodule.c 3 Dec 2002 23:40:22 -0000 1.12 *************** *** 980,983 **** --- 980,984 ---- {"txSize", (getter)TEObj_get_txSize, (setter)TEObj_set_txSize, "Current font size"}, {"nLines", (getter)TEObj_get_nLines, (setter)TEObj_set_nLines, "TBD"}, + {NULL, NULL, NULL, NULL}, }; *************** *** 988,991 **** --- 989,1010 ---- #define TEObj_hash NULL + #define TEObj_tp_init 0 + + #define TEObj_tp_alloc PyType_GenericAlloc + + static PyObject *TEObj_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + TEHandle itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, TEObj_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((TEObject *)self)->ob_itself = itself; + return self; + } + + #define TEObj_tp_free PyObject_Del + PyTypeObject TE_Type = { *************** *** 1010,1026 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ TEObj_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ TEObj_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 1029,1053 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ TEObj_methods, /* tp_methods */ ! 0, /*tp_members*/ TEObj_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! TEObj_tp_init, /* tp_init */ ! TEObj_tp_alloc, /* tp_alloc */ ! TEObj_tp_new, /* tp_new */ ! TEObj_tp_free, /* tp_free */ }; *************** *** 1314,1319 **** TE_Type.ob_type = &PyType_Type; Py_INCREF(&TE_Type); ! if (PyDict_SetItemString(d, "TEType", (PyObject *)&TE_Type) != 0) ! Py_FatalError("can't initialize TEType"); } --- 1341,1348 ---- TE_Type.ob_type = &PyType_Type; Py_INCREF(&TE_Type); ! PyModule_AddObject(m, "TE", (PyObject *)&TE_Type); ! /* Backward-compatible name */ ! Py_INCREF(&TE_Type); ! PyModule_AddObject(m, "TEType", (PyObject *)&TE_Type); } Index: tesupport.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/te/tesupport.py,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** tesupport.py 29 Nov 2002 23:40:47 -0000 1.11 --- tesupport.py 3 Dec 2002 23:40:22 -0000 1.12 *************** *** 94,98 **** ! class MyObjectDefinition(PEP252Mixin, GlobalObjectDefinition): # Attributes that can be set. getsetlist = [ --- 94,99 ---- ! class MyObjectDefinition(PEP253Mixin, GlobalObjectDefinition): ! # XXXX Could be subtype of Resource # Attributes that can be set. getsetlist = [ From jackjansen@users.sourceforge.net Tue Dec 3 23:40:23 2002 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 03 Dec 2002 15:40:23 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules/qdoffs _Qdoffsmodule.c,1.10,1.11 qdoffssupport.py,1.9,1.10 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules/qdoffs In directory sc8-pr-cvs1:/tmp/cvs-serv10318/qdoffs Modified Files: _Qdoffsmodule.c qdoffssupport.py Log Message: Added PEP253 support to most Carbon modules. This isn't complete yet: some of the more compilcated cases (CF, Res) haven't been done yet. Also, various types should inherit from each other (anything with an as_Resource method should be a Resource subtype, the CF types should become one family). Index: _Qdoffsmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/qdoffs/_Qdoffsmodule.c,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** _Qdoffsmodule.c 29 Nov 2002 23:40:46 -0000 1.10 --- _Qdoffsmodule.c 3 Dec 2002 23:40:21 -0000 1.11 *************** *** 134,137 **** --- 134,138 ---- #define GWorldObj_getsetlist NULL + #define GWorldObj_compare NULL *************** *** 139,142 **** --- 140,161 ---- #define GWorldObj_hash NULL + #define GWorldObj_tp_init 0 + + #define GWorldObj_tp_alloc PyType_GenericAlloc + + static PyObject *GWorldObj_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + GWorldPtr itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, GWorldObj_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((GWorldObject *)self)->ob_itself = itself; + return self; + } + + #define GWorldObj_tp_free PyObject_Del + PyTypeObject GWorld_Type = { *************** *** 161,177 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ GWorldObj_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ GWorldObj_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 180,204 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ GWorldObj_methods, /* tp_methods */ ! 0, /*tp_members*/ GWorldObj_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! GWorldObj_tp_init, /* tp_init */ ! GWorldObj_tp_alloc, /* tp_alloc */ ! GWorldObj_tp_new, /* tp_new */ ! GWorldObj_tp_free, /* tp_free */ }; *************** *** 685,690 **** GWorld_Type.ob_type = &PyType_Type; Py_INCREF(&GWorld_Type); ! if (PyDict_SetItemString(d, "GWorldType", (PyObject *)&GWorld_Type) != 0) ! Py_FatalError("can't initialize GWorldType"); } --- 712,719 ---- GWorld_Type.ob_type = &PyType_Type; Py_INCREF(&GWorld_Type); ! PyModule_AddObject(m, "GWorld", (PyObject *)&GWorld_Type); ! /* Backward-compatible name */ ! Py_INCREF(&GWorld_Type); ! PyModule_AddObject(m, "GWorldType", (PyObject *)&GWorld_Type); } Index: qdoffssupport.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/qdoffs/qdoffssupport.py,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** qdoffssupport.py 29 Nov 2002 23:40:46 -0000 1.9 --- qdoffssupport.py 3 Dec 2002 23:40:21 -0000 1.10 *************** *** 58,62 **** """ ! class MyObjectDefinition(PEP252Mixin, GlobalObjectDefinition): def outputCheckNewArg(self): Output("if (itself == NULL) return PyMac_Error(resNotFound);") --- 58,63 ---- """ ! class MyObjectDefinition(PEP253Mixin, GlobalObjectDefinition): ! # XXXX Should inherit from GrafPtr? def outputCheckNewArg(self): Output("if (itself == NULL) return PyMac_Error(resNotFound);") From jackjansen@users.sourceforge.net Tue Dec 3 23:40:23 2002 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Tue, 03 Dec 2002 15:40:23 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules/qt _Qtmodule.c,1.10,1.11 qtsupport.py,1.20,1.21 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules/qt In directory sc8-pr-cvs1:/tmp/cvs-serv10318/qt Modified Files: _Qtmodule.c qtsupport.py Log Message: Added PEP253 support to most Carbon modules. This isn't complete yet: some of the more compilcated cases (CF, Res) haven't been done yet. Also, various types should inherit from each other (anything with an as_Resource method should be a Resource subtype, the CF types should become one family). Index: _Qtmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/qt/_Qtmodule.c,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** _Qtmodule.c 29 Nov 2002 23:40:46 -0000 1.10 --- _Qtmodule.c 3 Dec 2002 23:40:21 -0000 1.11 *************** *** 1093,1096 **** --- 1093,1097 ---- #define MovieCtlObj_getsetlist NULL + #define MovieCtlObj_compare NULL *************** *** 1098,1101 **** --- 1099,1120 ---- #define MovieCtlObj_hash NULL + #define MovieCtlObj_tp_init 0 + + #define MovieCtlObj_tp_alloc PyType_GenericAlloc + + static PyObject *MovieCtlObj_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + MovieController itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, MovieCtlObj_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((MovieControllerObject *)self)->ob_itself = itself; + return self; + } + + #define MovieCtlObj_tp_free PyObject_Del + PyTypeObject MovieController_Type = { *************** *** 1120,1136 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ MovieCtlObj_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ MovieCtlObj_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 1139,1163 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ MovieCtlObj_methods, /* tp_methods */ ! 0, /*tp_members*/ MovieCtlObj_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! MovieCtlObj_tp_init, /* tp_init */ ! MovieCtlObj_tp_alloc, /* tp_alloc */ ! MovieCtlObj_tp_new, /* tp_new */ ! MovieCtlObj_tp_free, /* tp_free */ }; *************** *** 1554,1557 **** --- 1581,1585 ---- #define TimeBaseObj_getsetlist NULL + #define TimeBaseObj_compare NULL *************** *** 1559,1562 **** --- 1587,1608 ---- #define TimeBaseObj_hash NULL + #define TimeBaseObj_tp_init 0 + + #define TimeBaseObj_tp_alloc PyType_GenericAlloc + + static PyObject *TimeBaseObj_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + TimeBase itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, TimeBaseObj_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((TimeBaseObject *)self)->ob_itself = itself; + return self; + } + + #define TimeBaseObj_tp_free PyObject_Del + PyTypeObject TimeBase_Type = { *************** *** 1581,1597 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ TimeBaseObj_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ TimeBaseObj_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 1627,1651 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ TimeBaseObj_methods, /* tp_methods */ ! 0, /*tp_members*/ TimeBaseObj_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! TimeBaseObj_tp_init, /* tp_init */ ! TimeBaseObj_tp_alloc, /* tp_alloc */ ! TimeBaseObj_tp_new, /* tp_new */ ! TimeBaseObj_tp_free, /* tp_free */ }; *************** *** 1868,1871 **** --- 1922,1926 ---- #define UserDataObj_getsetlist NULL + #define UserDataObj_compare NULL *************** *** 1873,1876 **** --- 1928,1949 ---- #define UserDataObj_hash NULL + #define UserDataObj_tp_init 0 + + #define UserDataObj_tp_alloc PyType_GenericAlloc + + static PyObject *UserDataObj_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + UserData itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, UserDataObj_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((UserDataObject *)self)->ob_itself = itself; + return self; + } + + #define UserDataObj_tp_free PyObject_Del + PyTypeObject UserData_Type = { *************** *** 1895,1911 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ UserDataObj_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ UserDataObj_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 1968,1992 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ UserDataObj_methods, /* tp_methods */ ! 0, /*tp_members*/ UserDataObj_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! UserDataObj_tp_init, /* tp_init */ ! UserDataObj_tp_alloc, /* tp_alloc */ ! UserDataObj_tp_new, /* tp_new */ ! UserDataObj_tp_free, /* tp_free */ }; *************** *** 3053,3056 **** --- 3134,3138 ---- #define MediaObj_getsetlist NULL + #define MediaObj_compare NULL *************** *** 3058,3061 **** --- 3140,3161 ---- #define MediaObj_hash NULL + #define MediaObj_tp_init 0 + + #define MediaObj_tp_alloc PyType_GenericAlloc + + static PyObject *MediaObj_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + Media itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, MediaObj_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((MediaObject *)self)->ob_itself = itself; + return self; + } + + #define MediaObj_tp_free PyObject_Del + PyTypeObject Media_Type = { *************** *** 3080,3096 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ MediaObj_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ MediaObj_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 3180,3204 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ MediaObj_methods, /* tp_methods */ ! 0, /*tp_members*/ MediaObj_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! MediaObj_tp_init, /* tp_init */ ! MediaObj_tp_alloc, /* tp_alloc */ ! MediaObj_tp_new, /* tp_new */ ! MediaObj_tp_free, /* tp_free */ }; *************** *** 4344,4347 **** --- 4452,4456 ---- #define TrackObj_getsetlist NULL + #define TrackObj_compare NULL *************** *** 4349,4352 **** --- 4458,4479 ---- #define TrackObj_hash NULL + #define TrackObj_tp_init 0 + + #define TrackObj_tp_alloc PyType_GenericAlloc + + static PyObject *TrackObj_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + Track itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, TrackObj_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((TrackObject *)self)->ob_itself = itself; + return self; + } + + #define TrackObj_tp_free PyObject_Del + PyTypeObject Track_Type = { *************** *** 4371,4387 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ TrackObj_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ TrackObj_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 4498,4522 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ TrackObj_methods, /* tp_methods */ ! 0, /*tp_members*/ TrackObj_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! TrackObj_tp_init, /* tp_init */ ! TrackObj_tp_alloc, /* tp_alloc */ ! TrackObj_tp_new, /* tp_new */ ! TrackObj_tp_free, /* tp_free */ }; *************** *** 6775,6778 **** --- 6910,6914 ---- #define MovieObj_getsetlist NULL + #define MovieObj_compare NULL *************** *** 6780,6783 **** --- 6916,6937 ---- #define MovieObj_hash NULL + #define MovieObj_tp_init 0 + + #define MovieObj_tp_alloc PyType_GenericAlloc + + static PyObject *MovieObj_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + Movie itself; + char *kw[] = {"itself", 0}; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, MovieObj_Convert, &itself)) return NULL; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((MovieObject *)self)->ob_itself = itself; + return self; + } + + #define MovieObj_tp_free PyObject_Del + PyTypeObject Movie_Type = { *************** *** 6802,6818 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ MovieObj_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ MovieObj_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 6956,6980 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ MovieObj_methods, /* tp_methods */ ! 0, /*tp_members*/ MovieObj_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! MovieObj_tp_init, /* tp_init */ ! MovieObj_tp_alloc, /* tp_alloc */ ! MovieObj_tp_new, /* tp_new */ ! MovieObj_tp_free, /* tp_free */ }; *************** *** 9967,9992 **** MovieController_Type.ob_type = &PyType_Type; Py_INCREF(&MovieController_Type); ! if (PyDict_SetItemString(d, "MovieControllerType", (PyObject *)&MovieController_Type) != 0) ! Py_FatalError("can't initialize MovieControllerType"); TimeBase_Type.ob_type = &PyType_Type; Py_INCREF(&TimeBase_Type); ! if (PyDict_SetItemString(d, "TimeBaseType", (PyObject *)&TimeBase_Type) != 0) ! Py_FatalError("can't initialize TimeBaseType"); UserData_Type.ob_type = &PyType_Type; Py_INCREF(&UserData_Type); ! if (PyDict_SetItemString(d, "UserDataType", (PyObject *)&UserData_Type) != 0) ! Py_FatalError("can't initialize UserDataType"); Media_Type.ob_type = &PyType_Type; Py_INCREF(&Media_Type); ! if (PyDict_SetItemString(d, "MediaType", (PyObject *)&Media_Type) != 0) ! Py_FatalError("can't initialize MediaType"); Track_Type.ob_type = &PyType_Type; Py_INCREF(&Track_Type); ! if (PyDict_SetItemString(d, "TrackType", (PyObject *)&Track_Type) != 0) ! Py_FatalError("can't initialize TrackType"); Movie_Type.ob_type = &PyType_Type; Py_INCREF(&Movie_Type); ! if (PyDict_SetItemString(d, "MovieType", (PyObject *)&Movie_Type) != 0) ! Py_FatalError("can't initialize MovieType"); } --- 10129,10166 ---- MovieController_Type.ob_type = &PyType_Type; Py_INCREF(&MovieController_Type); ! PyModule_AddObject(m, "MovieController", (PyObject *)&MovieController_Type); ! /* Backward-compatible name */ ! Py_INCREF(&MovieController_Type); ! PyModule_AddObject(m, "MovieControllerType", (PyObject *)&MovieController_Type); TimeBase_Type.ob_type = &PyType_Type; Py_INCREF(&TimeBase_Type); ! PyModule_AddObject(m, "TimeBase", (PyObject *)&TimeBase_Type); ! /* Backward-compatible name */ ! Py_INCREF(&TimeBase_Type); ! PyModule_AddObject(m, "TimeBaseType", (PyObject *)&TimeBase_Type); UserData_Type.ob_type = &PyType_Type; Py_INCREF(&UserData_Type); ! PyModule_AddObject(m, "UserData", (PyObject *)&UserData_Type); ! /* Backward-compatible name */ ! Py_INCREF(&UserData_Type); ! PyModule_AddObject(m, "UserDataType", (PyObject *)&UserData_Type); Media_Type.ob_type = &PyType_Type; Py_INCREF(&Media_Type); ! PyModule_AddObject(m, "Media", (PyObject *)&Media_Type); ! /* Backward-compatible name */ ! Py_INCREF(&Media_Type); ! PyModule_AddObject(m, "MediaType", (PyObject *)&Media_Type); Track_Type.ob_type = &PyType_Type; Py_INCREF(&Track_Type); ! PyModule_AddObject(m, "Track", (PyObject *)&Track_Type); ! /* Backward-compatible name */ ! Py_INCREF(&Track_Type); ! PyModule_AddObject(m, "TrackType", (PyObject *)&Track_Type); Movie_Type.ob_type = &PyType_Type; Py_INCREF(&Movie_Type); ! PyModule_AddObject(m, "Movie", (PyObject *)&Movie_Type); ! /* Backward-compatible name */ ! Py_INCREF(&Movie_Type); ! PyModule_AddObject(m, "MovieType", (PyObject *)&Movie_Type); } Index: qtsupport.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/qt/qtsupport.py,v retrieving revision 1.20 retrieving revision 1.21 diff -C2 -d -r1.20 -r1.21 *** qtsupport.py 29 Nov 2002 23:40:47 -0000 1.20 --- qtsupport.py 3 Dec 2002 23:40:21 -0000 1.21 *************** *** 182,186 **** dummyStringPtr = FakeType('(StringPtr)0') ! class MovieObjectDefinition(PEP252Mixin, GlobalObjectDefinition): def outputCheckNewArg(self): Output("""if (itself == NULL) { --- 182,186 ---- dummyStringPtr = FakeType('(StringPtr)0') ! class MovieObjectDefinition(PEP253Mixin, GlobalObjectDefinition): def outputCheckNewArg(self): Output("""if (itself == NULL) { *************** *** 191,195 **** Output("DisposeMovie(%s);", itselfname) ! class TrackObjectDefinition(PEP252Mixin, GlobalObjectDefinition): def outputCheckNewArg(self): Output("""if (itself == NULL) { --- 191,195 ---- Output("DisposeMovie(%s);", itselfname) ! class TrackObjectDefinition(PEP253Mixin, GlobalObjectDefinition): def outputCheckNewArg(self): Output("""if (itself == NULL) { *************** *** 200,204 **** Output("DisposeMovieTrack(%s);", itselfname) ! class MediaObjectDefinition(PEP252Mixin, GlobalObjectDefinition): def outputCheckNewArg(self): Output("""if (itself == NULL) { --- 200,204 ---- Output("DisposeMovieTrack(%s);", itselfname) ! class MediaObjectDefinition(PEP253Mixin, GlobalObjectDefinition): def outputCheckNewArg(self): Output("""if (itself == NULL) { *************** *** 209,213 **** Output("DisposeTrackMedia(%s);", itselfname) ! class UserDataObjectDefinition(PEP252Mixin, GlobalObjectDefinition): def outputCheckNewArg(self): Output("""if (itself == NULL) { --- 209,213 ---- Output("DisposeTrackMedia(%s);", itselfname) ! class UserDataObjectDefinition(PEP253Mixin, GlobalObjectDefinition): def outputCheckNewArg(self): Output("""if (itself == NULL) { *************** *** 218,222 **** Output("DisposeUserData(%s);", itselfname) ! class TimeBaseObjectDefinition(PEP252Mixin, GlobalObjectDefinition): def outputCheckNewArg(self): Output("""if (itself == NULL) { --- 218,222 ---- Output("DisposeUserData(%s);", itselfname) ! class TimeBaseObjectDefinition(PEP253Mixin, GlobalObjectDefinition): def outputCheckNewArg(self): Output("""if (itself == NULL) { *************** *** 227,231 **** ## Output("DisposeTimeBase(%s);", itselfname) ! class MovieCtlObjectDefinition(PEP252Mixin, GlobalObjectDefinition): def outputCheckNewArg(self): Output("""if (itself == NULL) { --- 227,231 ---- ## Output("DisposeTimeBase(%s);", itselfname) ! class MovieCtlObjectDefinition(PEP253Mixin, GlobalObjectDefinition): def outputCheckNewArg(self): Output("""if (itself == NULL) { From tim_one@users.sourceforge.net Wed Dec 4 02:39:55 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 03 Dec 2002 18:39:55 -0800 Subject: [Python-checkins] python/dist/src/PCbuild readme.txt,1.32,1.33 Message-ID: Update of /cvsroot/python/python/dist/src/PCbuild In directory sc8-pr-cvs1:/tmp/cvs-serv20264/python/PCbuild Modified Files: readme.txt Log Message: Clarify _ssl instructions. Index: readme.txt =================================================================== RCS file: /cvsroot/python/python/dist/src/PCbuild/readme.txt,v retrieving revision 1.32 retrieving revision 1.33 diff -C2 -d -r1.32 -r1.33 *** readme.txt 3 Dec 2002 05:47:26 -0000 1.32 --- readme.txt 4 Dec 2002 02:39:52 -0000 1.33 *************** *** 200,209 **** XXX This isn't encouraging, but I don't know what to do about it. _ssl ! Python wrapper for the secure sockets library. Get the latest source code for OpenSSL from http://www.openssl.org Unpack into the "dist" directory, retaining the folder name from the archive - for example, the latest stable OpenSSL will install as --- 200,215 ---- XXX This isn't encouraging, but I don't know what to do about it. + _ssl ! Python wrapper for the secure sockets library. Get the latest source code for OpenSSL from http://www.openssl.org + You (probably) don't want the "engine" code. For example, get + openssl-0.9.6g.tar.gz + not + openssl-engine-0.9.6g.tar.gz + Unpack into the "dist" directory, retaining the folder name from the archive - for example, the latest stable OpenSSL will install as *************** *** 215,222 **** You must also install ActivePerl from http://www.activestate.com/Products/ActivePerl/ ! as this is used by the OpenSSL build process. Complain to them The MSVC project simply invokes PCBuild/build_ssl.py to perform ! the build. This Python script locates and builds your OpenSSL installation, then invokes a simple makefile to build the final .pyd. --- 221,228 ---- You must also install ActivePerl from http://www.activestate.com/Products/ActivePerl/ ! as this is used by the OpenSSL build process. Complain to them . The MSVC project simply invokes PCBuild/build_ssl.py to perform ! the build. This Python script locates and builds your OpenSSL installation, then invokes a simple makefile to build the final .pyd. *************** *** 229,234 **** should be able to be run directly from the command-line. ! build_ssl.py/MSVC isn't clever enough to clean OpenSSL - you must do this ! by hand. YOUR OWN EXTENSION DLLs --- 235,240 ---- should be able to be run directly from the command-line. ! build_ssl.py/MSVC isn't clever enough to clean OpenSSL - you must do ! this by hand. YOUR OWN EXTENSION DLLs From tim_one@users.sourceforge.net Wed Dec 4 03:16:40 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 03 Dec 2002 19:16:40 -0800 Subject: [Python-checkins] python/dist/src/PCbuild readme.txt,1.33,1.34 Message-ID: Update of /cvsroot/python/python/dist/src/PCbuild In directory sc8-pr-cvs1:/tmp/cvs-serv30786 Modified Files: readme.txt Log Message: Explain what's probably a problem unique to Win9x in building _ssl. Index: readme.txt =================================================================== RCS file: /cvsroot/python/python/dist/src/PCbuild/readme.txt,v retrieving revision 1.33 retrieving revision 1.34 diff -C2 -d -r1.33 -r1.34 *** readme.txt 4 Dec 2002 02:39:52 -0000 1.33 --- readme.txt 4 Dec 2002 03:16:37 -0000 1.34 *************** *** 227,230 **** --- 227,232 ---- installation, then invokes a simple makefile to build the final .pyd. + Win9x users: see "Win9x note" below. + build_ssl.py attempts to catch the most common errors (such as not being able to find OpenSSL sources, or not being able to find a Perl *************** *** 237,240 **** --- 239,267 ---- build_ssl.py/MSVC isn't clever enough to clean OpenSSL - you must do this by hand. + + Win9x note: If, near the start of the build process, you see + something like + + C:\Code\openssl-0.9.6g>set OPTS=no-asm + Out of environment space + + then you're in trouble, and will probable also see these errors near + the end of the process: + + NMAKE : fatal error U1073: don't know how to make + 'crypto\md5\asm\m5_win32.asm' + Stop. + NMAKE : fatal error U1073: don't know how to make + 'C:\Code\openssl-0.9.6g/out32/libeay32.lib' + Stop. + + You need more environment space. Win9x only has room for 256 bytes + by default, and especially after installing ActivePerl (which fiddles + the PATH envar), you're likely to run out. KB Q230205 + + http://support.microsoft.com/default.aspx?scid=KB;en-us;q230205 + + explains how to edit CONFIG.SYS to cure this. + YOUR OWN EXTENSION DLLs From tim_one@users.sourceforge.net Wed Dec 4 03:26:59 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 03 Dec 2002 19:26:59 -0800 Subject: [Python-checkins] python/dist/src/Lib/test regrtest.py,1.109,1.110 test_socket_ssl.py,1.5,1.6 test_support.py,1.46,1.47 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv1712/python/Lib/test Modified Files: regrtest.py test_socket_ssl.py test_support.py Log Message: Rearrange test_socket_ssl so that a skip is expected iff the network resource isn't enabled or the socket module doesn't support ssl. Index: regrtest.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/regrtest.py,v retrieving revision 1.109 retrieving revision 1.110 diff -C2 -d -r1.109 -r1.110 *** regrtest.py 3 Dec 2002 10:24:56 -0000 1.109 --- regrtest.py 4 Dec 2002 03:26:57 -0000 1.110 *************** *** 535,538 **** --- 535,541 ---- # input file has been downloaded. test_normalization.skip_expected # controls that. + # test_socket_ssl + # Controlled by test_socket_ssl.skip_expected. Requires the network + # resource, and a socket module with ssl support. _expectations = { *************** *** 566,570 **** test_resource test_signal - test_socket_ssl test_socketserver test_sunaudiodev --- 569,572 ---- *************** *** 584,588 **** test_nis test_ntpath - test_socket_ssl test_socketserver test_sunaudiodev --- 586,589 ---- *************** *** 619,623 **** test_pwd test_signal - test_socket_ssl test_socketserver test_sunaudiodev --- 620,623 ---- *************** *** 737,741 **** test_pty test_pwd - test_socket_ssl test_socketserver test_strop --- 737,740 ---- *************** *** 770,774 **** test_ntpath test_poll - test_socket_ssl test_socketserver test_sunaudiodev --- 769,772 ---- *************** *** 793,797 **** test_mpz test_openpty - test_socket_ssl test_socketserver test_winreg --- 791,794 ---- *************** *** 821,825 **** test_pyexpat test_sax - test_socket_ssl test_socketserver test_sunaudiodev --- 818,821 ---- *************** *** 851,855 **** test_popen2 test_resource - test_socket_ssl test_socketserver test_sunaudiodev --- 847,850 ---- *************** *** 864,867 **** --- 859,863 ---- import os.path from test import test_normalization + from test import test_socket_ssl self.valid = False *************** *** 875,878 **** --- 871,877 ---- if test_normalization.skip_expected: self.expected.add('test_normalization') + + if test_socket_ssl.skip_expected: + self.expected.add('test_socket_ssl') self.valid = True Index: test_socket_ssl.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_socket_ssl.py,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** test_socket_ssl.py 23 Jul 2002 19:04:02 -0000 1.5 --- test_socket_ssl.py 4 Dec 2002 03:26:57 -0000 1.6 *************** *** 2,27 **** from test import test_support ! # Optionally test SSL support. This currently requires the 'network' resource ! # as given on the regrtest command line. If not available, nothing after this ! # line will be executed. ! test_support.requires('network') ! import socket ! if not hasattr(socket, "ssl"): ! raise test_support.TestSkipped("socket module has no ssl support") ! import urllib ! socket.RAND_status() ! try: ! socket.RAND_egd(1) ! except TypeError: ! pass ! else: ! print "didn't raise TypeError" ! socket.RAND_add("this is a random string", 75.0) ! f = urllib.urlopen('https://sf.net') ! buf = f.read() ! f.close() --- 2,32 ---- from test import test_support + import socket ! # Optionally test SSL support. This requires the 'network' resource as given ! # on the regrtest command line. ! skip_expected = not (test_support.is_resource_enabled('network') and ! hasattr(socket, "ssl")) ! def test_main(): ! test_support.requires('network') ! if not hasattr(socket, "ssl"): ! raise test_support.TestSkipped("socket module has no ssl support") ! import urllib ! socket.RAND_status() ! try: ! socket.RAND_egd(1) ! except TypeError: ! pass ! else: ! print "didn't raise TypeError" ! socket.RAND_add("this is a random string", 75.0) ! f = urllib.urlopen('https://sf.net') ! buf = f.read() ! f.close() ! ! if __name__ == "__main__": ! test_main() Index: test_support.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_support.py,v retrieving revision 1.46 retrieving revision 1.47 diff -C2 -d -r1.46 -r1.47 *** test_support.py 9 Nov 2002 19:57:26 -0000 1.46 --- test_support.py 4 Dec 2002 03:26:57 -0000 1.47 *************** *** 51,56 **** pass def requires(resource, msg=None): ! if use_resources is not None and resource not in use_resources: if msg is None: msg = "Use of the `%s' resource not enabled" % resource --- 51,59 ---- pass + def is_resource_enabled(resource): + return use_resources is not None and resource in use_resources + def requires(resource, msg=None): ! if not is_resource_enabled(resource): if msg is None: msg = "Use of the `%s' resource not enabled" % resource From tim_one@users.sourceforge.net Wed Dec 4 04:00:18 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 03 Dec 2002 20:00:18 -0800 Subject: [Python-checkins] python/dist/src/PCbuild python20.wse,1.109,1.110 readme.txt,1.34,1.35 Message-ID: Update of /cvsroot/python/python/dist/src/PCbuild In directory sc8-pr-cvs1:/tmp/cvs-serv24330/python/PCbuild Modified Files: python20.wse readme.txt Log Message: Added _ssl.lib to the installer too. Restored alphabetical order of DLL and lib sections. Index: python20.wse =================================================================== RCS file: /cvsroot/python/python/dist/src/PCbuild/python20.wse,v retrieving revision 1.109 retrieving revision 1.110 diff -C2 -d -r1.109 -r1.110 *** python20.wse 3 Dec 2002 06:02:59 -0000 1.109 --- python20.wse 4 Dec 2002 04:00:09 -0000 1.110 *************** *** 1701,1711 **** end item: Install File ! Source=.\_ssl.pyd ! Destination=%MAINDIR%\DLLs\_ssl.pyd Flags=0000000000000010 end item: Install File ! Source=.\_sre.pyd ! Destination=%MAINDIR%\DLLs\_sre.pyd Flags=0000000000000010 end --- 1701,1711 ---- end item: Install File ! Source=.\_sre.pyd ! Destination=%MAINDIR%\DLLs\_sre.pyd Flags=0000000000000010 end item: Install File ! Source=.\_ssl.pyd ! Destination=%MAINDIR%\DLLs\_ssl.pyd Flags=0000000000000010 end *************** *** 1789,1792 **** --- 1789,1797 ---- Source=.\_sre.lib Destination=%MAINDIR%\libs\_sre.lib + Flags=0000000000000010 + end + item: Install File + Source=.\_ssl.lib + Destination=%MAINDIR%\libs\_ssl.lib Flags=0000000000000010 end Index: readme.txt =================================================================== RCS file: /cvsroot/python/python/dist/src/PCbuild/readme.txt,v retrieving revision 1.34 retrieving revision 1.35 diff -C2 -d -r1.34 -r1.35 *** readme.txt 4 Dec 2002 03:16:37 -0000 1.34 --- readme.txt 4 Dec 2002 04:00:12 -0000 1.35 *************** *** 246,250 **** Out of environment space ! then you're in trouble, and will probable also see these errors near the end of the process: --- 246,250 ---- Out of environment space ! then you're in trouble, and will probably also see these errors near the end of the process: From tim_one@users.sourceforge.net Wed Dec 4 04:12:03 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 03 Dec 2002 20:12:03 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime doc.txt,1.1,1.2 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv777 Modified Files: doc.txt Log Message: Repaired errors. Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** doc.txt 3 Dec 2002 22:54:22 -0000 1.1 --- doc.txt 4 Dec 2002 04:12:01 -0000 1.2 *************** *** 20,24 **** Like datetime, but also supports a customizable notion of time adjustment (for timezones, or daylight savings time, or any other ! computable adjustment) class timetz --- 20,24 ---- Like datetime, but also supports a customizable notion of time adjustment (for timezones, or daylight savings time, or any other ! computable adjustment). class timetz *************** *** 103,107 **** - unary plus, minus, abs ! These are exact, but unary minus and abs may overflow. - comparison of timedelta to timedelta --- 103,107 ---- - unary plus, minus, abs ! These are exact, but unary minus may overflow. - comparison of timedelta to timedelta From tim_one@users.sourceforge.net Wed Dec 4 05:08:17 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 03 Dec 2002 21:08:17 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.c,1.39,1.40 obj_date.c,1.19,1.20 obj_datetime.c,1.14,1.15 obj_delta.c,1.20,1.21 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv2441 Modified Files: datetime.c obj_date.c obj_datetime.c obj_delta.c Log Message: Reworked the overflow checking for timedeltas, and, for speed, added a bool "normalize?" argument to new_delta(). The scheme this replaces didn't make sense anymore, not since the timedelta constructor was beefed up to be as capable as the Python timedelta constructor. Index: datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.c,v retrieving revision 1.39 retrieving revision 1.40 diff -C2 -d -r1.39 -r1.40 *** datetime.c 3 Dec 2002 21:42:00 -0000 1.39 --- datetime.c 4 Dec 2002 05:08:14 -0000 1.40 *************** *** 14,22 **** #define MAXYEAR 9999 typedef struct { PyObject_HEAD ! long hashcode; ! long days; /* in -TOOBIG_INPUT .. TOOBIG_INPUT */ long seconds; /* 0 <= seconds < 24*3600 is invariant */ long microseconds; /* 0 <= microseconds < 1000000 is invariant */ --- 14,29 ---- #define MAXYEAR 9999 + /* Nine decimal digits is easy to communicate, and leaves enough room + * so that two delta days can be added w/o fear of overflowing a signed + * 32-bit int, and with plenty of room left over to absorb any possible + * carries from adding seconds. + */ + #define MAX_DELTA_DAYS 999999999 + typedef struct { PyObject_HEAD ! long hashcode; /* -1 when unknown */ ! long days; /* -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS */ long seconds; /* 0 <= seconds < 24*3600 is invariant */ long microseconds; /* 0 <= microseconds < 1000000 is invariant */ *************** *** 96,122 **** } ! /* All input fields (year, month, day, hour, minute, second, millisecond, ! * microsecond) are constrained to lie within -TOOBIG_INPUT .. TOOBIG_INPUT ! * exclusive of endpoints. You can't make this larger without studying the ! * code very carefully, as various "can't overflow" assurances follow ! * from the specific value used here. ! */ ! #define TOOBIG_INPUT 1000000000 /* a billion; 1e9 */ ! ! /* Check that x is in the range given above. If so, return 0. If not, ! * raise the given exception and return -1. */ static int ! check_range(long x, const char* tag, PyObject *exception) { char buf[200]; ! if (-TOOBIG_INPUT < x && x < TOOBIG_INPUT) return 0; /* PyErr_Format() ignores the "l" in "%ld", which isn't correct * on boxes where sizeof(long) > sizeof(int). So roll our own. */ ! PyOS_snprintf(buf, sizeof(buf), "%s=%ld; must have magnitude < %ld", ! tag, x, TOOBIG_INPUT); PyErr_SetString(exception, buf); return -1; --- 103,121 ---- } ! /* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS. If so, return 0. ! * If not, raise the given exception and return -1. */ static int ! check_delta_day_range(long days, PyObject *exception) { char buf[200]; ! if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS) return 0; /* PyErr_Format() ignores the "l" in "%ld", which isn't correct * on boxes where sizeof(long) > sizeof(int). So roll our own. */ ! PyOS_snprintf(buf, sizeof(buf), "days=%ld; must have magnitude <= %ld", ! days, MAX_DELTA_DAYS); PyErr_SetString(exception, buf); return -1; *************** *** 516,527 **** } static PyObject * ! new_delta(long days, long seconds, long microseconds) { PyDateTime_Delta *self; ! normalize_d_s_us(&days, &seconds, µseconds); ! if (check_range(days, "timedelta days", PyExc_OverflowError) < 0) return NULL; --- 515,535 ---- } + /* Create a timedelta instance. Normalize the members iff normalize is + * true. Passing false is a speed optimization, if you know for sure + * that seconds and microseconds are already in their proper ranges. In any + * case, raises OverflowError and returns NULL if the normalized days is out + * of range). + */ static PyObject * ! new_delta(long days, long seconds, long microseconds, int normalize) { PyDateTime_Delta *self; ! if (normalize) ! normalize_d_s_us(&days, &seconds, µseconds); ! assert(0 <= seconds && seconds < 24*3600); ! assert(0 <= microseconds && microseconds < 1000000); ! if (check_delta_day_range(days, PyExc_OverflowError) < 0) return NULL; *************** *** 606,620 **** return; ! dt = new_delta(0, 0, 1); if (dt == NULL || PyDict_SetItemString(d, "resolution", dt) < 0) return; Py_DECREF(dt); ! dt = new_delta(1-TOOBIG_INPUT, 0, 0); if (dt == NULL || PyDict_SetItemString(d, "min", dt) < 0) return; Py_DECREF(dt); ! dt = new_delta(TOOBIG_INPUT-1, 24*3600-1, 1000000-1); if (dt == NULL || PyDict_SetItemString(d, "max", dt) < 0) return; --- 614,628 ---- return; ! dt = new_delta(0, 0, 1, 0); if (dt == NULL || PyDict_SetItemString(d, "resolution", dt) < 0) return; Py_DECREF(dt); ! dt = new_delta(-MAX_DELTA_DAYS, 0, 0, 0); if (dt == NULL || PyDict_SetItemString(d, "min", dt) < 0) return; Py_DECREF(dt); ! dt = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0); if (dt == NULL || PyDict_SetItemString(d, "max", dt) < 0) return; *************** *** 634,638 **** Py_DECREF(dt); ! dt = new_delta(1, 0, 0); if (dt == NULL || PyDict_SetItemString(d, "resolution", dt) < 0) return; --- 642,646 ---- Py_DECREF(dt); ! dt = new_delta(1, 0, 0, 0); if (dt == NULL || PyDict_SetItemString(d, "resolution", dt) < 0) return; *************** *** 652,656 **** Py_DECREF(dt); ! dt = new_delta(0, 0, 1); if (dt == NULL || PyDict_SetItemString(d, "resolution", dt) < 0) return; --- 660,664 ---- Py_DECREF(dt); ! dt = new_delta(0, 0, 1, 0); if (dt == NULL || PyDict_SetItemString(d, "resolution", dt) < 0) return; Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.19 retrieving revision 1.20 diff -C2 -d -r1.19 -r1.20 *** obj_date.c 3 Dec 2002 19:32:27 -0000 1.19 --- obj_date.c 4 Dec 2002 05:08:14 -0000 1.20 *************** *** 305,309 **** GET_MONTH(right), GET_DAY(right)); ! return new_delta(left_ord - right_ord, 0, 0); } if (PyType_IsSubtype(right_type, &PyDateTime_DeltaType)) { --- 305,309 ---- GET_MONTH(right), GET_DAY(right)); ! return new_delta(left_ord - right_ord, 0, 0, 0); } if (PyType_IsSubtype(right_type, &PyDateTime_DeltaType)) { Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.14 retrieving revision 1.15 diff -C2 -d -r1.14 -r1.15 *** obj_datetime.c 3 Dec 2002 19:32:27 -0000 1.14 --- obj_datetime.c 4 Dec 2002 05:08:14 -0000 1.15 *************** *** 77,81 **** long delta_us = GET_MICROSECOND(left) - GET_MICROSECOND(right); ! return new_delta(days1 - days2, seconds1 - seconds2, delta_us); } --- 77,81 ---- long delta_us = GET_MICROSECOND(left) - GET_MICROSECOND(right); ! return new_delta(days1 - days2, seconds1 - seconds2, delta_us, 1); } Index: obj_delta.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_delta.c,v retrieving revision 1.20 retrieving revision 1.21 diff -C2 -d -r1.20 -r1.21 *** obj_delta.c 3 Dec 2002 20:43:44 -0000 1.20 --- obj_delta.c 4 Dec 2002 05:08:14 -0000 1.21 *************** *** 116,120 **** if (d == -1 && PyErr_Occurred()) goto Done; ! result = new_delta(d, s, us); Done: --- 116,120 ---- if (d == -1 && PyErr_Occurred()) goto Done; ! result = new_delta(d, s, us, 0); Done: *************** *** 181,185 **** long microseconds = GET_TD_MICROSECONDS(left) + GET_TD_MICROSECONDS(right); ! result = new_delta(days, seconds, microseconds); } --- 181,185 ---- long microseconds = GET_TD_MICROSECONDS(left) + GET_TD_MICROSECONDS(right); ! result = new_delta(days, seconds, microseconds, 1); } *************** *** 194,198 **** return new_delta(-GET_TD_DAYS(self), -GET_TD_SECONDS(self), ! -GET_TD_MICROSECONDS(self)); } --- 194,199 ---- return new_delta(-GET_TD_DAYS(self), -GET_TD_SECONDS(self), ! -GET_TD_MICROSECONDS(self), ! 1); } *************** *** 205,209 **** return new_delta(GET_TD_DAYS(self), GET_TD_SECONDS(self), ! GET_TD_MICROSECONDS(self)); } --- 206,211 ---- return new_delta(GET_TD_DAYS(self), GET_TD_SECONDS(self), ! GET_TD_MICROSECONDS(self), ! 0); } From rhettinger@users.sourceforge.net Wed Dec 4 07:32:28 2002 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Tue, 03 Dec 2002 23:32:28 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_types.py,1.41,1.42 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv25529/Lib/test Modified Files: test_types.py Log Message: Replace BadInternalCall with TypeError. Add a test case. Fix whitespace. Just van Rossum showed a weird, but clever way for pure python code to trigger the BadInternalCall. The C code had assumed that calling a class constructor would return an instance of that class; however, classes that abuse __new__ can invalidate that assumption. Index: test_types.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_types.py,v retrieving revision 1.41 retrieving revision 1.42 diff -C2 -d -r1.41 -r1.42 *** test_types.py 27 Nov 2002 07:29:33 -0000 1.41 --- test_types.py 4 Dec 2002 07:32:25 -0000 1.42 *************** *** 559,562 **** --- 559,569 ---- if type(dictlike().fromkeys('a')) is not dictlike: raise TestFailed, 'dictsubclass.fromkeys created wrong type' + from UserDict import UserDict + class mydict(dict): + def __new__(cls, *args, **kwargs): + return UserDict(*args, **kwargs) + try: mydict.fromkeys('a b c'.split()) + except TypeError: pass + else: raise TestFailed, 'dict.fromkeys() failed to detect non-dict class.' # dict.copy() d = {1:1, 2:2, 3:3} From rhettinger@users.sourceforge.net Wed Dec 4 07:32:28 2002 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Tue, 03 Dec 2002 23:32:28 -0800 Subject: [Python-checkins] python/dist/src/Objects dictobject.c,2.133,2.134 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv25529/Objects Modified Files: dictobject.c Log Message: Replace BadInternalCall with TypeError. Add a test case. Fix whitespace. Just van Rossum showed a weird, but clever way for pure python code to trigger the BadInternalCall. The C code had assumed that calling a class constructor would return an instance of that class; however, classes that abuse __new__ can invalidate that assumption. Index: dictobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/dictobject.c,v retrieving revision 2.133 retrieving revision 2.134 diff -C2 -d -r2.133 -r2.134 *** dictobject.c 27 Nov 2002 19:38:00 -0000 2.133 --- dictobject.c 4 Dec 2002 07:32:25 -0000 2.134 *************** *** 974,978 **** int status; ! if (!PyArg_ParseTuple(args, "OO|O:fromkeys", &cls, &seq, &value)) return NULL; --- 974,978 ---- int status; ! if (!PyArg_ParseTuple(args, "OO|O:fromkeys", &cls, &seq, &value)) return NULL; *************** *** 981,986 **** return NULL; if (!PyDict_Check(d)) { - PyErr_BadInternalCall(); Py_DECREF(d); return NULL; } --- 981,987 ---- return NULL; if (!PyDict_Check(d)) { Py_DECREF(d); + PyErr_SetString(PyExc_TypeError, + "class constructor must return a subclass of dict"); return NULL; } From aimacintyre@users.sourceforge.net Wed Dec 4 12:27:09 2002 From: aimacintyre@users.sourceforge.net (aimacintyre@users.sourceforge.net) Date: Wed, 04 Dec 2002 04:27:09 -0800 Subject: [Python-checkins] python/dist/src/Python thread_os2.h,2.14,2.15 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv20339 Modified Files: thread_os2.h Log Message: typo fix: declaration required for VACPP not EMX+gcc Index: thread_os2.h =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/thread_os2.h,v retrieving revision 2.14 retrieving revision 2.15 diff -C2 -d -r2.14 -r2.15 *** thread_os2.h 26 Feb 2002 11:41:34 -0000 2.14 --- thread_os2.h 4 Dec 2002 12:27:06 -0000 2.15 *************** *** 231,235 **** void PyThread_release_lock(PyThread_type_lock aLock) { ! #if defined(PYCC_GCC) type_os2_lock lock = (type_os2_lock)aLock; #endif --- 231,235 ---- void PyThread_release_lock(PyThread_type_lock aLock) { ! #if !defined(PYCC_GCC) type_os2_lock lock = (type_os2_lock)aLock; #endif From aimacintyre@users.sourceforge.net Wed Dec 4 12:29:40 2002 From: aimacintyre@users.sourceforge.net (aimacintyre@users.sourceforge.net) Date: Wed, 04 Dec 2002 04:29:40 -0800 Subject: [Python-checkins] python/dist/src/Python thread_os2.h,2.15,2.16 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv21877 Modified Files: thread_os2.h Log Message: reformat for PEP-7 style conformance Index: thread_os2.h =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/thread_os2.h,v retrieving revision 2.15 retrieving revision 2.16 diff -C2 -d -r2.15 -r2.16 *** thread_os2.h 4 Dec 2002 12:27:06 -0000 2.15 --- thread_os2.h 4 Dec 2002 12:29:37 -0000 2.16 *************** *** 29,44 **** PyThread_start_new_thread(void (*func)(void *), void *arg) { ! int aThread; ! int success = 0; ! aThread = _beginthread(func,NULL,65536,arg); ! if( aThread == -1 ) { ! success = -1; ! fprintf(stderr,"aThread failed == %d",aThread); ! dprintf(("_beginthread failed. return %ld\n", errno)); ! } ! return success; } --- 29,44 ---- PyThread_start_new_thread(void (*func)(void *), void *arg) { ! int aThread; ! int success = 0; ! aThread = _beginthread(func,NULL,65536,arg); ! if (aThread == -1) { ! success = -1; ! fprintf(stderr, "aThread failed == %d", aThread); ! dprintf(("_beginthread failed. return %ld\n", errno)); ! } ! return success; } *************** *** 47,62 **** { #if !defined(PYCC_GCC) ! PPIB pib; ! PTIB tib; #endif ! if (!initialized) ! PyThread_init_thread(); ! #if defined(PYCC_GCC) ! return _gettid(); #else ! DosGetInfoBlocks(&tib,&pib); ! return tib->tib_ptib2->tib2_ultid; #endif } --- 47,62 ---- { #if !defined(PYCC_GCC) ! PPIB pib; ! PTIB tib; #endif ! if (!initialized) ! PyThread_init_thread(); ! #if defined(PYCC_GCC) ! return _gettid(); #else ! DosGetInfoBlocks(&tib, &pib); ! return tib->tib_ptib2->tib2_ultid; #endif } *************** *** 65,75 **** do_PyThread_exit_thread(int no_cleanup) { ! dprintf(("%ld: PyThread_exit_thread called\n", PyThread_get_thread_ident())); ! if (!initialized) ! if (no_cleanup) ! _exit(0); ! else ! exit(0); ! _endthread(); } --- 65,76 ---- do_PyThread_exit_thread(int no_cleanup) { ! dprintf(("%ld: PyThread_exit_thread called\n", ! PyThread_get_thread_ident())); ! if (!initialized) ! if (no_cleanup) ! _exit(0); ! else ! exit(0); ! _endthread(); } *************** *** 77,81 **** PyThread_exit_thread(void) { ! do_PyThread_exit_thread(0); } --- 78,82 ---- PyThread_exit_thread(void) { ! do_PyThread_exit_thread(0); } *************** *** 83,87 **** PyThread__exit_thread(void) { ! do_PyThread_exit_thread(1); } --- 84,88 ---- PyThread__exit_thread(void) { ! do_PyThread_exit_thread(1); } *************** *** 90,99 **** do_PyThread_exit_prog(int status, int no_cleanup) { ! dprintf(("PyThread_exit_prog(%d) called\n", status)); ! if (!initialized) ! if (no_cleanup) ! _exit(status); ! else ! exit(status); } --- 91,100 ---- do_PyThread_exit_prog(int status, int no_cleanup) { ! dprintf(("PyThread_exit_prog(%d) called\n", status)); ! if (!initialized) ! if (no_cleanup) ! _exit(status); ! else ! exit(status); } *************** *** 101,105 **** PyThread_exit_prog(int status) { ! do_PyThread_exit_prog(status, 0); } --- 102,106 ---- PyThread_exit_prog(int status) { ! do_PyThread_exit_prog(status, 0); } *************** *** 107,111 **** PyThread__exit_prog(int status) { ! do_PyThread_exit_prog(status, 1); } #endif /* NO_EXIT_PROG */ --- 108,112 ---- PyThread__exit_prog(int status) { ! do_PyThread_exit_prog(status, 1); } #endif /* NO_EXIT_PROG */ *************** *** 118,123 **** typedef struct os2_lock_t { ! int is_set; ! HEV changed; } *type_os2_lock; --- 119,124 ---- typedef struct os2_lock_t { ! int is_set; ! HEV changed; } *type_os2_lock; *************** *** 126,157 **** { #if defined(PYCC_GCC) ! _fmutex *sem = malloc(sizeof(_fmutex)); ! if (!initialized) ! PyThread_init_thread(); ! dprintf(("%ld: PyThread_allocate_lock() -> %lx\n", ! PyThread_get_thread_ident(), ! (long)sem)); ! if (_fmutex_create(sem, 0)) { ! free(sem); ! sem = NULL; ! } ! return (PyThread_type_lock) sem; #else ! APIRET rc; ! type_os2_lock lock = (type_os2_lock)malloc(sizeof(struct os2_lock_t)); ! dprintf(("PyThread_allocate_lock called\n")); ! if (!initialized) ! PyThread_init_thread(); ! lock->is_set = 0; ! DosCreateEventSem(NULL, &lock->changed, 0, 0); ! dprintf(("%ld: PyThread_allocate_lock() -> %p\n", ! PyThread_get_thread_ident(), ! lock->changed)); ! return (PyThread_type_lock) lock; #endif } --- 127,158 ---- { #if defined(PYCC_GCC) ! _fmutex *sem = malloc(sizeof(_fmutex)); ! if (!initialized) ! PyThread_init_thread(); ! dprintf(("%ld: PyThread_allocate_lock() -> %lx\n", ! PyThread_get_thread_ident(), ! (long)sem)); ! if (_fmutex_create(sem, 0)) { ! free(sem); ! sem = NULL; ! } ! return (PyThread_type_lock)sem; #else ! APIRET rc; ! type_os2_lock lock = (type_os2_lock)malloc(sizeof(struct os2_lock_t)); ! dprintf(("PyThread_allocate_lock called\n")); ! if (!initialized) ! PyThread_init_thread(); ! lock->is_set = 0; ! DosCreateEventSem(NULL, &lock->changed, 0, 0); ! dprintf(("%ld: PyThread_allocate_lock() -> %p\n", ! PyThread_get_thread_ident(), ! lock->changed)); ! return (PyThread_type_lock)lock; #endif } *************** *** 161,177 **** { #if !defined(PYCC_GCC) ! type_os2_lock lock = (type_os2_lock)aLock; #endif ! dprintf(("%ld: PyThread_free_lock(%p) called\n", PyThread_get_thread_ident(),aLock)); #if defined(PYCC_GCC) ! if (aLock) { ! _fmutex_close((_fmutex *)aLock); ! free((_fmutex *)aLock); ! } #else ! DosCloseEventSem(lock->changed); ! free(aLock); #endif } --- 162,179 ---- { #if !defined(PYCC_GCC) ! type_os2_lock lock = (type_os2_lock)aLock; #endif ! dprintf(("%ld: PyThread_free_lock(%p) called\n", ! PyThread_get_thread_ident(),aLock)); #if defined(PYCC_GCC) ! if (aLock) { ! _fmutex_close((_fmutex *)aLock); ! free((_fmutex *)aLock); ! } #else ! DosCloseEventSem(lock->changed); ! free(aLock); #endif } *************** *** 186,230 **** { #if !defined(PYCC_GCC) ! int done = 0; ! ULONG count; ! PID pid = 0; ! TID tid = 0; ! type_os2_lock lock = (type_os2_lock)aLock; #endif ! dprintf(("%ld: PyThread_acquire_lock(%p, %d) called\n", PyThread_get_thread_ident(), ! aLock, waitflag)); #if defined(PYCC_GCC) ! /* always successful if the lock doesn't exist */ ! if (aLock && _fmutex_request((_fmutex *)aLock, waitflag ? 0 : _FMR_NOWAIT)) ! return 0; #else ! while (!done) { ! /* if the lock is currently set, we have to wait for the state to change */ ! if (lock->is_set) { ! if (!waitflag) ! return 0; ! DosWaitEventSem(lock->changed, SEM_INDEFINITE_WAIT); ! } ! ! /* ! * enter a critical section and try to get the semaphore. If ! * it is still locked, we will try again. ! */ ! if (DosEnterCritSec()) ! return 0; ! if (!lock->is_set) { ! lock->is_set = 1; ! DosResetEventSem(lock->changed, &count); ! done = 1; ! } ! DosExitCritSec(); ! } #endif ! return 1; } --- 188,236 ---- { #if !defined(PYCC_GCC) ! int done = 0; ! ULONG count; ! PID pid = 0; ! TID tid = 0; ! type_os2_lock lock = (type_os2_lock)aLock; #endif ! dprintf(("%ld: PyThread_acquire_lock(%p, %d) called\n", ! PyThread_get_thread_ident(), ! aLock, ! waitflag)); #if defined(PYCC_GCC) ! /* always successful if the lock doesn't exist */ ! if (aLock && ! _fmutex_request((_fmutex *)aLock, waitflag ? 0 : _FMR_NOWAIT)) ! return 0; #else ! while (!done) { ! /* if the lock is currently set, we have to wait for ! * the state to change ! */ ! if (lock->is_set) { ! if (!waitflag) ! return 0; ! DosWaitEventSem(lock->changed, SEM_INDEFINITE_WAIT); ! } ! /* enter a critical section and try to get the semaphore. If ! * it is still locked, we will try again. ! */ ! if (DosEnterCritSec()) ! return 0; ! if (!lock->is_set) { ! lock->is_set = 1; ! DosResetEventSem(lock->changed, &count); ! done = 1; ! } ! ! DosExitCritSec(); ! } #endif ! return 1; } *************** *** 232,261 **** { #if !defined(PYCC_GCC) ! type_os2_lock lock = (type_os2_lock)aLock; #endif ! dprintf(("%ld: PyThread_release_lock(%p) called\n", PyThread_get_thread_ident(),aLock)); #if defined(PYCC_GCC) ! if (aLock) ! _fmutex_release((_fmutex *)aLock); #else ! if (!lock->is_set) { ! dprintf(("%ld: Could not PyThread_release_lock(%p) error: %l\n", ! PyThread_get_thread_ident(), aLock, GetLastError())); ! return; ! } ! if (DosEnterCritSec()) { ! dprintf(("%ld: Could not PyThread_release_lock(%p) error: %l\n", ! PyThread_get_thread_ident(), aLock, GetLastError())); ! return; ! } ! ! lock->is_set = 0; ! DosPostEventSem(lock->changed); ! ! DosExitCritSec(); #endif } --- 238,272 ---- { #if !defined(PYCC_GCC) ! type_os2_lock lock = (type_os2_lock)aLock; #endif ! dprintf(("%ld: PyThread_release_lock(%p) called\n", ! PyThread_get_thread_ident(), ! aLock)); #if defined(PYCC_GCC) ! if (aLock) ! _fmutex_release((_fmutex *)aLock); #else ! if (!lock->is_set) { ! dprintf(("%ld: Could not PyThread_release_lock(%p) error: %l\n", ! PyThread_get_thread_ident(), ! aLock, ! GetLastError())); ! return; ! } ! ! if (DosEnterCritSec()) { ! dprintf(("%ld: Could not PyThread_release_lock(%p) error: %l\n", ! PyThread_get_thread_ident(), ! aLock, ! GetLastError())); ! return; ! } + lock->is_set = 0; + DosPostEventSem(lock->changed); ! DosExitCritSec(); #endif } From aimacintyre@users.sourceforge.net Wed Dec 4 12:37:19 2002 From: aimacintyre@users.sourceforge.net (aimacintyre@users.sourceforge.net) Date: Wed, 04 Dec 2002 04:37:19 -0800 Subject: [Python-checkins] python/dist/src/PC/os2emx Makefile,1.5,1.6 Message-ID: Update of /cvsroot/python/python/dist/src/PC/os2emx In directory sc8-pr-cvs1:/tmp/cvs-serv26266 Modified Files: Makefile Log Message: make BSDDB 1.85 module buildable again after BSDDB3 module import Index: Makefile =================================================================== RCS file: /cvsroot/python/python/dist/src/PC/os2emx/Makefile,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** Makefile 18 Aug 2002 06:26:33 -0000 1.5 --- Makefile 4 Dec 2002 12:37:17 -0000 1.6 *************** *** 237,241 **** DESCRIPTION.mpz$(MODULE.EXT)= Python Extension DLL for access to GNU multi-precision library DESCRIPTION.readline$(MODULE.EXT)= Python Extension DLL for access to GNU ReadLine library ! DESCRIPTION.bsddb$(MODULE.EXT)= Python Extension DLL for access to BSD DB (v1.85) library DESCRIPTION._curses$(MODULE.EXT)= Python Extension DLL for access to ncurses library DESCRIPTION.pyexpat$(MODULE.EXT)= Python Extension DLL for access to expat library --- 237,241 ---- DESCRIPTION.mpz$(MODULE.EXT)= Python Extension DLL for access to GNU multi-precision library DESCRIPTION.readline$(MODULE.EXT)= Python Extension DLL for access to GNU ReadLine library ! DESCRIPTION.bsddb185$(MODULE.EXT)= Python Extension DLL for access to BSD DB (v1.85) library DESCRIPTION._curses$(MODULE.EXT)= Python Extension DLL for access to ncurses library DESCRIPTION.pyexpat$(MODULE.EXT)= Python Extension DLL for access to expat library *************** *** 423,427 **** endif ifeq ($(BSDDB),yes) ! HARDEXTMODULES+= bsddb endif ifeq ($(CURSES),yes) --- 423,427 ---- endif ifeq ($(BSDDB),yes) ! HARDEXTMODULES+= bsddb185 endif ifeq ($(CURSES),yes) *************** *** 576,580 **** # - optional modules (requiring other software to be installed) ! bsddb$(MODULE.EXT): $(OUT)bsddbmodule$O $(OUT)bsddb_m.def $(PYTHON.IMPLIB) $(LD) $(LDFLAGS.DLL) -o $@ $(^^) $(L^) -ldb $(LIBS) --- 576,580 ---- # - optional modules (requiring other software to be installed) ! bsddb185$(MODULE.EXT): $(OUT)bsddbmodule$O $(OUT)bsddb185_m.def $(PYTHON.IMPLIB) $(LD) $(LDFLAGS.DLL) -o $@ $(^^) $(L^) -ldb $(LIBS) From aimacintyre@users.sourceforge.net Wed Dec 4 12:40:51 2002 From: aimacintyre@users.sourceforge.net (aimacintyre@users.sourceforge.net) Date: Wed, 04 Dec 2002 04:40:51 -0800 Subject: [Python-checkins] python/dist/src/PC/os2emx README.os2emx,1.2,1.3 Message-ID: Update of /cvsroot/python/python/dist/src/PC/os2emx In directory sc8-pr-cvs1:/tmp/cvs-serv28339 Modified Files: README.os2emx Log Message: history update Index: README.os2emx =================================================================== RCS file: /cvsroot/python/python/dist/src/PC/os2emx/README.os2emx,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** README.os2emx 18 Aug 2002 06:28:21 -0000 1.2 --- README.os2emx 4 Dec 2002 12:40:49 -0000 1.3 *************** *** 6,10 **** This release of the port incorporates the following changes from the ! April 14, 2002 release of the Python 2.2.1 port: - based on the Python v2.3 final release source. --- 6,10 ---- This release of the port incorporates the following changes from the ! October 24, 2002 release of the Python 2.2.2 port: - based on the Python v2.3 final release source. *************** *** 80,83 **** --- 80,84 ---- - v2.2.1c2 on March 31, 2002 (not uploaded to archive sites); - v2.2.1 on April 14, 2002. + - v2.2.2 on October 24, 2002. It is possible to have these earlier ports still usable after installing From tim_one@users.sourceforge.net Wed Dec 4 19:24:35 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 04 Dec 2002 11:24:35 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime test_both.py,1.31,1.32 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv4382 Modified Files: test_both.py Log Message: Added a new test for the module constants (trivial, but needs to be tested!). Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.31 retrieving revision 1.32 diff -C2 -d -r1.31 -r1.32 *** test_both.py 3 Dec 2002 23:07:28 -0000 1.31 --- test_both.py 4 Dec 2002 19:24:32 -0000 1.32 *************** *** 37,40 **** --- 37,49 ---- ############################################################################# + # module tests + + class TestModule(unittest.TestCase): + + def test_constants(self): + self.assertEqual(datetime.MINYEAR, 1) + self.assertEqual(datetime.MAXYEAR, 9999) + + ############################################################################# # timedelta tests *************** *** 853,857 **** def test_suite(): allsuites = [unittest.makeSuite(klass, 'test') ! for klass in (TestTimeDelta, TestDate, TestDateTime, --- 862,867 ---- def test_suite(): allsuites = [unittest.makeSuite(klass, 'test') ! for klass in (TestModule, ! TestTimeDelta, TestDate, TestDateTime, From tim_one@users.sourceforge.net Wed Dec 4 19:49:14 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 04 Dec 2002 11:49:14 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime doc.txt,1.2,1.3 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv29188 Modified Files: doc.txt Log Message: Started documenting the date class; much more is needed, and I see some methods in the Python implementation don't yet exist in the C implementation. Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** doc.txt 4 Dec 2002 04:12:01 -0000 1.2 --- doc.txt 4 Dec 2002 19:49:11 -0000 1.3 *************** *** 33,36 **** --- 33,47 ---- + Module constants + ================ + MINYEAR + The smallest year number allowed in a date, datetime, or datetimetz + object. + + MAXYEAR + The largest year number allowed in a date, datetime, or datetimetz + object. + + class timedelta =============== *************** *** 98,101 **** --- 109,115 ---- This is exact, but may overflow. + - certain additions and subtractions with date, datetime, and datimetz + objects (see below) + - timedelta // (int or long) -> timedelta The floor is computed and the remainder (if any) is thrown away. *************** *** 111,121 **** - pickling - In addition, subtraction of two datetime objects returns a timedelta, - and addition or subtraction of a datetime and a timedelta returns a - datetime. - class date ========== --- 125,198 ---- - pickling class date ========== + A date object represents a date (year, month and day) in an idealized + calendar, the current Gregorian calendar indefinitely extended in both + directions. January 1 of year 1 is called day number 1, January 2 of year + 1 is called day number 2, and so on. This matches the definition of the + "proleptic Gregorian" calendar in Dershowitz and Reingold's book + "Calendrical Calculations", where it's the base calendar for all + computations. See the book for algorithms for converting between + proleptic Gregorian ordinals and many other calendar systems. + + Constructor: + + date(year, month, day) + + All arguments are required. Arguments may be ints or longs, in the + following ranges: + + MINYEAR <= year <= MAXYEAR + 1 <= month <= 12 + 1 <= day <= number of days in the given month and year + + If an argument outside those ranges is given, ValueError is raised. + + + Class attributes: + + .min + The earliest representable date, date(MINYEAR, 1, 1). + + .max + The latest representable date, date(MAXYEAR, 12, 31). + + .resolution + The smallest possible difference between non-equal date + objects, timedelta(days=1). + + Instance attributes (read-only): + + .year between MINYEAR and MAXYEAR inclusive + .month between 1 and 12 inclusive + .day between 1 and the number of days in the given month + of the given year + + Supported operations: + + - date1 + timedelta -> date2 + timedelta + date1 -> date2 + date2 is timedelta.days days removed from the date1, moving forward + in time if timedelta.days > 0, and date2 - date1 == timedelta.days + after. timedelta.seconds and timedelta.microseconds are ignored. + OverflowError is raised if date2.year would be smaller than MINYEAR + or larger than MAXYEAR. + + - date1 - timedelta -> date2 + The same as date1 + (-timedelta). + + - date1 - date2 -> timedelta + This is exact, and cannot overflow. timedelta.seconds and + timedelta.microseconds are 0, and date2 + timedelta == date1 + after. + + - comparison of date to date, where date1 is considered less than + date2 when date1 precedes date2 in time. + + - hash, use as dict key + + - pickling + From loewis@users.sourceforge.net Wed Dec 4 19:54:38 2002 From: loewis@users.sourceforge.net (loewis@users.sourceforge.net) Date: Wed, 04 Dec 2002 11:54:38 -0800 Subject: [Python-checkins] python/dist/src/Modules _tkinter.c,1.133,1.134 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv2233/Modules Modified Files: _tkinter.c Log Message: Decode untyped strings from UTF-8. Index: _tkinter.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/_tkinter.c,v retrieving revision 1.133 retrieving revision 1.134 diff -C2 -d -r1.133 -r1.134 *** _tkinter.c 26 Nov 2002 22:12:12 -0000 1.133 --- _tkinter.c 4 Dec 2002 19:54:36 -0000 1.134 *************** *** 771,776 **** TkappObject *app = (TkappObject*)tkapp; ! if (value->typePtr == NULL) ! return PyString_FromStringAndSize(value->bytes, value->length); if (value->typePtr == app->BooleanType) { --- 771,801 ---- TkappObject *app = (TkappObject*)tkapp; ! if (value->typePtr == NULL) { ! /* If the result contains any bytes with the top bit set, ! it's UTF-8 and we should decode it to Unicode */ ! #ifdef Py_USING_UNICODE ! int i; ! char *s = value->bytes; ! int len = value->length; ! for (i = 0; i < len; i++) { ! if (value->bytes[i] & 0x80) ! break; ! } ! ! if (i == value->length) ! result = PyString_FromStringAndSize(s, len); ! else { ! /* Convert UTF-8 to Unicode string */ ! result = PyUnicode_DecodeUTF8(s, len, "strict"); ! if (result == NULL) { ! PyErr_Clear(); ! result = PyString_FromStringAndSize(s, len); ! } ! } ! #else ! res = PyString_FromStringAndSize(value->bytes, value->length); ! #endif ! return result; ! } if (value->typePtr == app->BooleanType) { From tim_one@users.sourceforge.net Wed Dec 4 22:08:27 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 04 Dec 2002 14:08:27 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime doc.txt,1.4,1.5 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv28230 Modified Files: doc.txt Log Message: Typo repair. Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** doc.txt 4 Dec 2002 22:07:15 -0000 1.4 --- doc.txt 4 Dec 2002 22:08:21 -0000 1.5 *************** *** 170,174 **** where January 1 of year 1 has ordinal 1. ValueError is raised unless 1 <= ordinal <= date.max.toordinal(). For any date d, ! date.fromordinal(d.toordinal()) == d Class attributes: --- 170,174 ---- where January 1 of year 1 has ordinal 1. ValueError is raised unless 1 <= ordinal <= date.max.toordinal(). For any date d, ! d.fromordinal(d.toordinal()) == d Class attributes: From tim_one@users.sourceforge.net Wed Dec 4 22:07:24 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 04 Dec 2002 14:07:24 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime doc.txt,1.3,1.4 obj_date.c,1.20,1.21 test_both.py,1.32,1.33 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv27619 Modified Files: doc.txt obj_date.c test_both.py Log Message: Implemented the date fromtimestamp() and fromordinal() class methods (the Python implementation already had them). Added a simple test for extreme ordinal values. Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** doc.txt 4 Dec 2002 19:49:11 -0000 1.3 --- doc.txt 4 Dec 2002 22:07:15 -0000 1.4 *************** *** 150,153 **** --- 150,174 ---- If an argument outside those ranges is given, ValueError is raised. + Other constructors (class methods): + + - today() + + Return the current local date. This is equivalent to + fromtimestamp(time.time()). + + - fromtimestamp(timestamp) + + Return the local date corresponding to the POSIX timestamp, such as + is returned by time.time(). This may raise ValueError, if the + timestamp is out of the range of values supported by the platform C + localtime() function. It's common for this to be restricted to + years in 1970 through 2038. + + - fromordinal(ordinal) + + Return the date corresponding to the proleptic Gregorian ordinal, + where January 1 of year 1 has ordinal 1. ValueError is raised + unless 1 <= ordinal <= date.max.toordinal(). For any date d, + date.fromordinal(d.toordinal()) == d Class attributes: Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.20 retrieving revision 1.21 diff -C2 -d -r1.20 -r1.21 *** obj_date.c 4 Dec 2002 05:08:14 -0000 1.20 --- obj_date.c 4 Dec 2002 22:07:15 -0000 1.21 *************** *** 156,159 **** --- 156,161 ---- } + /* Constructor. */ + static PyObject * date_new(PyTypeObject *type, PyObject *args, PyObject *kw) *************** *** 188,191 **** --- 190,268 ---- } + /* Class-method constructors. */ + + /* Return new date from localtime(t). */ + static PyObject * + date_local_from_time_t(PyObject *cls, time_t t) + { + struct tm *tm; + PyObject *result = NULL; + + tm = localtime(&t); + if (tm) + result = PyObject_CallFunction(cls, "iii", + tm->tm_year + 1900, + tm->tm_mon + 1, + tm->tm_mday); + else + PyErr_SetString(PyExc_ValueError, + "timestamp out of range for " + "platform localtime() function"); + return result; + } + + /* Return new date from current time. */ + static PyObject * + date_today(PyObject *self, PyObject *cls) + { + time_t timet; + + time(&timet); + return date_local_from_time_t(cls, timet); + } + + /* Return new date from given timestamp (Python timestamp -- a double). */ + static PyObject * + date_fromtimestamp(PyObject *self, PyObject *args) + { + PyObject *cls; + double timestamp; + PyObject *result = NULL; + + if (PyArg_ParseTuple(args, "Od:fromtimestamp", &cls, ×tamp)) + result = date_local_from_time_t(cls, (time_t)timestamp); + return result; + } + + /* Return new date from proleptic Gregorian ordinal. Raises ValueError if + * the ordinal is out of range. + */ + static PyObject * + date_fromordinal(PyObject *self, PyObject *args) + { + PyObject *result = NULL; + PyObject *cls; + long ordinal; + + + if (PyArg_ParseTuple(args, "Ol:fromtimestamp", &cls, &ordinal)) { + long year; + long month; + long day; + + if (ordinal < 1) + PyErr_SetString(PyExc_ValueError, "ordinal must be " + ">= 1"); + else { + ord_to_ymd(ordinal, &year, &month, &day); + result = PyObject_CallFunction(cls, "lll", + year, month, day); + } + } + return result; + } + + /* Attributes. */ + static PyObject * date_year(PyDateTime_Date *self, void *unused) *************** *** 351,369 **** static PyObject * - date_today(PyObject *self, PyObject *cls) - { - /* XXX need to create the instance by calling cls(y,mon,d,h,min,s,u) */ - struct tm *tm; - time_t timet; - - time(&timet); - tm = localtime(&timet); - - return PyObject_CallFunction(cls, "iii", - tm->tm_year + 1900, tm->tm_mon + 1, - tm->tm_mday); - } - - static PyObject * date_toordinal(PyDateTime_Date *self) { --- 428,431 ---- *************** *** 436,441 **** static PyMethodDef date_methods[] = { /* Class methods: */ ! {"today", (PyCFunction)date_today, METH_O | METH_CLASS, ! "Return a new date that represents the current date."}, /* Instance methods: */ --- 498,509 ---- static PyMethodDef date_methods[] = { /* Class methods: */ ! {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS | ! METH_CLASS, ! "timestamp -> local date from a POSIX timestamp (like time.time())."}, ! {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS | ! METH_CLASS, ! "int -> date corresponding to a proleptic Gregorian ordinal."}, ! {"today", (PyCFunction)date_today, METH_O | METH_CLASS, ! "Construct local date corresponing to current day."}, /* Instance methods: */ Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.32 retrieving revision 1.33 diff -C2 -d -r1.32 -r1.33 *** test_both.py 4 Dec 2002 19:24:32 -0000 1.32 --- test_both.py 4 Dec 2002 22:07:16 -0000 1.33 *************** *** 351,354 **** --- 351,379 ---- n += 1 + def test_extreme_ordinals(self): + a = self.theclass.min + a = self.theclass(a.year, a.month, a.day) # get rid of time parts + aord = a.toordinal() + b = a.fromordinal(aord) + self.assertEqual(a, b) + + self.assertRaises(ValueError, lambda: a.fromordinal(aord - 1)) + + b = a + timedelta(days=1) + self.assertEqual(b.toordinal(), aord + 1) + self.assertEqual(b, self.theclass.fromordinal(aord + 1)) + + a = self.theclass.max + a = self.theclass(a.year, a.month, a.day) # get rid of time parts + aord = a.toordinal() + b = a.fromordinal(aord) + self.assertEqual(a, b) + + self.assertRaises(ValueError, lambda: a.fromordinal(aord + 1)) + + b = a - timedelta(days=1) + self.assertEqual(b.toordinal(), aord - 1) + self.assertEqual(b, self.theclass.fromordinal(aord - 1)) + def test_bad_constructor_arguments(self): # bad years From tim_one@users.sourceforge.net Wed Dec 4 22:18:56 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 04 Dec 2002 14:18:56 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_date.c,1.21,1.22 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv31978 Modified Files: obj_date.c Log Message: Typo repair. Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.21 retrieving revision 1.22 diff -C2 -d -r1.21 -r1.22 *** obj_date.c 4 Dec 2002 22:07:15 -0000 1.21 --- obj_date.c 4 Dec 2002 22:18:49 -0000 1.22 *************** *** 246,250 **** ! if (PyArg_ParseTuple(args, "Ol:fromtimestamp", &cls, &ordinal)) { long year; long month; --- 246,250 ---- ! if (PyArg_ParseTuple(args, "Ol:formordinal", &cls, &ordinal)) { long year; long month; From tim_one@users.sourceforge.net Wed Dec 4 22:49:19 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 04 Dec 2002 14:49:19 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime test_both.py,1.33,1.34 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv11846 Modified Files: test_both.py Log Message: Added a test for fromtimestamp(). Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.33 retrieving revision 1.34 diff -C2 -d -r1.33 -r1.34 *** test_both.py 4 Dec 2002 22:07:16 -0000 1.33 --- test_both.py 4 Dec 2002 22:49:04 -0000 1.34 *************** *** 468,471 **** --- 468,495 ---- self.assertRaises(OverflowError, dt.__sub__, -tiny) + def test_fromtimestamp(self): + import time + + # Try an arbitrary fixed value. + year, month, day = 1999, 9, 19 + ts = time.mktime((year, month, day, 0, 0, 0, 0, 0, -1)) + d = self.theclass.fromtimestamp(ts) + self.assertEqual(d.year, year) + self.assertEqual(d.month, month) + self.assertEqual(d.day, day) + + # Try today. + today = self.theclass.today() + ts = time.time() + todayagain = self.theclass.fromtimestamp(ts) + if today != todayagain: + # It's possible that equality fails if we're running at a + # midnight boundary, so wait a little and try again. + time.sleep(5) + today = self.theclass.today() + ts = time.time() + todayagain = self.theclass.fromtimestamp(ts) + self.assertEqual(today, todayagain) + def test_weekday(self): for i in range(7): From tim_one@users.sourceforge.net Wed Dec 4 23:08:57 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 04 Dec 2002 15:08:57 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime test_both.py,1.34,1.35 test_datetime.py,1.53,1.54 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv19359 Modified Files: test_both.py test_datetime.py Log Message: Moved the beefy test_ordinal_conversions() from test_datetime into test_both, replacing the latter's weaker version (it had a crippled version because the C date type didn't support an ordinal->date method before today). That was the last remaining date test in test_datetime, so removed the TestDate class from test_datetime too. Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.34 retrieving revision 1.35 diff -C2 -d -r1.34 -r1.35 *** test_both.py 4 Dec 2002 22:49:04 -0000 1.34 --- test_both.py 4 Dec 2002 23:08:47 -0000 1.35 *************** *** 326,352 **** # first example from "Calendrical Calculations" (1945, 11, 12, 710347)]: ! d = date(y, m, d) ! self.assertEqual(d.toordinal(), n) ! # Check first and last days of year exhaustively across the whole ! # range of years date objects support. ! n = 1 ! for year in range(MINYEAR, MAXYEAR+1): ! self.assertEqual(date(year, 1, 1).toordinal(), n) # Verify that moving back a day gets to the end of year-1. ! if year > MINYEAR: ! self.assertEqual(date(year - 1, 12, 31).toordinal(), n-1) ! n += 365 ! n += year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) ! # Check every day in a leap-year and a non-leap year. dim = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] ! for year, isleap in (2000, True), (2002, False): ! n = date(year, 1, 1).toordinal() for month, maxday in zip(range(1, 13), dim): if month == 2 and isleap: maxday += 1 for day in range(1, maxday+1): ! self.assertEqual(date(year, month, day).toordinal(), n) n += 1 --- 326,359 ---- # first example from "Calendrical Calculations" (1945, 11, 12, 710347)]: ! d = self.theclass(y, m, d) ! self.assertEqual(n, d.toordinal()) ! self.assertEqual(d, self.theclass.fromordinal(n)) ! # Check first and last days of year spottily across the whole ! # range of years supported. ! for year in xrange(MINYEAR, MAXYEAR+1, 7): ! # Verify (year, 1, 1) -> ordinal -> y, m, d is identity. ! d = self.theclass(year, 1, 1) ! n = d.toordinal() ! d2 = self.theclass.fromordinal(n) ! self.assertEqual(d, d2) # Verify that moving back a day gets to the end of year-1. ! if year > 1: ! d = self.theclass.fromordinal(n-1) ! d2 = self.theclass(year-1, 12, 31) ! self.assertEqual(d, d2) ! self.assertEqual(d2.toordinal(), n-1) ! # Test every day in a leap-year and a non-leap year. dim = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] ! for year, isleap in (2000, 1), (2002, 0): ! n = self.theclass(year, 1, 1).toordinal() for month, maxday in zip(range(1, 13), dim): if month == 2 and isleap: maxday += 1 for day in range(1, maxday+1): ! d = self.theclass(year, month, day) ! self.assertEqual(d.toordinal(), n) ! self.assertEqual(d, self.theclass.fromordinal(n)) n += 1 Index: test_datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_datetime.py,v retrieving revision 1.53 retrieving revision 1.54 diff -C2 -d -r1.53 -r1.54 *** test_datetime.py 1 Dec 2002 19:37:28 -0000 1.53 --- test_datetime.py 4 Dec 2002 23:08:49 -0000 1.54 *************** *** 10,56 **** MINYEAR, MAXYEAR - - class TestDate(unittest.TestCase): - - theclass = date - - # All the other tests here have been moved into test_both. This one - # relies on stuff only the Python version implements. - def test_ordinal_conversions(self): - from datetime import _ymd2ord, _ord2ymd - - # Check some fixed values. - for y, m, d, n in [(1, 1, 1, 1), # calendar origin - (0, 12, 31, 0), - (0, 12, 30, -1), - # first example from "Calendrical Calculations" - (1945, 11, 12, 710347)]: - self.assertEqual(n, _ymd2ord(y, m, d)) - self.assertEqual((y, m, d), _ord2ymd(n)) - - # Check first and last days of year exhaustively across 2000 years - # centered at the origin, and spottily over the whole range of - # years datetime objects support. - for year in range(-1001, 1002) + range(MINYEAR, MAXYEAR+1, 7): - # Verify (year, 1, 1) -> ordinal -> y, m, d is identity. - n = _ymd2ord(year, 1, 1) - self.assertEqual((year, 1, 1), _ord2ymd(n)) - # Verify that moving back a day gets to the end of year-1. - self.assertEqual((year-1, 12, 31), _ord2ymd(n-1)) - self.assertEqual(_ymd2ord(year-1, 12, 31), n-1) - - # Test every day in a leap-year and a non-leap year. - dim = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] - for year, isleap in (2000, 1), (2002, 0): - n = _ymd2ord(year, 1, 1) - for month, maxday in zip(range(1, 13), dim): - if month == 2 and isleap: - maxday += 1 - for day in range(1, maxday+1): - self.assertEqual((year, month, day), _ord2ymd(n)) - self.assertEqual(n, _ymd2ord(year, month, day)) - n += 1 - - class TestTime(unittest.TestCase): --- 10,13 ---- *************** *** 211,215 **** ! class TestDateTime(TestDate): theclass = datetime --- 168,172 ---- ! class TestDateTime(unittest.TestCase): theclass = datetime *************** *** 308,317 **** def test_suite(): - s2 = unittest.makeSuite(TestDate, 'test') s3 = unittest.makeSuite(TestTime, 'test') s4 = unittest.makeSuite(TestTimeTZ, 'test') s5 = unittest.makeSuite(TestDateTime, 'test') s6 = unittest.makeSuite(TestDateTimeTZ, 'test') ! return unittest.TestSuite([s2, s3, s4, s5, s6]) def test_main(): --- 265,273 ---- def test_suite(): s3 = unittest.makeSuite(TestTime, 'test') s4 = unittest.makeSuite(TestTimeTZ, 'test') s5 = unittest.makeSuite(TestDateTime, 'test') s6 = unittest.makeSuite(TestDateTimeTZ, 'test') ! return unittest.TestSuite([s3, s4, s5, s6]) def test_main(): From tim_one@users.sourceforge.net Thu Dec 5 00:40:36 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 04 Dec 2002 16:40:36 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime doc.txt,1.5,1.6 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv17668 Modified Files: doc.txt Log Message: Clarified some subtleties. Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** doc.txt 4 Dec 2002 22:08:21 -0000 1.5 --- doc.txt 5 Dec 2002 00:40:30 -0000 1.6 *************** *** 101,111 **** - timedelta + timedelta -> timedelta ! This is exact, but may overflow. - timedelta - timedelta -> timedelta ! This is exact, but may overflow. - timedelta * (int or long) -> timedelta ! This is exact, but may overflow. - certain additions and subtractions with date, datetime, and datimetz --- 101,120 ---- - timedelta + timedelta -> timedelta ! This is exact, but may overflow. After ! t1 = t2 + t3 ! t1-t2 == t3 and t1-t3 == t2 are true. - timedelta - timedelta -> timedelta ! This is exact, but may overflow. After ! t1 = t2 - t3 ! t2 == t1 + t3 is true. - timedelta * (int or long) -> timedelta ! (int or long) * timedelta -> timedelta ! This is exact, but may overflow. After ! t1 = t2 * i ! t1 // i == t2 is true, provided i != 0. In general, ! t * i == t * (i-1) + t ! is true. - certain additions and subtractions with date, datetime, and datimetz *************** *** 116,121 **** Division by 0 raises ZeroDivisionError. ! - unary plus, minus, abs ! These are exact, but unary minus may overflow. - comparison of timedelta to timedelta --- 125,139 ---- Division by 0 raises ZeroDivisionError. ! - +timedelta -> timedelta ! Returns a timedelta object with the same value. ! ! - -timedelta -> timedelta ! -t is equivalent to timedelta(-t.days, -t.seconds, -t.microseconds), ! and to t*-1. This is exact, but may overflow (for example, ! -time.max is not representable as a timedelta object). ! ! - abs(timedelta) -> timedelta ! abs(t) is equivalent to +t when t.days >= 0, and to -t when ! t.days < 0. This is exact, and cannot overflow. - comparison of timedelta to timedelta *************** *** 155,159 **** Return the current local date. This is equivalent to ! fromtimestamp(time.time()). - fromtimestamp(timestamp) --- 173,177 ---- Return the current local date. This is equivalent to ! date.fromtimestamp(time.time()). - fromtimestamp(timestamp) *************** *** 170,174 **** where January 1 of year 1 has ordinal 1. ValueError is raised unless 1 <= ordinal <= date.max.toordinal(). For any date d, ! d.fromordinal(d.toordinal()) == d Class attributes: --- 188,192 ---- where January 1 of year 1 has ordinal 1. ValueError is raised unless 1 <= ordinal <= date.max.toordinal(). For any date d, ! date.fromordinal(d.toordinal()) == d. Class attributes: *************** *** 202,206 **** - date1 - timedelta -> date2 ! The same as date1 + (-timedelta). - date1 - date2 -> timedelta --- 220,227 ---- - date1 - timedelta -> date2 ! Computes the date2 such that date2 + timedelta == date1. This ! isn't quite equivalent to date1 + (-timedelta), because -timedelta ! in isolation can overflow in cases where date1 - timedelta does ! not. - date1 - date2 -> timedelta *************** *** 210,214 **** - comparison of date to date, where date1 is considered less than ! date2 when date1 precedes date2 in time. - hash, use as dict key --- 231,236 ---- - comparison of date to date, where date1 is considered less than ! date2 when date1 precedes date2 in time. In other words, ! date1 < date2 if and only if date1.toordinal() < date2.toordinal(). - hash, use as dict key From tim_one@users.sourceforge.net Thu Dec 5 01:39:41 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 04 Dec 2002 17:39:41 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.py,1.74,1.75 doc.txt,1.6,1.7 obj_date.c,1.22,1.23 obj_datetime.c,1.15,1.16 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv3759 Modified Files: datetime.py doc.txt obj_date.c obj_datetime.c Log Message: Fleshed out the docs for class date. Repaired some senseless docstrings. Noted that date.strftime() doesn't exist in the C implementation, and that there are no tests of it in the Python implementation either. Index: datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.py,v retrieving revision 1.74 retrieving revision 1.75 diff -C2 -d -r1.74 -r1.75 *** datetime.py 3 Dec 2002 21:50:20 -0000 1.74 --- datetime.py 5 Dec 2002 01:39:39 -0000 1.75 *************** *** 496,501 **** timetuple() toordinal() ! weekday(), isoweekday(), isocalendar() ! isoformat() Properties (readonly): --- 496,503 ---- timetuple() toordinal() ! weekday() ! isoweekday(), isocalendar(), isoformat() ! ctime() ! strftime() Properties (readonly): *************** *** 1036,1044 **** timetuple() ctime() strftime() - toordinal() - weekday(), isoweekday(), isocalendar() - isoformat() Properties (readonly): --- 1038,1046 ---- timetuple() + toordinal() + weekday() + isoweekday(), isocalendar(), isoformat() ctime() strftime() Properties (readonly): *************** *** 1228,1233 **** """Return the time formatted according to ISO. ! This is 'YYYY-MM-DD HH:MM:SS.mmmmmm' ! where -xx:yy is the timezone offset. Optional argument sep specifies the separator between date and --- 1230,1234 ---- """Return the time formatted according to ISO. ! This is 'YYYY-MM-DD HH:MM:SS.mmmmmm'. Optional argument sep specifies the separator between date and Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** doc.txt 5 Dec 2002 00:40:30 -0000 1.6 --- doc.txt 5 Dec 2002 01:39:39 -0000 1.7 *************** *** 238,241 **** --- 238,303 ---- - pickling + Instance methods: + + - timetuple() + Return a 9-element tuple of the form returned by time.localtime(). + The hours, minutes and seconds are 0, and the DST flag is -1. + d.timetuple() is equivalent to + (d.year, d.month, d.day, + 0, 0, 0, # h, m, s + d.weekday(), # 0 is Monday + d.toordinal() - date(d.year, 1, 1).toordinal() + 1, # day of year + -1) + + - toordinal() + Return the proleptic Gregorian ordinal of the date, where January 1 + of year 1 has ordinal 1. For any date object d, + date.fromordinal(d.toordinal()) == d. + + - weekday() + Return the day of the week as an integer, where Monday is 0 and + Sunday is 6. For example, date(2002, 12, 4).weekday() == 2, a + Wednesday. + See also isoweekday(). + + - isoweekday() + Return the day of the week as an integer, where Monday is 1 and + Sunday is 7. For example, date(2002, 12, 4).isoweekday() == 3, a + Wednesday. + See also weekday() and isocalendar(). + + - isocalendar() + Return a 3-tuple, (ISO year, ISO week number, ISO weekday). + + The ISO calendar is a widely used variant of the Gregorian calendar. + See + for a good explanation. + + The ISO year consists of 52 or 53 full weeks, and where a week starts + on a Monday and ends on a Sunday. The first week of an ISO year is + the first (Gregorian) calendar week of a year containing a Thursday. + This is called week number 1, and the ISO year of that Thursday is + the same as its Gregorian year. + + For example, 2004 begins on a Thursday, so the first week of ISO + year 2004 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan + 2004, so that + + date(2003, 12, 29).isocalendar() == (2004, 1, 1) + date(2004, 1, 4).isocalendar() == (2004, 1, 7) + + - isoformat() + Return a string representing the date in ISO 8601 format, + 'YYYY-MM-DD'. For example, + date(2002, 12, 4).isoformat() == '2002-12-04'. + + - ctime() + Return a string representing the date, for example + date(2002, 12, 4).ctime() == 'Wed Dec 4 00:00:00 2002'. + d.ctime() is equivalent to time.ctime(time.mktime(d.timetuple())). + + - strftime(format) + XXX And the C implementation doesn't have this yet either. + XXX And there are no tests for it. Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.22 retrieving revision 1.23 diff -C2 -d -r1.22 -r1.23 *** obj_date.c 4 Dec 2002 22:18:49 -0000 1.22 --- obj_date.c 5 Dec 2002 01:39:39 -0000 1.23 *************** *** 496,499 **** --- 496,500 ---- } + /* XXX strftime is missing. */ static PyMethodDef date_methods[] = { /* Class methods: */ *************** *** 515,528 **** "Return a 3-tuple containing ISO year, week number, and weekday.\n\n" "The first ISO week of the year is the (Mon-Sun) week containing the\n" ! "year's first Thursday; everything rest derives from that."}, {"isoformat", (PyCFunction)date_isoformat, METH_KEYWORDS, ! "Return the day of the week represented by the date.\n" ! "Monday == 1 ... Sunday == 7"}, {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS, "Return the day of the week represented by the date.\n" "Monday == 1 ... Sunday == 7"}, {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS, ! "Return proleptic Gregorian ordinal for the year, month and day.\n" ! "January 1 of year 1 is day 1."}, {"weekday", (PyCFunction)date_weekday, METH_NOARGS, "Return the day of the week represented by the date.\n" --- 516,527 ---- "Return a 3-tuple containing ISO year, week number, and weekday.\n\n" "The first ISO week of the year is the (Mon-Sun) week containing the\n" ! "year's first Thursday; everything else derives from that."}, {"isoformat", (PyCFunction)date_isoformat, METH_KEYWORDS, ! "Return string in ISO 8601 format, YYYY-MM-DD."}, {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS, "Return the day of the week represented by the date.\n" "Monday == 1 ... Sunday == 7"}, {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS, ! "Return proleptic Gregorian ordinal. January 1 of year 1 is day 1."}, {"weekday", (PyCFunction)date_weekday, METH_NOARGS, "Return the day of the week represented by the date.\n" Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.15 retrieving revision 1.16 diff -C2 -d -r1.15 -r1.16 *** obj_datetime.c 4 Dec 2002 05:08:14 -0000 1.15 --- obj_datetime.c 5 Dec 2002 01:39:39 -0000 1.16 *************** *** 464,469 **** "Return ctime() style string."}, {"isoformat", (PyCFunction)datetime_isoformat, METH_KEYWORDS, ! "Return the day of the week represented by the datetime.\n" ! "Monday == 1 ... Sunday == 7"}, {"__setstate__", (PyCFunction)datetime_setstate, METH_O, PyDoc_STR("__setstate__(state)")}, --- 464,470 ---- "Return ctime() style string."}, {"isoformat", (PyCFunction)datetime_isoformat, METH_KEYWORDS, ! "[sep] -> string in ISO 8601 format, YYYY-MM-DDTHH:MM:SS.mmmmmm.\n" ! "\n\nsep is used to separate the year from the time, and defaults\n" ! "to 'T'."}, {"__setstate__", (PyCFunction)datetime_setstate, METH_O, PyDoc_STR("__setstate__(state)")}, From tim_one@users.sourceforge.net Thu Dec 5 01:53:27 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 04 Dec 2002 17:53:27 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_datetime.c,1.16,1.17 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv8377 Modified Files: obj_datetime.c Log Message: Repaired botched newlines I introduced in a docstring. Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.16 retrieving revision 1.17 diff -C2 -d -r1.16 -r1.17 *** obj_datetime.c 5 Dec 2002 01:39:39 -0000 1.16 --- obj_datetime.c 5 Dec 2002 01:53:25 -0000 1.17 *************** *** 464,469 **** "Return ctime() style string."}, {"isoformat", (PyCFunction)datetime_isoformat, METH_KEYWORDS, ! "[sep] -> string in ISO 8601 format, YYYY-MM-DDTHH:MM:SS.mmmmmm.\n" ! "\n\nsep is used to separate the year from the time, and defaults\n" "to 'T'."}, {"__setstate__", (PyCFunction)datetime_setstate, METH_O, --- 464,469 ---- "Return ctime() style string."}, {"isoformat", (PyCFunction)datetime_isoformat, METH_KEYWORDS, ! "[sep] -> string in ISO 8601 format, YYYY-MM-DDTHH:MM:SS.mmmmmm.\n\n" ! "sep is used to separate the year from the time, and defaults\n" "to 'T'."}, {"__setstate__", (PyCFunction)datetime_setstate, METH_O, From tim_one@users.sourceforge.net Thu Dec 5 01:56:52 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 04 Dec 2002 17:56:52 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime doc.txt,1.7,1.8 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv9781 Modified Files: doc.txt Log Message: Typo repair. Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** doc.txt 5 Dec 2002 01:39:39 -0000 1.7 --- doc.txt 5 Dec 2002 01:56:50 -0000 1.8 *************** *** 131,135 **** -t is equivalent to timedelta(-t.days, -t.seconds, -t.microseconds), and to t*-1. This is exact, but may overflow (for example, ! -time.max is not representable as a timedelta object). - abs(timedelta) -> timedelta --- 131,135 ---- -t is equivalent to timedelta(-t.days, -t.seconds, -t.microseconds), and to t*-1. This is exact, but may overflow (for example, ! -timedelta.max is not representable as a timedelta object). - abs(timedelta) -> timedelta From montanaro@users.sourceforge.net Thu Dec 5 02:37:25 2002 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Wed, 04 Dec 2002 18:37:25 -0800 Subject: [Python-checkins] python/dist/src/Tools/scripts ftpmirror.py,1.15,1.16 Message-ID: Update of /cvsroot/python/python/dist/src/Tools/scripts In directory sc8-pr-cvs1:/tmp/cvs-serv20636 Modified Files: ftpmirror.py Log Message: allow optional port specified as part of the hostname, e.g., "www.zope.org:8021". Index: ftpmirror.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Tools/scripts/ftpmirror.py,v retrieving revision 1.15 retrieving revision 1.16 diff -C2 -d -r1.15 -r1.16 *** ftpmirror.py 11 Sep 2002 20:36:01 -0000 1.15 --- ftpmirror.py 5 Dec 2002 02:37:23 -0000 1.16 *************** *** 5,9 **** usage: ftpmirror [-v] [-q] [-i] [-m] [-n] [-r] [-s pat] [-l username [-p passwd [-a account]]] ! hostname [remotedir [localdir]] -v: verbose -q: quiet --- 5,9 ---- usage: ftpmirror [-v] [-q] [-i] [-m] [-n] [-r] [-s pat] [-l username [-p passwd [-a account]]] ! hostname[:port] [remotedir [localdir]] -v: verbose -q: quiet *************** *** 14,18 **** -l username [-p passwd [-a account]]: login info (default .netrc or anonymous) -s pat: skip files matching pattern ! hostname: remote host remotedir: remote directory (default initial) localdir: local directory (default current) --- 14,18 ---- -l username [-p passwd [-a account]]: login info (default .netrc or anonymous) -s pat: skip files matching pattern ! hostname: remote host w/ optional port separated by ':' remotedir: remote directory (default initial) localdir: local directory (default current) *************** *** 53,56 **** --- 53,59 ---- if not args: usage('hostname missing') host = args[0] + port = 0 + if ':' in host: + host, port = host.split(':', 1) try: auth = netrc.netrc().authenticators(host) *************** *** 80,84 **** f = ftplib.FTP() if verbose: print 'Connecting to %s...' % `host` ! f.connect(host) if not nologin: if verbose: --- 83,87 ---- f = ftplib.FTP() if verbose: print 'Connecting to %s...' % `host` ! f.connect(host,port) if not nologin: if verbose: From montanaro@users.sourceforge.net Thu Dec 5 02:43:16 2002 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Wed, 04 Dec 2002 18:43:16 -0800 Subject: [Python-checkins] python/dist/src/Tools/scripts ftpmirror.py,1.16,1.17 Message-ID: Update of /cvsroot/python/python/dist/src/Tools/scripts In directory sc8-pr-cvs1:/tmp/cvs-serv22142 Modified Files: ftpmirror.py Log Message: * when given, port should be converted to int * when connecting, if the port is non-standard, display it as well Index: ftpmirror.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Tools/scripts/ftpmirror.py,v retrieving revision 1.16 retrieving revision 1.17 diff -C2 -d -r1.16 -r1.17 *** ftpmirror.py 5 Dec 2002 02:37:23 -0000 1.16 --- ftpmirror.py 5 Dec 2002 02:43:14 -0000 1.17 *************** *** 56,59 **** --- 56,60 ---- if ':' in host: host, port = host.split(':', 1) + port = int(port) try: auth = netrc.netrc().authenticators(host) *************** *** 82,86 **** # f = ftplib.FTP() ! if verbose: print 'Connecting to %s...' % `host` f.connect(host,port) if not nologin: --- 83,88 ---- # f = ftplib.FTP() ! if verbose: print "Connecting to '%s%s'..." % (host, ! (port and ":%d"%port or "")) f.connect(host,port) if not nologin: From montanaro@users.sourceforge.net Thu Dec 5 02:58:38 2002 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Wed, 04 Dec 2002 18:58:38 -0800 Subject: [Python-checkins] python/dist/src/Tools/scripts setup.py,NONE,1.1 Message-ID: Update of /cvsroot/python/python/dist/src/Tools/scripts In directory sc8-pr-cvs1:/tmp/cvs-serv26341 Added Files: setup.py Log Message: simple setup.py to install some interesting scripts in $(prefix)/bin. --- NEW FILE: setup.py --- from distutils.core import setup setup( scripts=[ 'byteyears.py', 'checkpyc.py', 'copytime.py', 'crlf.py', 'dutree.py', 'ftpmirror.py', 'h2py.py', 'lfcr.py', '../../Lib/tabnanny.py', 'untabify.py', ], ) From tim_one@users.sourceforge.net Thu Dec 5 04:47:18 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 04 Dec 2002 20:47:18 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.c,1.40,1.41 doc.txt,1.8,1.9 obj_date.c,1.23,1.24 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv20378 Modified Files: datetime.c doc.txt obj_date.c Log Message: date_isoformat() was essentially identical to date_str(), so got rid of the former. Noted in the docs that they do the same thing. Added XXX comment pointing out an odd asymmetry between date_add() and date_subtract(): the latter can return a datetime object, but the former never can. Is it intended that adding a date to a timedelta with a non-zero non-days member produce a datetime instead of a date? If so, date_add() needs reworking; but if not, data_subtract() needs reworking. Got a start on implementing the sundry .strftime() methods. Index: datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.c,v retrieving revision 1.40 retrieving revision 1.41 diff -C2 -d -r1.40 -r1.41 *** datetime.c 4 Dec 2002 05:08:14 -0000 1.40 --- datetime.c 5 Dec 2002 04:47:16 -0000 1.41 *************** *** 333,336 **** --- 333,371 ---- } + /* I sure don't want to reproduce the strftime code from the time module, + * so this imports the module and calls it. Slow! + */ + static PyObject * + format_strftime(PyObject *format, PyObject *tuple) + { + PyObject *time; + PyObject *time_strftime; + PyObject *result; + + assert(PyTuple_Size(tuple) == 9); + + if (! PyString_Check(format)) { + PyErr_Format(PyExc_TypeError, + "strftime requires a string format, not " + "type '%s'", format->ob_type->tp_name); + return NULL; + } + + time = PyImport_ImportModule("time"); + if (time == NULL) + return NULL; + + time_strftime = PyObject_GetAttrString(time, "strftime"); + Py_DECREF(time); + if (time_strftime == NULL) + return NULL; + + result = PyObject_CallFunction(time_strftime, "OO", + format, + tuple); + Py_DECREF(time_strftime); + return result; + } + static char * isoformat_date(PyDateTime_Date *dt, char buffer[], int bufflen) Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** doc.txt 5 Dec 2002 01:56:50 -0000 1.8 --- doc.txt 5 Dec 2002 04:47:16 -0000 1.9 *************** *** 291,294 **** --- 291,295 ---- 'YYYY-MM-DD'. For example, date(2002, 12, 4).isoformat() == '2002-12-04'. + str(d) is equivalent to d.isoformat(). - ctime() Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.23 retrieving revision 1.24 diff -C2 -d -r1.23 -r1.24 *** obj_date.c 5 Dec 2002 01:39:39 -0000 1.23 --- obj_date.c 5 Dec 2002 04:47:16 -0000 1.24 *************** *** 313,326 **** static PyObject * - date_isoformat(PyDateTime_Date *self, PyObject *args, PyObject *kw) - { - char buffer[128]; - - isoformat_date(self, buffer, sizeof(buffer)); - - return PyString_FromString(buffer); - } - - static PyObject * date_isoweekday(PyDateTime_Date *self) { --- 313,316 ---- *************** *** 362,365 **** --- 352,356 ---- } + /* XXX This is much more complicated than date_add. Why? */ static PyObject * date_subtract(PyObject *left, PyObject *right) *************** *** 509,528 **** /* Instance methods: */ ! {"ctime", (PyCFunction)date_ctime, METH_NOARGS, "Return ctime() style string."}, ! {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS, "Return time tuple, compatible with time.localtime()."}, ! {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS, "Return a 3-tuple containing ISO year, week number, and weekday.\n\n" "The first ISO week of the year is the (Mon-Sun) week containing the\n" "year's first Thursday; everything else derives from that."}, ! {"isoformat", (PyCFunction)date_isoformat, METH_KEYWORDS, "Return string in ISO 8601 format, YYYY-MM-DD."}, ! {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS, "Return the day of the week represented by the date.\n" "Monday == 1 ... Sunday == 7"}, ! {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS, "Return proleptic Gregorian ordinal. January 1 of year 1 is day 1."}, ! {"weekday", (PyCFunction)date_weekday, METH_NOARGS, "Return the day of the week represented by the date.\n" "Monday == 0 ... Sunday == 6"}, --- 500,519 ---- /* Instance methods: */ ! {"ctime", (PyCFunction)date_ctime, METH_NOARGS, "Return ctime() style string."}, ! {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS, "Return time tuple, compatible with time.localtime()."}, ! {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS, "Return a 3-tuple containing ISO year, week number, and weekday.\n\n" "The first ISO week of the year is the (Mon-Sun) week containing the\n" "year's first Thursday; everything else derives from that."}, ! {"isoformat", (PyCFunction)date_str, METH_NOARGS, "Return string in ISO 8601 format, YYYY-MM-DD."}, ! {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS, "Return the day of the week represented by the date.\n" "Monday == 1 ... Sunday == 7"}, ! {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS, "Return proleptic Gregorian ordinal. January 1 of year 1 is day 1."}, ! {"weekday", (PyCFunction)date_weekday, METH_NOARGS, "Return the day of the week represented by the date.\n" "Monday == 0 ... Sunday == 6"}, From tim_one@users.sourceforge.net Thu Dec 5 04:49:44 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 04 Dec 2002 20:49:44 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_date.c,1.24,1.25 obj_datetime.c,1.17,1.18 obj_delta.c,1.21,1.22 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv21648 Modified Files: obj_date.c obj_datetime.c obj_delta.c Log Message: Got rid of the filename comments at the tops of these files. They were all wrong when I started this, and one was still wrong. Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.24 retrieving revision 1.25 diff -C2 -d -r1.24 -r1.25 *** obj_date.c 5 Dec 2002 04:47:16 -0000 1.24 --- obj_date.c 5 Dec 2002 04:49:42 -0000 1.25 *************** *** 1,4 **** ! /* imp_date.c ! * * PyDateTime_Date implementation. */ --- 1,3 ---- ! /* * PyDateTime_Date implementation. */ Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.17 retrieving revision 1.18 diff -C2 -d -r1.17 -r1.18 *** obj_datetime.c 5 Dec 2002 01:53:25 -0000 1.17 --- obj_datetime.c 5 Dec 2002 04:49:42 -0000 1.18 *************** *** 1,4 **** ! /* obj_datetime.c ! * * PyDateTime_DateTime implementation. */ --- 1,3 ---- ! /* * PyDateTime_DateTime implementation. */ Index: obj_delta.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_delta.c,v retrieving revision 1.21 retrieving revision 1.22 diff -C2 -d -r1.21 -r1.22 *** obj_delta.c 4 Dec 2002 05:08:14 -0000 1.21 --- obj_delta.c 5 Dec 2002 04:49:42 -0000 1.22 *************** *** 1,4 **** ! /* obj_delta.c ! * * PyDateTime_Delta implementation. */ --- 1,3 ---- ! /* * PyDateTime_Delta implementation. */ From tim_one@users.sourceforge.net Thu Dec 5 05:04:12 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 04 Dec 2002 21:04:12 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.c,1.41,1.42 doc.txt,1.9,1.10 obj_date.c,1.25,1.26 test_both.py,1.35,1.36 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv25346 Modified Files: datetime.c doc.txt obj_date.c test_both.py Log Message: Implemented, documented, and added a test for date.strftime(). Index: datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.c,v retrieving revision 1.41 retrieving revision 1.42 diff -C2 -d -r1.41 -r1.42 *** datetime.c 5 Dec 2002 04:47:16 -0000 1.41 --- datetime.c 5 Dec 2002 05:04:09 -0000 1.42 *************** *** 345,355 **** assert(PyTuple_Size(tuple) == 9); - if (! PyString_Check(format)) { - PyErr_Format(PyExc_TypeError, - "strftime requires a string format, not " - "type '%s'", format->ob_type->tp_name); - return NULL; - } - time = PyImport_ImportModule("time"); if (time == NULL) --- 345,348 ---- *************** *** 361,367 **** return NULL; ! result = PyObject_CallFunction(time_strftime, "OO", ! format, ! tuple); Py_DECREF(time_strftime); return result; --- 354,358 ---- return NULL; ! result = PyObject_CallFunction(time_strftime, "OO", format, tuple); Py_DECREF(time_strftime); return result; Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** doc.txt 5 Dec 2002 04:47:16 -0000 1.9 --- doc.txt 5 Dec 2002 05:04:09 -0000 1.10 *************** *** 299,304 **** - strftime(format) ! XXX And the C implementation doesn't have this yet either. ! XXX And there are no tests for it. --- 299,305 ---- - strftime(format) ! Return a string representing the date, controlled by an explicit ! format string. d.strftime(f) is the same as ! time.strftime(f, d.timetuple()). Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.25 retrieving revision 1.26 diff -C2 -d -r1.25 -r1.26 *** obj_date.c 5 Dec 2002 04:49:42 -0000 1.25 --- obj_date.c 5 Dec 2002 05:04:09 -0000 1.26 *************** *** 351,354 **** --- 351,367 ---- } + static PyObject * + date_strftime(PyDateTime_Date *self, PyObject *format) + { + PyObject *result; + PyObject *tuple = date_timetuple(self); + + if (tuple == NULL) + return NULL; + result = format_strftime(format, tuple); + Py_DECREF(tuple); + return result; + } + /* XXX This is much more complicated than date_add. Why? */ static PyObject * *************** *** 492,524 **** --- 505,552 ---- METH_CLASS, "timestamp -> local date from a POSIX timestamp (like time.time())."}, + {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS | METH_CLASS, "int -> date corresponding to a proleptic Gregorian ordinal."}, + {"today", (PyCFunction)date_today, METH_O | METH_CLASS, "Construct local date corresponing to current day."}, /* Instance methods: */ + {"ctime", (PyCFunction)date_ctime, METH_NOARGS, "Return ctime() style string."}, + + {"strftime", (PyCFunction)date_strftime, METH_O, + "format -> strftime() style string."}, + {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS, "Return time tuple, compatible with time.localtime()."}, + {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS, "Return a 3-tuple containing ISO year, week number, and weekday.\n\n" "The first ISO week of the year is the (Mon-Sun) week containing the\n" "year's first Thursday; everything else derives from that."}, + {"isoformat", (PyCFunction)date_str, METH_NOARGS, "Return string in ISO 8601 format, YYYY-MM-DD."}, + {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS, "Return the day of the week represented by the date.\n" "Monday == 1 ... Sunday == 7"}, + {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS, "Return proleptic Gregorian ordinal. January 1 of year 1 is day 1."}, + {"weekday", (PyCFunction)date_weekday, METH_NOARGS, "Return the day of the week represented by the date.\n" "Monday == 0 ... Sunday == 6"}, + {"__setstate__", (PyCFunction)date_setstate, METH_O, PyDoc_STR("__setstate__(state)")}, + {"__getstate__", (PyCFunction)date_getstate, METH_NOARGS, PyDoc_STR("__getstate__() -> state")}, + {NULL, NULL} }; Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.35 retrieving revision 1.36 diff -C2 -d -r1.35 -r1.36 *** test_both.py 4 Dec 2002 23:08:47 -0000 1.35 --- test_both.py 5 Dec 2002 05:04:09 -0000 1.36 *************** *** 572,575 **** --- 572,583 ---- self.assertEqual(t.ctime(), "Sat Mar 2 00:00:00 2002") + def test_strftime(self): + t = self.theclass(2005, 3, 2) + self.assertEqual(t.strftime("m:%m d:%d y:%y"), "m:03 d:02 y:05") + + self.assertRaises(TypeError, t.strftime) # needs an arg + self.assertRaises(TypeError, t.strftime, "one", "two") # too many args + self.assertRaises(TypeError, t.strftime, 42) # arg wrong type + def test_resolution_info(self): self.assert_(isinstance(self.theclass.min, self.theclass)) From jlt63@users.sourceforge.net Thu Dec 5 15:18:20 2002 From: jlt63@users.sourceforge.net (jlt63@users.sourceforge.net) Date: Thu, 05 Dec 2002 07:18:20 -0800 Subject: [Python-checkins] python/dist/src/Lib/test regrtest.py,1.110,1.111 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv21244 Modified Files: regrtest.py Log Message: Patch #551977: Regression exceptions for cygwin This patch updates regrtest.py to understand which tests are normally skipped under Cygwin. The list of tests was verified with the Cygwin Python maintainer. Index: regrtest.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/regrtest.py,v retrieving revision 1.110 retrieving revision 1.111 diff -C2 -d -r1.110 -r1.111 *** regrtest.py 4 Dec 2002 03:26:57 -0000 1.110 --- regrtest.py 5 Dec 2002 15:18:15 -0000 1.111 *************** *** 853,856 **** --- 853,878 ---- test_winsound """, + 'cygwin': + """ + test_al + test_cd + test_cl + test_curses + test_dbm + test_email_codecs + test_gl + test_imgfile + test_largefile + test_linuxaudiodev + test_locale + test_mpz + test_nis + test_socket_ssl + test_socketserver + test_sunaudiodev + test_unicode_file + test_winreg + test_winsound + """, } From tim_one@users.sourceforge.net Thu Dec 5 17:07:23 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 05 Dec 2002 09:07:23 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.py,1.75,1.76 obj_date.c,1.26,1.27 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv3763 Modified Files: datetime.py obj_date.c Log Message: No semantic change. Rearranged some code and changed comments, trying to sort out what the intent of date +/- timedelta is. The Python and C implementations disagree on whether this should or should not ever return a datetime. Index: datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.py,v retrieving revision 1.75 retrieving revision 1.76 diff -C2 -d -r1.75 -r1.76 *** datetime.py 5 Dec 2002 01:39:39 -0000 1.75 --- datetime.py 5 Dec 2002 17:07:20 -0000 1.76 *************** *** 636,646 **** __radd__ = __add__ timedelta_class = timedelta # Allows a subclass to override def __sub__(self, other): ! """Subtract two dates, or a date and a timedelta. ! ! An int/long/float argument is also allowed, interpreted as seconds. ! """ if isinstance(other, timedelta): return self + -other --- 636,647 ---- __radd__ = __add__ + # XXX What is timedelta_class for? If a subclass wants to redefine + # XXX subtraction, it should redefine subtraction. + # XXX The C implementation has nothing like this, and there's + # XXX no test for it. timedelta_class = timedelta # Allows a subclass to override def __sub__(self, other): ! """Subtract two dates, or a date and a timedelta.""" if isinstance(other, timedelta): return self + -other *************** *** 651,659 **** return NotImplemented - # Day-of-the-week and week-of-the-year, according to ISO - def weekday(self): "Return day of the week, where Monday == 0 ... Sunday == 6." return (self.toordinal() + 6) % 7 def isoweekday(self): --- 652,660 ---- return NotImplemented def weekday(self): "Return day of the week, where Monday == 0 ... Sunday == 6." return (self.toordinal() + 6) % 7 + + # Day-of-the-week and week-of-the-year, according to ISO def isoweekday(self): Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.26 retrieving revision 1.27 diff -C2 -d -r1.26 -r1.27 *** obj_date.c 5 Dec 2002 05:04:09 -0000 1.26 --- obj_date.c 5 Dec 2002 17:07:20 -0000 1.27 *************** *** 29,35 **** datetime_subtract(PyObject *left, PyObject *right); - /* date(2009, 12, 28) + timedelta(4) == 2010-01-01 (2010, 1, -2) - expected (2009, 53, 5) - */ static PyObject * add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta) --- 29,32 ---- *************** *** 94,97 **** --- 91,159 ---- } + static PyObject * + date_subtract(PyObject *left, PyObject *right) + { + PyTypeObject *left_type = left->ob_type; + PyTypeObject *right_type = right->ob_type; + + if (PyType_IsSubtype(left_type, &PyDateTime_DateTimeType) + || PyType_IsSubtype(right_type, &PyDateTime_DateTimeType)) { + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + } + if (PyType_IsSubtype(left_type, &PyDateTime_DateType)) { + if (PyType_IsSubtype(right_type, &PyDateTime_DateType)) { + /* date - date */ + long left_ord = ymd_to_ord(GET_YEAR(left), + GET_MONTH(left), + GET_DAY(left)); + long right_ord = ymd_to_ord(GET_YEAR(right), + GET_MONTH(right), + GET_DAY(right)); + return new_delta(left_ord - right_ord, 0, 0, 0); + } + if (PyType_IsSubtype(right_type, &PyDateTime_DeltaType)) { + PyObject *result = NULL; + if (GET_TD_SECONDS(right) != 0 + || GET_TD_MICROSECONDS(right) != 0) { + /* need to convert to datetime + delta */ + PyObject *dt = new_datetime(GET_YEAR(left), + GET_MONTH(left), + GET_DAY(left), + 0, 0, 0, 0); + if (dt != NULL) { + result = datetime_subtract(dt, right); + Py_DECREF(dt); + } + } + else if (GET_TD_DAYS(right) == 0) { + /* date - timedelta(0) */ + Py_INCREF(left); + result = left; + } + else { + long year, month, day; + long ord = ymd_to_ord(GET_YEAR(left), + GET_MONTH(left), + GET_DAY(left)); + ord -= GET_TD_DAYS(right); + if (ord < 1) + goto Overflow; + ord_to_ymd(ord, &year, &month, &day); + if (year < MINYEAR || year > MAXYEAR) + goto Overflow; + result = new_date(year, month, day); + } + return result; + } + } + Py_INCREF(Py_NotImplemented); + return Py_NotImplemented; + + Overflow: + PyErr_SetString(PyExc_OverflowError, "date subtraction"); + return NULL; + } + /* 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 *************** *** 362,431 **** Py_DECREF(tuple); return result; - } - - /* XXX This is much more complicated than date_add. Why? */ - static PyObject * - date_subtract(PyObject *left, PyObject *right) - { - PyTypeObject *left_type = left->ob_type; - PyTypeObject *right_type = right->ob_type; - - if (PyType_IsSubtype(left_type, &PyDateTime_DateTimeType) - || PyType_IsSubtype(right_type, &PyDateTime_DateTimeType)) { - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - } - if (PyType_IsSubtype(left_type, &PyDateTime_DateType)) { - if (PyType_IsSubtype(right_type, &PyDateTime_DateType)) { - /* date - date */ - long left_ord = ymd_to_ord(GET_YEAR(left), - GET_MONTH(left), - GET_DAY(left)); - long right_ord = ymd_to_ord(GET_YEAR(right), - GET_MONTH(right), - GET_DAY(right)); - return new_delta(left_ord - right_ord, 0, 0, 0); - } - if (PyType_IsSubtype(right_type, &PyDateTime_DeltaType)) { - PyObject *result = NULL; - if (GET_TD_SECONDS(right) != 0 - || GET_TD_MICROSECONDS(right) != 0) { - /* need to convert to datetime + delta */ - PyObject *dt = new_datetime(GET_YEAR(left), - GET_MONTH(left), - GET_DAY(left), - 0, 0, 0, 0); - if (dt != NULL) { - result = datetime_subtract(dt, right); - Py_DECREF(dt); - } - } - else if (GET_TD_DAYS(right) == 0) { - /* date - timedelta(0) */ - Py_INCREF(left); - result = left; - } - else { - long year, month, day; - long ord = ymd_to_ord(GET_YEAR(left), - GET_MONTH(left), - GET_DAY(left)); - ord -= GET_TD_DAYS(right); - if (ord < 1) - goto Overflow; - ord_to_ymd(ord, &year, &month, &day); - if (year < MINYEAR || year > MAXYEAR) - goto Overflow; - result = new_date(year, month, day); - } - return result; - } - } - Py_INCREF(Py_NotImplemented); - return Py_NotImplemented; - - Overflow: - PyErr_SetString(PyExc_OverflowError, "date subtraction"); - return NULL; } --- 424,427 ---- From tim_one@users.sourceforge.net Thu Dec 5 17:11:54 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 05 Dec 2002 09:11:54 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime doc.txt,1.10,1.11 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv4656 Modified Files: doc.txt Log Message: Documented what the Python implementation actually does for date +/- timedelta. The C code doesn't yet match, and these behaviors aren't yet tested. The Python implementation also has a funky class attribute, date.timedelta_class, which is used to construct the result of date-date; it's unclear what the point is, the C implementation doesn't have this, and it's not tested. Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** doc.txt 5 Dec 2002 05:04:09 -0000 1.10 --- doc.txt 5 Dec 2002 17:11:52 -0000 1.11 *************** *** 214,221 **** timedelta + date1 -> date2 date2 is timedelta.days days removed from the date1, moving forward ! in time if timedelta.days > 0, and date2 - date1 == timedelta.days ! after. timedelta.seconds and timedelta.microseconds are ignored. ! OverflowError is raised if date2.year would be smaller than MINYEAR ! or larger than MAXYEAR. - date1 - timedelta -> date2 --- 214,221 ---- timedelta + date1 -> date2 date2 is timedelta.days days removed from the date1, moving forward ! in time if timedelta.days > 0, or backward if timedetla.days < 0. ! date2 - date1 == timedelta.days after. timedelta.seconds and ! timedelta.microseconds are ignored. OverflowError is raised if ! date2.year would be smaller than MINYEAR or larger than MAXYEAR. - date1 - timedelta -> date2 *************** *** 223,227 **** isn't quite equivalent to date1 + (-timedelta), because -timedelta in isolation can overflow in cases where date1 - timedelta does ! not. - date1 - date2 -> timedelta --- 223,227 ---- isn't quite equivalent to date1 + (-timedelta), because -timedelta in isolation can overflow in cases where date1 - timedelta does ! not. timedelta.seconds and timedelta.microseconds are ignored. - date1 - date2 -> timedelta From tim_one@users.sourceforge.net Thu Dec 5 17:14:54 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 05 Dec 2002 09:14:54 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.py,1.76,1.77 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv7015 Modified Files: datetime.py Log Message: Removed the date.timedelta_class class attribute. If somebody really wanted this, they should have done at least one of {document it, test it, put it in the C implementation too}. Index: datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.py,v retrieving revision 1.76 retrieving revision 1.77 diff -C2 -d -r1.76 -r1.77 *** datetime.py 5 Dec 2002 17:07:20 -0000 1.76 --- datetime.py 5 Dec 2002 17:14:52 -0000 1.77 *************** *** 636,645 **** __radd__ = __add__ - # XXX What is timedelta_class for? If a subclass wants to redefine - # XXX subtraction, it should redefine subtraction. - # XXX The C implementation has nothing like this, and there's - # XXX no test for it. - timedelta_class = timedelta # Allows a subclass to override - def __sub__(self, other): """Subtract two dates, or a date and a timedelta.""" --- 636,639 ---- *************** *** 649,653 **** days1 = self.toordinal() days2 = other.toordinal() ! return self.timedelta_class(days1 - days2) return NotImplemented --- 643,647 ---- days1 = self.toordinal() days2 = other.toordinal() ! return timedelta(days1 - days2) return NotImplemented *************** *** 1220,1227 **** (other.__minute) * 60 + other.__hour * 3600) ! return self.timedelta_class( ! days1 - days2, ! secs1 - secs2, ! self.__microsecond - other.__microsecond) return NotImplemented --- 1214,1220 ---- (other.__minute) * 60 + other.__hour * 3600) ! return timedelta(days1 - days2, ! secs1 - secs2, ! self.__microsecond - other.__microsecond) return NotImplemented From tim_one@users.sourceforge.net Thu Dec 5 17:20:31 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 05 Dec 2002 09:20:31 -0800 Subject: [Python-checkins] python/dist/src/Lib/test regrtest.py,1.111,1.112 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv9491/python/Lib/test Modified Files: regrtest.py Log Message: Add a Cygwin skip mentioned by Jason Tishler. Index: regrtest.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/regrtest.py,v retrieving revision 1.111 retrieving revision 1.112 diff -C2 -d -r1.111 -r1.112 *** regrtest.py 5 Dec 2002 15:18:15 -0000 1.111 --- regrtest.py 5 Dec 2002 17:20:25 -0000 1.112 *************** *** 856,859 **** --- 856,860 ---- """ test_al + test_bsddb3 test_cd test_cl *************** *** 868,872 **** test_mpz test_nis - test_socket_ssl test_socketserver test_sunaudiodev --- 869,872 ---- From tim_one@users.sourceforge.net Thu Dec 5 19:03:21 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 05 Dec 2002 11:03:21 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_date.c,1.27,1.28 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv14072 Modified Files: obj_date.c Log Message: Changed the C implementations of date + timedelta timedelta + date date - timedelta to match the Python implementations (the docs were already changed to match). Despite the major simplification of the code, no tests failed as a result. This says, in part, that the tests weren't testing enough. I'll add more tests next. Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.27 retrieving revision 1.28 diff -C2 -d -r1.27 -r1.28 *** obj_date.c 5 Dec 2002 17:07:20 -0000 1.27 --- obj_date.c 5 Dec 2002 19:03:17 -0000 1.28 *************** *** 23,62 **** } static PyObject * ! datetime_add(PyObject *left, PyObject *right); ! ! static PyObject * ! datetime_subtract(PyObject *left, PyObject *right); ! ! static PyObject * ! add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta) { ! PyObject *result; ! /* delta + date */ ! if (GET_TD_SECONDS(delta) != 0 ! || GET_TD_MICROSECONDS(delta) != 0) { ! /* Convert to datetime and pass it off. */ ! PyObject *dt = new_datetime(GET_YEAR(date), GET_MONTH(date), ! GET_DAY(date), 0, 0, 0, 0); ! if (dt == NULL) ! return NULL; ! result = datetime_add((PyObject *)delta, dt); ! Py_DECREF(dt); ! } ! else if (GET_TD_DAYS(delta) != 0) { ! /* There's actually something to do. */ ! long int year = GET_YEAR(date); ! long int month = GET_MONTH(date); ! long int day = GET_DAY(date) + GET_TD_DAYS(delta); ! if (normalize_date(&year, &month, &day) < 0) ! result = NULL; ! else ! result = new_date(year, month, day); ! } ! else { ! /* The delta is timedelta(0), so return the original date. */ ! Py_INCREF(date); ! result = (PyObject *) date; ! } return result; } --- 23,41 ---- } + /* date + timedelta -> date. If arg negate is true, subtract the timedelta + * instead. + */ static PyObject * ! add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate) { ! PyObject *result = NULL; ! long year = GET_YEAR(date); ! long month = GET_MONTH(date); ! long deltadays = GET_TD_DAYS(delta); ! /* C-level overflow is impossible because |deltadays| < 1e9. */ ! long day = GET_DAY(date) + (negate ? -deltadays : deltadays); ! ! if (normalize_date(&year, &month, &day) >= 0) ! result = new_date(year, month, day); return result; } *************** *** 76,89 **** /* date + ??? */ if (PyType_IsSubtype(right_type, &PyDateTime_DeltaType)) return add_date_timedelta((PyDateTime_Date *) left, ! (PyDateTime_Delta *) right); } else { ! /* 'right' must be one of us, or we wouldn't have ! been called */ if (PyType_IsSubtype(left_type, &PyDateTime_DeltaType)) return add_date_timedelta((PyDateTime_Date *) right, ! (PyDateTime_Delta *) left); ! /* else fall through; we don't support it here */ } Py_INCREF(Py_NotImplemented); --- 55,72 ---- /* date + ??? */ if (PyType_IsSubtype(right_type, &PyDateTime_DeltaType)) + /* date + delta */ return add_date_timedelta((PyDateTime_Date *) left, ! (PyDateTime_Delta *) right, ! 0); } else { ! /* ??? + date ! * 'right' must be one of us, or we wouldn't have been called ! */ if (PyType_IsSubtype(left_type, &PyDateTime_DeltaType)) + /* delta + date */ return add_date_timedelta((PyDateTime_Date *) right, ! (PyDateTime_Delta *) left, ! 0); } Py_INCREF(Py_NotImplemented); *************** *** 114,157 **** } if (PyType_IsSubtype(right_type, &PyDateTime_DeltaType)) { ! PyObject *result = NULL; ! if (GET_TD_SECONDS(right) != 0 ! || GET_TD_MICROSECONDS(right) != 0) { ! /* need to convert to datetime + delta */ ! PyObject *dt = new_datetime(GET_YEAR(left), ! GET_MONTH(left), ! GET_DAY(left), ! 0, 0, 0, 0); ! if (dt != NULL) { ! result = datetime_subtract(dt, right); ! Py_DECREF(dt); ! } ! } ! else if (GET_TD_DAYS(right) == 0) { ! /* date - timedelta(0) */ ! Py_INCREF(left); ! result = left; ! } ! else { ! long year, month, day; ! long ord = ymd_to_ord(GET_YEAR(left), ! GET_MONTH(left), ! GET_DAY(left)); ! ord -= GET_TD_DAYS(right); ! if (ord < 1) ! goto Overflow; ! ord_to_ymd(ord, &year, &month, &day); ! if (year < MINYEAR || year > MAXYEAR) ! goto Overflow; ! result = new_date(year, month, day); ! } ! return result; } } Py_INCREF(Py_NotImplemented); return Py_NotImplemented; - - Overflow: - PyErr_SetString(PyExc_OverflowError, "date subtraction"); - return NULL; } --- 97,108 ---- } if (PyType_IsSubtype(right_type, &PyDateTime_DeltaType)) { ! /* date - delta */ ! return add_date_timedelta((PyDateTime_Date *) left, ! (PyDateTime_Delta *) right, ! 1); } } Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } From tim_one@users.sourceforge.net Thu Dec 5 19:45:09 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 05 Dec 2002 11:45:09 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.py,1.77,1.78 test_both.py,1.36,1.37 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv32415 Modified Files: datetime.py test_both.py Log Message: Added more tests of addition for dates, datetimes and timedeltas. This uncovered an endcase glitch in the Python date.__sub__, which got repaired. Index: datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.py,v retrieving revision 1.77 retrieving revision 1.78 diff -C2 -d -r1.77 -r1.78 *** datetime.py 5 Dec 2002 17:14:52 -0000 1.77 --- datetime.py 5 Dec 2002 19:45:03 -0000 1.78 *************** *** 409,414 **** self.__seconds + other.__seconds, self.__microseconds + other.__microseconds) ! raise TypeError ! # XXX Should be 'return NotImplemented', but there's a bug in 2.2... __radd__ = __add__ --- 409,413 ---- self.__seconds + other.__seconds, self.__microseconds + other.__microseconds) ! return NotImplemented __radd__ = __add__ *************** *** 639,643 **** """Subtract two dates, or a date and a timedelta.""" if isinstance(other, timedelta): ! return self + -other if isinstance(other, date): days1 = self.toordinal() --- 638,642 ---- """Subtract two dates, or a date and a timedelta.""" if isinstance(other, timedelta): ! return self + timedelta(-other.days) if isinstance(other, date): days1 = self.toordinal() Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.36 retrieving revision 1.37 diff -C2 -d -r1.36 -r1.37 *** test_both.py 5 Dec 2002 05:04:09 -0000 1.36 --- test_both.py 5 Dec 2002 19:45:04 -0000 1.37 *************** *** 297,301 **** --- 297,336 ---- # date tests + class TestDateOnly(unittest.TestCase): + # Tests here won't pass if also run on datetime objects, so don't + # subclass this to test datetimes too. + + def test_delta_non_days_ignored(self): + dt = date(2000, 1, 2) + delta = timedelta(days=1, hours=2, minutes=3, seconds=4, + microseconds=5) + days = timedelta(delta.days) + self.assertEqual(days, timedelta(1)) + + dt2 = dt + delta + self.assertEqual(dt2, dt + days) + + dt2 = delta + dt + self.assertEqual(dt2, dt + days) + + dt2 = dt - delta + self.assertEqual(dt2, dt - days) + + delta = -delta + days = timedelta(delta.days) + self.assertEqual(days, timedelta(-2)) + + dt2 = dt + delta + self.assertEqual(dt2, dt + days) + + dt2 = delta + dt + self.assertEqual(dt2, dt + days) + + dt2 = dt - delta + self.assertEqual(dt2, dt - days) + class TestDate(unittest.TestCase): + # Tests here should pass for both dates and datetimes, except for a + # few tests that TestDateTime overrides. theclass = date *************** *** 438,446 **** --- 473,484 ---- self.assertEqual(diff.seconds, 0) self.assertEqual(diff.microseconds, 0) + day = timedelta(1) week = timedelta(7) a = self.theclass(2002, 3, 2) self.assertEqual(a + day, self.theclass(2002, 3, 3)) + self.assertEqual(day + a, self.theclass(2002, 3, 3)) self.assertEqual(a - day, self.theclass(2002, 3, 1)) + self.assertEqual(-day + a, self.theclass(2002, 3, 1)) self.assertEqual(a + week, self.theclass(2002, 3, 9)) self.assertEqual(a - week, self.theclass(2002, 2, 23)) *************** *** 455,458 **** --- 493,497 ---- self.assertEqual(a - (a - week), week) self.assertEqual(a - (a - day), day) + # Add/sub ints, longs, floats should be illegal for i in 1, 1L, 1.0: *************** *** 462,465 **** --- 501,516 ---- self.assertRaises(TypeError, lambda: i-a) + # delta - date is senseless. + self.assertRaises(TypeError, lambda: day - a) + # mixing date and (delta or date) via * or // is senseless + self.assertRaises(TypeError, lambda: day * a) + self.assertRaises(TypeError, lambda: a * day) + self.assertRaises(TypeError, lambda: day // a) + self.assertRaises(TypeError, lambda: a // day) + self.assertRaises(TypeError, lambda: a * a) + self.assertRaises(TypeError, lambda: a // a) + # date + date is senseless + self.assertRaises(TypeError, lambda: a + a) + def test_overflow(self): tiny = self.theclass.resolution *************** *** 832,837 **** --- 883,890 ---- week = timedelta(7) self.assertEqual(a + hour, self.theclass(2002, 3, 2, 18, 6)) + self.assertEqual(hour + a, self.theclass(2002, 3, 2, 18, 6)) self.assertEqual(a + 10*hour, self.theclass(2002, 3, 3, 3, 6)) self.assertEqual(a - hour, self.theclass(2002, 3, 2, 16, 6)) + self.assertEqual(-hour + a, self.theclass(2002, 3, 2, 16, 6)) self.assertEqual(a - hour, a + -hour) self.assertEqual(a - 20*hour, self.theclass(2002, 3, 1, 21, 6)) *************** *** 873,876 **** --- 926,941 ---- self.assertRaises(TypeError, lambda: i-a) + # delta - datetime is senseless. + self.assertRaises(TypeError, lambda: day - a) + # mixing datetime and (delta or datetime) via * or // is senseless + self.assertRaises(TypeError, lambda: day * a) + self.assertRaises(TypeError, lambda: a * day) + self.assertRaises(TypeError, lambda: day // a) + self.assertRaises(TypeError, lambda: a // day) + self.assertRaises(TypeError, lambda: a * a) + self.assertRaises(TypeError, lambda: a // a) + # datetime + datetime is senseless + self.assertRaises(TypeError, lambda: a + a) + def test_pickling(self): import pickle, cPickle *************** *** 928,931 **** --- 993,997 ---- for klass in (TestModule, TestTimeDelta, + TestDateOnly, TestDate, TestDateTime, From jlt63@users.sourceforge.net Thu Dec 5 20:18:41 2002 From: jlt63@users.sourceforge.net (jlt63@users.sourceforge.net) Date: Thu, 05 Dec 2002 12:18:41 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_commands.py,1.8,1.9 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv15348 Modified Files: test_commands.py Log Message: Patch #648998: test_commands ACL patch Although motived by Cygwin, this patch will prevent test_commands from failing on Unixes that support ACLs. For example, the following is an excerpt from the Solaris ls manpage: ... -rwxrwxrwx+ 1 smith dev 10876 May 16 9:42 part2 The plus sign indicates that there is an ACL associated with the file. ... Index: test_commands.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_commands.py,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** test_commands.py 30 Sep 2002 15:44:41 -0000 1.8 --- test_commands.py 5 Dec 2002 20:18:39 -0000 1.9 *************** *** 46,49 **** --- 46,50 ---- # while the second one has a space in both names. pat = r'''d......... # It is a directory. + \+? # It may have ACLs. \s+\d+ # It has some number of links. [^/]* # Skip user, group, size, and date. From tim_one@users.sourceforge.net Thu Dec 5 20:28:43 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 05 Dec 2002 12:28:43 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime doc.txt,1.11,1.12 test_both.py,1.37,1.38 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv19855 Modified Files: doc.txt test_both.py Log Message: Added some timedelta tests for claims made in the docs that weren't otherwise being tested directly, + clarified the docs. Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** doc.txt 5 Dec 2002 17:11:52 -0000 1.11 --- doc.txt 5 Dec 2002 20:28:41 -0000 1.12 *************** *** 66,70 **** A week is converted to 7 days. ! and days, seconds and microseconds are normalized so that 0 <= microseconds < 1000000 --- 66,71 ---- A week is converted to 7 days. ! and days, seconds and microseconds are then normalized so that the ! representation is unique, with 0 <= microseconds < 1000000 *************** *** 73,80 **** If any argument is a float, and there are fractional microseconds, ! the value retained is rounded to the nearest microsecond. If the normalized value of days lies outside the indicated range, OverflowError is raised. Class attributes: --- 74,91 ---- If any argument is a float, and there are fractional microseconds, ! the fractional microseconds left over from all arguments are combined ! and their sum is rounded to the nearest microsecond. If the normalized value of days lies outside the indicated range, OverflowError is raised. + + Note that normalization of negative values may be surprising at first. + For example, + + >>> d = timedelta(microseconds=-1) + >>> (d.days, d.seconds, d.microseconds) + (-1, 86399, 999999) + >>> + Class attributes: Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.37 retrieving revision 1.38 diff -C2 -d -r1.37 -r1.38 *** test_both.py 5 Dec 2002 19:45:04 -0000 1.37 --- test_both.py 5 Dec 2002 20:28:41 -0000 1.38 *************** *** 294,297 **** --- 294,323 ---- self.assertRaises(OverflowError, lambda: -timedelta.max) + def test_microsecond_rounding(self): + td = timedelta + eq = self.assertEqual + + # Single-field rounding. + eq(td(milliseconds=0.4/1000), td(0)) # rounds to 0 + eq(td(milliseconds=-0.4/1000), td(0)) # rounds to 0 + eq(td(milliseconds=0.6/1000), td(microseconds=1)) + eq(td(milliseconds=-0.6/1000), td(microseconds=-1)) + + # Rounding due to contributions from more than one field. + us_per_hour = 3600e6 + us_per_day = us_per_hour * 24 + eq(td(days=.4/us_per_day), td(0)) + eq(td(hours=.2/us_per_hour), td(0)) + eq(td(days=.4/us_per_day, hours=.2/us_per_hour), td(microseconds=1)) + + eq(td(days=-.4/us_per_day), td(0)) + eq(td(hours=-.2/us_per_hour), td(0)) + eq(td(days=-.4/us_per_day, hours=-.2/us_per_hour), td(microseconds=-1)) + + def test_massive_normalization(self): + td = timedelta(microseconds=-1) + self.assertEqual((td.days, td.seconds, td.microseconds), + (-1, 24*3600-1, 999999)) + ############################################################################# # date tests From jlt63@users.sourceforge.net Thu Dec 5 20:31:56 2002 From: jlt63@users.sourceforge.net (jlt63@users.sourceforge.net) Date: Thu, 05 Dec 2002 12:31:56 -0800 Subject: [Python-checkins] python/dist/src/Modules bz2module.c,1.12,1.13 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv20998 Modified Files: bz2module.c Log Message: Patch #649060: Cygwin bz2module patch This patch enables the bz2 module to build cleanly under Cygwin. Index: bz2module.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/bz2module.c,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** bz2module.c 23 Nov 2002 09:16:19 -0000 1.12 --- bz2module.c 5 Dec 2002 20:31:53 -0000 1.13 *************** *** 1388,1393 **** 0, /*tp_call*/ 0, /*tp_str*/ ! PyObject_GenericGetAttr,/*tp_getattro*/ ! PyObject_GenericSetAttr,/*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/ --- 1388,1393 ---- 0, /*tp_call*/ 0, /*tp_str*/ ! 0, /*tp_getattro*/ ! 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/ *************** *** 1408,1414 **** 0, /*tp_dictoffset*/ (initproc)BZ2File_init, /*tp_init*/ ! PyType_GenericAlloc, /*tp_alloc*/ 0, /*tp_new*/ ! _PyObject_Del, /*tp_free*/ 0, /*tp_is_gc*/ }; --- 1408,1414 ---- 0, /*tp_dictoffset*/ (initproc)BZ2File_init, /*tp_init*/ ! 0, /*tp_alloc*/ 0, /*tp_new*/ ! 0, /*tp_free*/ 0, /*tp_is_gc*/ }; *************** *** 1653,1658 **** 0, /*tp_call*/ 0, /*tp_str*/ ! PyObject_GenericGetAttr,/*tp_getattro*/ ! PyObject_GenericSetAttr,/*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/ --- 1653,1658 ---- 0, /*tp_call*/ 0, /*tp_str*/ ! 0, /*tp_getattro*/ ! 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/ *************** *** 1673,1679 **** 0, /*tp_dictoffset*/ (initproc)BZ2Comp_init, /*tp_init*/ ! PyType_GenericAlloc, /*tp_alloc*/ ! PyType_GenericNew, /*tp_new*/ ! _PyObject_Del, /*tp_free*/ 0, /*tp_is_gc*/ }; --- 1673,1679 ---- 0, /*tp_dictoffset*/ (initproc)BZ2Comp_init, /*tp_init*/ ! 0, /*tp_alloc*/ ! 0, /*tp_new*/ ! 0, /*tp_free*/ 0, /*tp_is_gc*/ }; *************** *** 1870,1875 **** 0, /*tp_call*/ 0, /*tp_str*/ ! PyObject_GenericGetAttr,/*tp_getattro*/ ! PyObject_GenericSetAttr,/*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/ --- 1870,1875 ---- 0, /*tp_call*/ 0, /*tp_str*/ ! 0, /*tp_getattro*/ ! 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/ *************** *** 1890,1896 **** 0, /*tp_dictoffset*/ (initproc)BZ2Decomp_init, /*tp_init*/ ! PyType_GenericAlloc, /*tp_alloc*/ ! PyType_GenericNew, /*tp_new*/ ! _PyObject_Del, /*tp_free*/ 0, /*tp_is_gc*/ }; --- 1890,1896 ---- 0, /*tp_dictoffset*/ (initproc)BZ2Decomp_init, /*tp_init*/ ! 0, /*tp_alloc*/ ! 0, /*tp_new*/ ! 0, /*tp_free*/ 0, /*tp_is_gc*/ }; *************** *** 2090,2096 **** --- 2090,2111 ---- BZ2File_Type.tp_base = &PyFile_Type; BZ2File_Type.tp_new = PyFile_Type.tp_new; + BZ2File_Type.tp_getattro = PyObject_GenericGetAttr; + BZ2File_Type.tp_setattro = PyObject_GenericSetAttr; + BZ2File_Type.tp_alloc = PyType_GenericAlloc; + BZ2File_Type.tp_free = _PyObject_Del; BZ2Comp_Type.ob_type = &PyType_Type; + BZ2Comp_Type.tp_getattro = PyObject_GenericGetAttr; + BZ2Comp_Type.tp_setattro = PyObject_GenericSetAttr; + BZ2Comp_Type.tp_alloc = PyType_GenericAlloc; + BZ2Comp_Type.tp_new = PyType_GenericNew; + BZ2Comp_Type.tp_free = _PyObject_Del; + BZ2Decomp_Type.ob_type = &PyType_Type; + BZ2Decomp_Type.tp_getattro = PyObject_GenericGetAttr; + BZ2Decomp_Type.tp_setattro = PyObject_GenericSetAttr; + BZ2Decomp_Type.tp_alloc = PyType_GenericAlloc; + BZ2Decomp_Type.tp_new = PyType_GenericNew; + BZ2Decomp_Type.tp_free = _PyObject_Del; m = Py_InitModule3("bz2", bz2_methods, bz2__doc__); From montanaro@users.sourceforge.net Thu Dec 5 21:12:37 2002 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Thu, 05 Dec 2002 13:12:37 -0800 Subject: [Python-checkins] python/dist/src/Tools/scripts setup.py,1.1,1.2 Message-ID: Update of /cvsroot/python/python/dist/src/Tools/scripts In directory sc8-pr-cvs1:/tmp/cvs-serv7147 Modified Files: setup.py Log Message: add logmerge.py (pydoc is already installed) Index: setup.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Tools/scripts/setup.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** setup.py 5 Dec 2002 02:58:36 -0000 1.1 --- setup.py 5 Dec 2002 21:12:34 -0000 1.2 *************** *** 11,14 **** --- 11,15 ---- 'h2py.py', 'lfcr.py', + 'logmerge.py', '../../Lib/tabnanny.py', 'untabify.py', From tim_one@users.sourceforge.net Thu Dec 5 21:29:38 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 05 Dec 2002 13:29:38 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_date.c,1.28,1.29 obj_datetime.c,1.18,1.19 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv13210 Modified Files: obj_date.c obj_datetime.c Log Message: Moving on to datetime objects. Mostly mechanical edits to fold longs and increase uniformity. Noticed that date_nonzero() and datetime_nonzero() can never return false, since the year is constrained to be no smaller than 1. So replaced their guts with "return 1;". Some other simplications to the multiple ways of spelling "isoformat of a datetime". Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.28 retrieving revision 1.29 diff -C2 -d -r1.28 -r1.29 *** obj_date.c 5 Dec 2002 19:03:17 -0000 1.28 --- obj_date.c 5 Dec 2002 21:29:36 -0000 1.29 *************** *** 335,341 **** date_nonzero(PyDateTime_Date *self) { ! return (GET_YEAR(self) != 0 ! || GET_MONTH(self) != 0 ! || GET_DAY(self) != 0); } --- 335,340 ---- date_nonzero(PyDateTime_Date *self) { ! assert(GET_YEAR(self) >= 1); ! return 1; } Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** obj_datetime.c 5 Dec 2002 04:49:42 -0000 1.18 --- obj_datetime.c 5 Dec 2002 21:29:36 -0000 1.19 *************** *** 21,24 **** --- 21,27 ---- add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta) { + /* Note that the C-level additions can't overflow, because of + * invariant bounds on the member values. + */ long year = GET_YEAR(date); long month = GET_MONTH(date); *************** *** 40,43 **** --- 43,49 ---- sub_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta) { + /* Note that the C-level subtractions can't overflow, because of + * invariant bounds on the member values. + */ long year = GET_YEAR(date); long month = GET_MONTH(date); *************** *** 73,77 **** long seconds2 = (GET_HOUR(right) * 60 + GET_MINUTE(right)) * 60 + GET_SECOND(right); - long delta_us = GET_MICROSECOND(left) - GET_MICROSECOND(right); --- 79,82 ---- *************** *** 88,93 **** /* datetime + ??? */ if (PyType_IsSubtype(right_type, &PyDateTime_DeltaType)) ! return add_datetime_timedelta((PyDateTime_DateTime *) left, ! (PyDateTime_Delta *) right); } else if (PyType_IsSubtype(left_type, &PyDateTime_DeltaType)) { --- 93,100 ---- /* datetime + ??? */ if (PyType_IsSubtype(right_type, &PyDateTime_DeltaType)) ! /* datetime + delta */ ! return add_datetime_timedelta( ! (PyDateTime_DateTime *)left, ! (PyDateTime_Delta *)right); } else if (PyType_IsSubtype(left_type, &PyDateTime_DeltaType)) { *************** *** 116,120 **** } else if (PyType_IsSubtype(right_type, &PyDateTime_DeltaType)) { ! /* datetime - timedelta */ result = sub_datetime_timedelta( (PyDateTime_DateTime *)left, --- 123,127 ---- } else if (PyType_IsSubtype(right_type, &PyDateTime_DeltaType)) { ! /* datetime - delta */ result = sub_datetime_timedelta( (PyDateTime_DateTime *)left, *************** *** 234,258 **** static PyObject * datetime_repr(PyDateTime_DateTime *self) { ! char buffer[1028]; char *typename; typename = self->ob_type->tp_name; if (GET_MICROSECOND(self)) { ! PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d, %d, %d, %d, %d, %d)", typename, GET_YEAR(self), GET_MONTH(self), GET_DAY(self), ! GET_HOUR(self), GET_MINUTE(self), GET_SECOND(self), ! GET_MICROSECOND(self)); } else if (GET_SECOND(self)) { ! PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d, %d, %d, %d, %d)", typename, GET_YEAR(self), GET_MONTH(self), GET_DAY(self), ! GET_HOUR(self), GET_MINUTE(self), GET_SECOND(self)); } else { ! PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d, %d, %d, %d)", typename, GET_YEAR(self), GET_MONTH(self), GET_DAY(self), --- 241,301 ---- static PyObject * + datetime_hour(PyDateTime_DateTime *self, void *unused) + { + return PyInt_FromLong(GET_HOUR(self)); + } + + static PyObject * + datetime_minute(PyDateTime_DateTime *self, void *unused) + { + return PyInt_FromLong(GET_MINUTE(self)); + } + + static PyObject * + datetime_second(PyDateTime_DateTime *self, void *unused) + { + return PyInt_FromLong(GET_SECOND(self)); + } + + static PyObject * + datetime_microsecond(PyDateTime_DateTime *self, void *unused) + { + return PyInt_FromLong(GET_MICROSECOND(self)); + } + + static PyGetSetDef datetime_getset[] = { + {"hour", (getter)datetime_hour}, + {"minute", (getter)datetime_minute}, + {"second", (getter)datetime_second}, + {"microsecond", (getter)datetime_microsecond}, + {NULL} + }; + + static PyObject * datetime_repr(PyDateTime_DateTime *self) { ! char buffer[1000]; char *typename; typename = self->ob_type->tp_name; if (GET_MICROSECOND(self)) { ! PyOS_snprintf(buffer, sizeof(buffer), ! "%s(%d, %d, %d, %d, %d, %d, %d)", typename, GET_YEAR(self), GET_MONTH(self), GET_DAY(self), ! GET_HOUR(self), GET_MINUTE(self), ! GET_SECOND(self), GET_MICROSECOND(self)); } else if (GET_SECOND(self)) { ! PyOS_snprintf(buffer, sizeof(buffer), ! "%s(%d, %d, %d, %d, %d, %d)", typename, GET_YEAR(self), GET_MONTH(self), GET_DAY(self), ! GET_HOUR(self), GET_MINUTE(self), ! GET_SECOND(self)); } else { ! PyOS_snprintf(buffer, sizeof(buffer), ! "%s(%d, %d, %d, %d, %d)", typename, GET_YEAR(self), GET_MONTH(self), GET_DAY(self), *************** *** 263,267 **** static PyObject * ! datetime_str(PyDateTime_DateTime *self) { char buffer[128]; --- 306,310 ---- static PyObject * ! datetime_isoformat_helper(PyDateTime_DateTime *self, char sep) { char buffer[128]; *************** *** 269,273 **** cp = isoformat_date((PyDateTime_Date *)self, buffer, sizeof(buffer)); ! *cp++ = ' '; isoformat_time(self, cp, sizeof(buffer) - (cp - buffer)); --- 312,317 ---- cp = isoformat_date((PyDateTime_Date *)self, buffer, sizeof(buffer)); ! assert(cp != NULL); ! *cp++ = sep; isoformat_time(self, cp, sizeof(buffer) - (cp - buffer)); *************** *** 276,329 **** static PyObject * ! datetime_hour(PyDateTime_DateTime *self, void *unused) ! { ! return (PyInt_FromLong(GET_HOUR(self))); ! } ! ! static PyObject * ! datetime_minute(PyDateTime_DateTime *self, void *unused) ! { ! return (PyInt_FromLong(GET_MINUTE(self))); ! } ! ! static PyObject * ! datetime_second(PyDateTime_DateTime *self, void *unused) ! { ! return (PyInt_FromLong(GET_SECOND(self))); ! } ! ! static PyObject * ! datetime_microsecond(PyDateTime_DateTime *self, void *unused) { ! return (PyInt_FromLong(GET_MICROSECOND(self))); } - static PyGetSetDef datetime_getset[] = { - {"hour", (getter)datetime_hour}, - {"minute", (getter)datetime_minute}, - {"second", (getter)datetime_second}, - {"microsecond", (getter)datetime_microsecond}, - {NULL} - }; - static PyObject * datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw) { - char buffer[128]; char sep = 'T'; - char *cp; - static char *keywords[] = {"sep", NULL}; ! if (!PyArg_ParseTupleAndKeywords(args, kw, "|c:isoformat", keywords, &sep)) return NULL; ! ! cp = isoformat_date((PyDateTime_Date *)self, buffer, sizeof(buffer)); ! assert(cp != NULL); ! *cp++ = sep; ! isoformat_time(self, cp, sizeof(buffer) - (cp - buffer)); ! ! return PyString_FromString(buffer); } --- 320,339 ---- static PyObject * ! datetime_str(PyDateTime_DateTime *self) { ! return datetime_isoformat_helper(self, ' '); } static PyObject * datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw) { char sep = 'T'; static char *keywords[] = {"sep", NULL}; ! if (!PyArg_ParseTupleAndKeywords(args, kw, "|c:isoformat", keywords, ! &sep)) return NULL; ! return datetime_isoformat_helper(self, sep); } *************** *** 331,339 **** datetime_nonzero(PyDateTime_DateTime *self) { ! return (GET_MICROSECOND(self) != 0 ! || GET_SECOND(self) != 0 ! || GET_MINUTE(self) != 0 ! || GET_HOUR(self) != 0 ! || date_nonzero((PyDateTime_Date *) self) != 0); } --- 341,346 ---- datetime_nonzero(PyDateTime_DateTime *self) { ! assert(GET_YEAR(self) >= 1); ! return 1; } From mwh@users.sourceforge.net Thu Dec 5 21:32:34 2002 From: mwh@users.sourceforge.net (mwh@users.sourceforge.net) Date: Thu, 05 Dec 2002 13:32:34 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_types.py,1.42,1.43 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv15146/Lib/test Modified Files: test_types.py Log Message: The final tweaks before closing [ 633152 ] list slice ass ignores subtypes of list Allow arbitrary sequences on the RHS of extended slices. Index: test_types.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_types.py,v retrieving revision 1.42 retrieving revision 1.43 diff -C2 -d -r1.42 -r1.43 *** test_types.py 4 Dec 2002 07:32:25 -0000 1.42 --- test_types.py 5 Dec 2002 21:32:32 -0000 1.43 *************** *** 431,434 **** --- 431,438 ---- vereq(a, b) vereq(a, c) + a = range(10) + a[::2] = tuple(range(5)) + vereq(a, [0, 1, 1, 3, 2, 5, 3, 7, 4, 9]) + print '6.6 Mappings == Dictionaries' From mwh@users.sourceforge.net Thu Dec 5 21:32:34 2002 From: mwh@users.sourceforge.net (mwh@users.sourceforge.net) Date: Thu, 05 Dec 2002 13:32:34 -0800 Subject: [Python-checkins] python/dist/src/Objects listobject.c,2.141,2.142 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv15146/Objects Modified Files: listobject.c Log Message: The final tweaks before closing [ 633152 ] list slice ass ignores subtypes of list Allow arbitrary sequences on the RHS of extended slices. Index: listobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/listobject.c,v retrieving revision 2.141 retrieving revision 2.142 diff -C2 -d -r2.141 -r2.142 *** listobject.c 12 Nov 2002 22:08:10 -0000 2.141 --- listobject.c 5 Dec 2002 21:32:32 -0000 2.142 *************** *** 2239,2269 **** else { /* assign slice */ ! PyObject **garbage, *ins; int cur, i; ! if (!PyList_Check(value)) { ! PyErr_Format(PyExc_TypeError, ! "must assign list (not \"%.200s\") to slice", ! value->ob_type->tp_name); ! return -1; } ! if (PyList_GET_SIZE(value) != slicelength) { PyErr_Format(PyExc_ValueError, ! "attempt to assign list of size %d to extended slice of size %d", ! PyList_Size(value), slicelength); return -1; } ! if (!slicelength) return 0; - - /* protect against a[::-1] = a */ - if (self == (PyListObject*)value) { - value = list_slice((PyListObject*)value, 0, - PyList_GET_SIZE(value)); - } - else { - Py_INCREF(value); } --- 2239,2272 ---- else { /* assign slice */ ! PyObject **garbage, *ins, *seq; int cur, i; ! /* protect against a[::-1] = a */ ! if (self == (PyListObject*)value) { ! seq = list_slice((PyListObject*)value, 0, ! PyList_GET_SIZE(value)); ! } ! else { ! char msg[256]; ! PyOS_snprintf(msg, sizeof(msg), ! "must assign sequence (not \"%.200s\") to extended slice", ! value->ob_type->tp_name); ! seq = PySequence_Fast(value, msg); ! if (!seq) ! return -1; } ! if (PySequence_Fast_GET_SIZE(seq) != slicelength) { PyErr_Format(PyExc_ValueError, ! "attempt to assign sequence of size %d to extended slice of size %d", ! PySequence_Fast_GET_SIZE(seq), ! slicelength); ! Py_DECREF(seq); return -1; } ! if (!slicelength) { ! Py_DECREF(seq); return 0; } *************** *** 2275,2279 **** garbage[i] = PyList_GET_ITEM(self, cur); ! ins = PyList_GET_ITEM(value, i); Py_INCREF(ins); PyList_SET_ITEM(self, cur, ins); --- 2278,2282 ---- garbage[i] = PyList_GET_ITEM(self, cur); ! ins = PySequence_Fast_GET_ITEM(seq, i); Py_INCREF(ins); PyList_SET_ITEM(self, cur, ins); *************** *** 2285,2289 **** PyMem_FREE(garbage); ! Py_DECREF(value); return 0; --- 2288,2292 ---- PyMem_FREE(garbage); ! Py_DECREF(seq); return 0; From tim_one@users.sourceforge.net Thu Dec 5 23:16:01 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 05 Dec 2002 15:16:01 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime doc.txt,1.12,1.13 obj_datetime.c,1.19,1.20 test_both.py,1.38,1.39 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv22288 Modified Files: doc.txt obj_datetime.c test_both.py Log Message: Brute-forced datetime.today() and datetime.fromtimestamp() to work as intended. I hate this. I think what I really want is to figure out how, at the C level, to say "OK, I've got a type object. Now figure out what *it* calls the 'fromtimestamp' class method, and call that". Else, like now, I get goofy code duplication and a lack of extensibility. Also got a start on serious docs for datetime. Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** doc.txt 5 Dec 2002 20:28:41 -0000 1.12 --- doc.txt 5 Dec 2002 23:15:59 -0000 1.13 *************** *** 317,320 **** --- 317,495 ---- class datetime ============== + A datetime object is a single object containing all the information from + a date object and a time object. Like a date object, datetime assumes + the current Gregorian calendar extended in both directions; like a time + object, datetime assumes there are exact 3600*24 seconds in every day. + + Constructor: + + datetime(year, month, day, + hour=0, minute=0, second=0, microsecond=0) + + The year, month and day arguments are required. Arguments may be ints + or longs, in the following ranges: + + MINYEAR <= year <= MAXYEAR + 1 <= month <= 12 + 1 <= day <= number of days in the given month and year + 0 <= hour < 24 + 0 <= minute < 60 + 0 <= second < 60 + 0 <= microsecond < 1000000 + + If an argument outside those ranges is given, ValueError is raised. + + Other constructors (class methods): + + - today() + + Return the current local datetime. This is equivalent to + datetime.fromtimestamp(time.time()). + + - now() + + Return the current local datetime. This is like today(), but, if + possible, supplies more precision than can be gotten from going + through a time.time() timestamp. + XXX It currently doesn't. + + - fromtimestamp(timestamp) + + Return the local datetime corresponding to the POSIX timestamp, such as + is returned by time.time(). This may raise ValueError, if the + timestamp is out of the range of values supported by the platform C + localtime() function. It's common for this to be restricted to + years in 1970 through 2038. + + - fromordinal(ordinal) + + Return the date corresponding to the proleptic Gregorian ordinal, + where January 1 of year 1 has ordinal 1. ValueError is raised + unless 1 <= ordinal <= datetime.max.toordinal(). + + XXX THERE ARE A SLEW OF OTHER CONSTRUCTORS IN THE PYTHON IMPLEMENTATION + XXX THAT DON'T EXIST YET IN THE C IMPLEMENTATION. + + Class attributes: + + .min + The earliest representable datetime, + datetime(MINYEAR, 1, 1). + + .max + The latest representable datetime, + datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999). + + .resolution + The smallest possible difference between non-equal datetime + objects, timedelta(microseconds=1). + + Instance attributes (read-only): + + .year between MINYEAR and MAXYEAR inclusive + .month between 1 and 12 inclusive + .day between 1 and the number of days in the given month + of the given year + .hour in range(24) + .minute in range(60) + .second in range(60) + .microsecond in range(1000000) + + Supported operations: + + - datetime1 + timedelta -> datetime2 + timedelta + datetime1 -> datetime2 + datetime2 is a duration of timedelta removed from datetime1, moving + forward in time if timedelta.days > 0, or backward if + timedelta.days < 0. datetime2 - datetime1 == timedelta after. + OverflowError is raised if date2.year would be smaller than MINYEAR + or larger than MAXYEAR. + + XXX NOTHING BELOW THIS POINT HAS BEEN CHECKED, AND MUCH IS CERTAINLY + XXX WRONG (CUT & PASTE ERRORS MOSTLY) AND/OR MISIMPLEMENTED. + + - date1 - timedelta -> date2 + Computes the date2 such that date2 + timedelta == date1. This + isn't quite equivalent to date1 + (-timedelta), because -timedelta + in isolation can overflow in cases where date1 - timedelta does + not. timedelta.seconds and timedelta.microseconds are ignored. + + - date1 - date2 -> timedelta + This is exact, and cannot overflow. timedelta.seconds and + timedelta.microseconds are 0, and date2 + timedelta == date1 + after. + + - comparison of date to date, where date1 is considered less than + date2 when date1 precedes date2 in time. In other words, + date1 < date2 if and only if date1.toordinal() < date2.toordinal(). + + - hash, use as dict key + + - pickling + + Instance methods: + + - timetuple() + Return a 9-element tuple of the form returned by time.localtime(). + The hours, minutes and seconds are 0, and the DST flag is -1. + d.timetuple() is equivalent to + (d.year, d.month, d.day, + 0, 0, 0, # h, m, s + d.weekday(), # 0 is Monday + d.toordinal() - date(d.year, 1, 1).toordinal() + 1, # day of year + -1) + + - toordinal() + Return the proleptic Gregorian ordinal of the date, where January 1 + of year 1 has ordinal 1. For any date object d, + date.fromordinal(d.toordinal()) == d. + + - weekday() + Return the day of the week as an integer, where Monday is 0 and + Sunday is 6. For example, date(2002, 12, 4).weekday() == 2, a + Wednesday. + See also isoweekday(). + + - isoweekday() + Return the day of the week as an integer, where Monday is 1 and + Sunday is 7. For example, date(2002, 12, 4).isoweekday() == 3, a + Wednesday. + See also weekday() and isocalendar(). + + - isocalendar() + Return a 3-tuple, (ISO year, ISO week number, ISO weekday). + + The ISO calendar is a widely used variant of the Gregorian calendar. + See + for a good explanation. + + The ISO year consists of 52 or 53 full weeks, and where a week starts + on a Monday and ends on a Sunday. The first week of an ISO year is + the first (Gregorian) calendar week of a year containing a Thursday. + This is called week number 1, and the ISO year of that Thursday is + the same as its Gregorian year. + + For example, 2004 begins on a Thursday, so the first week of ISO + year 2004 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan + 2004, so that + + date(2003, 12, 29).isocalendar() == (2004, 1, 1) + date(2004, 1, 4).isocalendar() == (2004, 1, 7) + + - isoformat() + Return a string representing the date in ISO 8601 format, + 'YYYY-MM-DD'. For example, + date(2002, 12, 4).isoformat() == '2002-12-04'. + str(d) is equivalent to d.isoformat(). + + - ctime() + Return a string representing the date, for example + date(2002, 12, 4).ctime() == 'Wed Dec 4 00:00:00 2002'. + d.ctime() is equivalent to time.ctime(time.mktime(d.timetuple())). + + - strftime(format) + Return a string representing the date, controlled by an explicit + format string. d.strftime(f) is the same as + time.strftime(f, d.timetuple()). Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.19 retrieving revision 1.20 diff -C2 -d -r1.19 -r1.20 *** obj_datetime.c 5 Dec 2002 21:29:36 -0000 1.19 --- obj_datetime.c 5 Dec 2002 23:15:59 -0000 1.20 *************** *** 241,244 **** --- 241,337 ---- static PyObject * + datetime_local_from_time_t(PyObject *cls, time_t t) + { + struct tm *tm; + PyObject *result = NULL; + + tm = localtime(&t); + if (tm) + result = PyObject_CallFunction(cls, "llllll", + tm->tm_year + 1900, + tm->tm_mon + 1, + tm->tm_mday, + tm->tm_hour, + tm->tm_min, + tm->tm_sec); + else + PyErr_SetString(PyExc_ValueError, + "timestamp out of range for " + "platform localtime() function"); + return result; + } + + /* Return new datetime from given timestamp (Python timestamp -- a double). */ + static PyObject * + datetime_fromtimestamp(PyObject *self, PyObject *args) + { + PyObject *cls; + double timestamp; + PyObject *result = NULL; + + if (PyArg_ParseTuple(args, "Od:fromtimestamp", &cls, ×tamp)) + result = datetime_local_from_time_t(cls, (time_t)timestamp); + return result; + } + + static PyObject * + datetime_now(PyObject *self, PyObject *cls) + { + /* XXX MAJOR: This needs to get some notion of current time + * XXX to better than 1-second resolution. Doing this in a x- + * XXX platform way is mondo painful. Maybe floattime() from + * XXX timemodule.c is good enough? We're running out of bits + * XXX in a typical time_t, though, and gettimeofday() should do + * XXX better than floattime() -- but gettimeofday isn't portable. + */ + #if 0 + /* XXX need to create the instance by calling cls(y,mon,d,h,min,s,u) */ + struct timeval t; + struct tm *tm; + time_t timet; + + #ifdef GETTIMEOFDAY_NO_TZ + gettimeofday(&t); + #else /* !GETTIMEOFDAY_NO_TZ */ + gettimeofday(&t, (struct timezone *)NULL); + #endif /* !GETTIMEOFDAY_NO_TZ */ + timet = t.tv_sec; + tm = localtime(&timet); + + return PyObject_CallFunction(cls, "iiiiiil", + tm->tm_year + 1900, tm->tm_mon + 1, + tm->tm_mday, tm->tm_hour, tm->tm_min, + tm->tm_sec, t.tv_usec); + #else + /* XXX need to create the instance by calling cls(y,mon,d,h,min,s,u) */ + struct tm *tm; + time_t timet; + + time(&timet); + tm = localtime(&timet); + + return PyObject_CallFunction(cls, "llllll", + tm->tm_year + 1900, tm->tm_mon + 1, + tm->tm_mday, tm->tm_hour, tm->tm_min, + tm->tm_sec); + #endif + } + + static PyObject * + datetime_today(PyObject *self, PyObject *cls) + { + struct tm *tm; + time_t timet; + + time(&timet); + tm = localtime(&timet); + + return PyObject_CallFunction(cls, "llllll", + tm->tm_year + 1900, tm->tm_mon + 1, + tm->tm_mday, tm->tm_hour, + tm->tm_min, tm->tm_sec); + } + + static PyObject * datetime_hour(PyDateTime_DateTime *self, void *unused) { *************** *** 345,406 **** } - static PyObject * - datetime_now(PyObject *self, PyObject *cls) - { - /* XXX MAJOR: This needs to get some notion of current time - * XXX to better than 1-second resolution. Doing this in a x- - * XXX platform way is mondo painful. Maybe floattime() from - * XXX timemodule.c is good enough? We're running out of bits - * XXX in a typical time_t, though, and gettimeofday() should do - * XXX better than floattime() -- but gettimeofday isn't portable. - */ - #if 0 - /* XXX need to create the instance by calling cls(y,mon,d,h,min,s,u) */ - struct timeval t; - struct tm *tm; - time_t timet; - - #ifdef GETTIMEOFDAY_NO_TZ - gettimeofday(&t); - #else /* !GETTIMEOFDAY_NO_TZ */ - gettimeofday(&t, (struct timezone *)NULL); - #endif /* !GETTIMEOFDAY_NO_TZ */ - timet = t.tv_sec; - tm = localtime(&timet); - - return PyObject_CallFunction(cls, "iiiiiil", - tm->tm_year + 1900, tm->tm_mon + 1, - tm->tm_mday, tm->tm_hour, tm->tm_min, - tm->tm_sec, t.tv_usec); - #else - /* XXX need to create the instance by calling cls(y,mon,d,h,min,s,u) */ - struct tm *tm; - time_t timet; - - time(&timet); - tm = localtime(&timet); - - return PyObject_CallFunction(cls, "iiiiiil", - tm->tm_year + 1900, tm->tm_mon + 1, - tm->tm_mday, tm->tm_hour, tm->tm_min, - tm->tm_sec, 0); - #endif - } - - static PyObject * - datetime_today(PyObject *self, PyObject *cls) - { - /* XXX need to create the instance by calling cls(y,mon,d,h,min,s,u) */ - struct tm *tm; - time_t timet; - - time(&timet); - tm = localtime(&timet); - - return PyObject_CallFunction(cls, "iiiiiil", - tm->tm_year + 1900, tm->tm_mon + 1, - tm->tm_mday, 0, 0, 0, 0); - } - /* Pickle support. Quite a maze! */ static PyObject * --- 438,441 ---- *************** *** 463,478 **** --- 498,522 ---- {"now", (PyCFunction)datetime_now, METH_O | METH_CLASS, "Return a new datetime that represents the current time."}, + {"today", (PyCFunction)datetime_today, METH_O | METH_CLASS, "Return a new datetime that represents the current date."}, + {"fromtimestamp", (PyCFunction)datetime_fromtimestamp, METH_VARARGS | + METH_CLASS, + "timestamp -> local datetime from a POSIX timestamp " + "(like time.time())."}, + /* Instance methods: */ {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS, "Return ctime() style string."}, + {"isoformat", (PyCFunction)datetime_isoformat, METH_KEYWORDS, "[sep] -> string in ISO 8601 format, YYYY-MM-DDTHH:MM:SS.mmmmmm.\n\n" "sep is used to separate the year from the time, and defaults\n" "to 'T'."}, + {"__setstate__", (PyCFunction)datetime_setstate, METH_O, PyDoc_STR("__setstate__(state)")}, + {"__getstate__", (PyCFunction)datetime_getstate, METH_NOARGS, PyDoc_STR("__getstate__() -> state")}, Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.38 retrieving revision 1.39 diff -C2 -d -r1.38 -r1.39 *** test_both.py 5 Dec 2002 20:28:41 -0000 1.38 --- test_both.py 5 Dec 2002 23:15:59 -0000 1.39 *************** *** 563,577 **** self.assertEqual(d.day, day) ! # Try today. ! today = self.theclass.today() ! ts = time.time() ! todayagain = self.theclass.fromtimestamp(ts) ! if today != todayagain: ! # It's possible that equality fails if we're running at a ! # midnight boundary, so wait a little and try again. ! time.sleep(5) today = self.theclass.today() ts = time.time() todayagain = self.theclass.fromtimestamp(ts) self.assertEqual(today, todayagain) --- 563,583 ---- self.assertEqual(d.day, day) ! def test_today(self): ! import time ! ! count = 0 ! while count < 3: ! count += 1 today = self.theclass.today() ts = time.time() todayagain = self.theclass.fromtimestamp(ts) + if today == todayagain: + break + # It's possible that equality fails if we're running at a + # midnight boundary, and also possible that it fails if we're + # testing datetime and it takes more than a second between + # operations above. Wait a little and try again. + time.sleep(1) + self.assertEqual(today, todayagain) *************** *** 1014,1017 **** --- 1020,1037 ---- self.assertEqual(cmp(t2, t1), 1) + def test_fromtimestamp(self): + import time + + # Try an arbitrary fixed value. + year, month, day = 1999, 9, 19 + hour, minute, second = 22, 17, 36 + ts = time.mktime((year, month, day, hour, minute, second, 0, 0, -1)) + d = self.theclass.fromtimestamp(ts) + self.assertEqual(d.year, year) + self.assertEqual(d.month, month) + self.assertEqual(d.day, day) + self.assertEqual(d.hour, hour) + self.assertEqual(d.minute, minute) + self.assertEqual(d.second, second) def test_suite(): From jackjansen@users.sourceforge.net Thu Dec 5 23:20:14 2002 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Thu, 05 Dec 2002 15:20:14 -0800 Subject: [Python-checkins] python/dist/src/Tools/bgen/bgen bgenObjectDefinition.py,1.20,1.21 Message-ID: Update of /cvsroot/python/python/dist/src/Tools/bgen/bgen In directory sc8-pr-cvs1:/tmp/cvs-serv24705 Modified Files: bgenObjectDefinition.py Log Message: Fixed typo. Index: bgenObjectDefinition.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Tools/bgen/bgen/bgenObjectDefinition.py,v retrieving revision 1.20 retrieving revision 1.21 diff -C2 -d -r1.20 -r1.21 *** bgenObjectDefinition.py 3 Dec 2002 23:35:22 -0000 1.20 --- bgenObjectDefinition.py 5 Dec 2002 23:20:12 -0000 1.21 *************** *** 378,382 **** def output_tp_init(self): if self.output_tp_initBody: ! Output("static int %s_init(PyObject *self, PyObject *args, PyObject *kwds)", self.prefix) OutLbrace() self.output_tp_initBody() --- 378,382 ---- def output_tp_init(self): if self.output_tp_initBody: ! Output("static int %s_tp_init(PyObject *self, PyObject *args, PyObject *kwds)", self.prefix) OutLbrace() self.output_tp_initBody() From jackjansen@users.sourceforge.net Thu Dec 5 23:26:41 2002 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Thu, 05 Dec 2002 15:26:41 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules/res _Resmodule.c,1.15,1.16 resedit.py,1.6,1.7 ressupport.py,1.23,1.24 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules/res In directory sc8-pr-cvs1:/tmp/cvs-serv26728 Modified Files: _Resmodule.c resedit.py ressupport.py Log Message: Fixed so the Res.Resource() accepts either another resource, a string or no argument (giving an empty resource). Index: _Resmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/res/_Resmodule.c,v retrieving revision 1.15 retrieving revision 1.16 diff -C2 -d -r1.15 -r1.16 *** _Resmodule.c 29 Nov 2002 23:40:47 -0000 1.15 --- _Resmodule.c 5 Dec 2002 23:26:38 -0000 1.16 *************** *** 613,616 **** --- 613,658 ---- #define ResObj_hash NULL + static int ResObj_tp_init(PyObject *self, PyObject *args, PyObject *kwds) + { + char *srcdata = NULL; + int srclen = 0; + Handle itself; + char *kw[] = {"itself", 0}; + + if (PyArg_ParseTupleAndKeywords(args, kwds, "O&", kw, ResObj_Convert, &itself)) + { + ((ResourceObject *)self)->ob_itself = itself; + return 0; + } + PyErr_Clear(); + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|s#", kw, &srcdata, &srclen)) return -1; + if ((itself = NewHandle(srclen)) == NULL) + { + PyErr_NoMemory(); + return 0; + } + ((ResourceObject *)self)->ob_itself = itself; + if (srclen && srcdata) + { + HLock(itself); + memcpy(*itself, srcdata, srclen); + HUnlock(itself); + } + return 0; + } + + #define ResObj_tp_alloc PyType_GenericAlloc + + static PyObject *ResObj_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds) + { + PyObject *self; + if ((self = type->tp_alloc(type, 0)) == NULL) return NULL; + ((ResourceObject *)self)->ob_itself = NULL; + ((ResourceObject *)self)->ob_freeit = NULL; + return self; + } + + #define ResObj_tp_free PyObject_Del + PyTypeObject Resource_Type = { *************** *** 635,651 **** PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*outputHook_tp_as_buffer*/ ! 0, /*outputHook_tp_flags*/ ! 0, /*outputHook_tp_doc*/ ! 0, /*outputHook_tp_traverse*/ ! 0, /*outputHook_tp_clear*/ ! 0, /*outputHook_tp_richcompare*/ ! 0, /*outputHook_tp_weaklistoffset*/ ! 0, /*outputHook_tp_iter*/ ! 0, /*outputHook_tp_iternext*/ ResObj_methods, /* tp_methods */ ! 0, /*outputHook_tp_members*/ ResObj_getsetlist, /*tp_getset*/ ! 0, /*outputHook_tp_base*/ }; --- 677,701 ---- PyObject_GenericGetAttr, /*tp_getattro*/ PyObject_GenericSetAttr, /*tp_setattro */ ! 0, /*tp_as_buffer*/ ! Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ ! 0, /*tp_doc*/ ! 0, /*tp_traverse*/ ! 0, /*tp_clear*/ ! 0, /*tp_richcompare*/ ! 0, /*tp_weaklistoffset*/ ! 0, /*tp_iter*/ ! 0, /*tp_iternext*/ ResObj_methods, /* tp_methods */ ! 0, /*tp_members*/ ResObj_getsetlist, /*tp_getset*/ ! 0, /*tp_base*/ ! 0, /*tp_dict*/ ! 0, /*tp_descr_get*/ ! 0, /*tp_descr_set*/ ! 0, /*tp_dictoffset*/ ! ResObj_tp_init, /* tp_init */ ! ResObj_tp_alloc, /* tp_alloc */ ! ResObj_tp_new, /* tp_new */ ! ResObj_tp_free, /* tp_free */ }; *************** *** 1695,1721 **** #endif - static PyObject *Res_Resource(PyObject *_self, PyObject *_args) - { - PyObject *_res = NULL; - - char *buf; - int len; - Handle h; - - if (!PyArg_ParseTuple(_args, "s#", &buf, &len)) - return NULL; - h = NewHandle(len); - if ( h == NULL ) { - PyErr_NoMemory(); - return NULL; - } - HLock(h); - memcpy(*h, buf, len); - HUnlock(h); - _res = ResObj_New(h); - return _res; - - } - static PyObject *Res_Handle(PyObject *_self, PyObject *_args) { --- 1745,1748 ---- *************** *** 1872,1877 **** PyDoc_STR("(FSRef ref, Buffer forkNameLength, SignedByte permissions) -> (SInt16 refNum)")}, #endif - {"Resource", (PyCFunction)Res_Resource, 1, - PyDoc_STR("Convert a string to a resource object.\n\nThe created resource object is actually just a handle,\napply AddResource() to write it to a resource file.\nSee also the Handle() docstring.\n")}, {"Handle", (PyCFunction)Res_Handle, 1, PyDoc_STR("Convert a string to a Handle object.\n\nResource() and Handle() are very similar, but objects created with Handle() are\nby default automatically DisposeHandle()d upon object cleanup. Use AutoDispose()\nto change this.\n")}, --- 1899,1902 ---- *************** *** 1938,1943 **** Resource_Type.ob_type = &PyType_Type; Py_INCREF(&Resource_Type); ! if (PyDict_SetItemString(d, "ResourceType", (PyObject *)&Resource_Type) != 0) ! Py_FatalError("can't initialize ResourceType"); } --- 1963,1970 ---- Resource_Type.ob_type = &PyType_Type; Py_INCREF(&Resource_Type); ! PyModule_AddObject(m, "Resource", (PyObject *)&Resource_Type); ! /* Backward-compatible name */ ! Py_INCREF(&Resource_Type); ! PyModule_AddObject(m, "ResourceType", (PyObject *)&Resource_Type); } Index: resedit.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/res/resedit.py,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** resedit.py 5 Sep 2001 15:44:37 -0000 1.6 --- resedit.py 5 Dec 2002 23:26:38 -0000 1.7 *************** *** 1,29 **** ! resource_body = """ ! char *buf; ! int len; ! Handle h; ! ! if (!PyArg_ParseTuple(_args, "s#", &buf, &len)) ! return NULL; ! h = NewHandle(len); ! if ( h == NULL ) { ! PyErr_NoMemory(); ! return NULL; ! } ! HLock(h); ! memcpy(*h, buf, len); ! HUnlock(h); ! _res = ResObj_New(h); ! return _res; ! """ ! ! f = ManualGenerator("Resource", resource_body) ! f.docstring = lambda: """Convert a string to a resource object. ! ! The created resource object is actually just a handle, ! apply AddResource() to write it to a resource file. ! See also the Handle() docstring. ! """ ! functions.append(f) handle_body = """ --- 1,29 ---- ! ##resource_body = """ ! ##char *buf; ! ##int len; ! ##Handle h; ! ## ! ##if (!PyArg_ParseTuple(_args, "s#", &buf, &len)) ! ## return NULL; ! ##h = NewHandle(len); ! ##if ( h == NULL ) { ! ## PyErr_NoMemory(); ! ## return NULL; ! ##} ! ##HLock(h); ! ##memcpy(*h, buf, len); ! ##HUnlock(h); ! ##_res = ResObj_New(h); ! ##return _res; ! ##""" ! ## ! ##f = ManualGenerator("Resource", resource_body) ! ##f.docstring = lambda: """Convert a string to a resource object. ! ## ! ##The created resource object is actually just a handle, ! ##apply AddResource() to write it to a resource file. ! ##See also the Handle() docstring. ! ##""" ! ##functions.append(f) handle_body = """ Index: ressupport.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/res/ressupport.py,v retrieving revision 1.23 retrieving revision 1.24 diff -C2 -d -r1.23 -r1.24 *** ressupport.py 29 Nov 2002 23:40:47 -0000 1.23 --- ressupport.py 5 Dec 2002 23:26:38 -0000 1.24 *************** *** 101,105 **** module = MacModule('_Res', 'Res', includestuff, finalstuff, initstuff) ! class ResDefinition(PEP252Mixin, GlobalObjectDefinition): getsetlist = [ ('data', --- 101,105 ---- module = MacModule('_Res', 'Res', includestuff, finalstuff, initstuff) ! class ResDefinition(PEP253Mixin, GlobalObjectDefinition): getsetlist = [ ('data', *************** *** 177,180 **** --- 177,216 ---- Output("self->ob_itself = NULL;") + def output_tp_newBody(self): + Output("PyObject *self;") + Output + Output("if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;") + Output("((%s *)self)->ob_itself = NULL;", self.objecttype) + Output("((%s *)self)->ob_freeit = NULL;", self.objecttype) + Output("return self;") + + def output_tp_initBody(self): + Output("char *srcdata = NULL;") + Output("int srclen = 0;") + Output("%s itself;", self.itselftype); + Output("char *kw[] = {\"itself\", 0};") + Output() + Output("if (PyArg_ParseTupleAndKeywords(args, kwds, \"O&\", kw, %s_Convert, &itself))", + self.prefix); + OutLbrace() + Output("((%s *)self)->ob_itself = itself;", self.objecttype) + Output("return 0;") + OutRbrace() + Output("PyErr_Clear();") + Output("if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|s#\", kw, &srcdata, &srclen)) return -1;") + Output("if ((itself = NewHandle(srclen)) == NULL)") + OutLbrace() + Output("PyErr_NoMemory();") + Output("return 0;") + OutRbrace() + Output("((%s *)self)->ob_itself = itself;", self.objecttype) + # XXXX Output("((%s *)self)->ob_freeit = PyMac_AutoDisposeHandle;") + Output("if (srclen && srcdata)") + OutLbrace() + Output("HLock(itself);") + Output("memcpy(*itself, srcdata, srclen);") + Output("HUnlock(itself);") + OutRbrace() + Output("return 0;") resobject = ResDefinition('Resource', 'ResObj', 'Handle') From tim_one@users.sourceforge.net Thu Dec 5 23:27:09 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 05 Dec 2002 15:27:09 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime doc.txt,1.13,1.14 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv27093 Modified Files: doc.txt Log Message: Typo repairs. Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** doc.txt 5 Dec 2002 23:15:59 -0000 1.13 --- doc.txt 5 Dec 2002 23:27:06 -0000 1.14 *************** *** 364,373 **** - fromordinal(ordinal) ! Return the date corresponding to the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1. ValueError is raised ! unless 1 <= ordinal <= datetime.max.toordinal(). XXX THERE ARE A SLEW OF OTHER CONSTRUCTORS IN THE PYTHON IMPLEMENTATION ! XXX THAT DON'T EXIST YET IN THE C IMPLEMENTATION. Class attributes: --- 364,374 ---- - fromordinal(ordinal) ! Return the datetime corresponding to the proleptic Gregorian ordinal, where January 1 of year 1 has ordinal 1. ValueError is raised ! unless 1 <= ordinal <= datetime.max.toordinal(). The hour, minute, ! second and microsecond of the result are all 0. XXX THERE ARE A SLEW OF OTHER CONSTRUCTORS IN THE PYTHON IMPLEMENTATION ! XXX THAT DON'T EXIST YET IN THE C IMPLEMENTATION. Class attributes: *************** *** 403,408 **** forward in time if timedelta.days > 0, or backward if timedelta.days < 0. datetime2 - datetime1 == timedelta after. ! OverflowError is raised if date2.year would be smaller than MINYEAR ! or larger than MAXYEAR. XXX NOTHING BELOW THIS POINT HAS BEEN CHECKED, AND MUCH IS CERTAINLY --- 404,409 ---- forward in time if timedelta.days > 0, or backward if timedelta.days < 0. datetime2 - datetime1 == timedelta after. ! OverflowError is raised if datetime2.year would be smaller than ! MINYEAR or larger than MAXYEAR. XXX NOTHING BELOW THIS POINT HAS BEEN CHECKED, AND MUCH IS CERTAINLY From tim_one@users.sourceforge.net Fri Dec 6 00:15:31 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 05 Dec 2002 16:15:31 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime test_both.py,1.39,1.40 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv10338 Modified Files: test_both.py Log Message: Verify that fromordinal() zeroes out "extra" instance members. Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.39 retrieving revision 1.40 diff -C2 -d -r1.39 -r1.40 *** test_both.py 5 Dec 2002 23:15:59 -0000 1.39 --- test_both.py 6 Dec 2002 00:15:28 -0000 1.40 *************** *** 389,393 **** d = self.theclass(y, m, d) self.assertEqual(n, d.toordinal()) ! self.assertEqual(d, self.theclass.fromordinal(n)) # Check first and last days of year spottily across the whole --- 389,401 ---- d = self.theclass(y, m, d) self.assertEqual(n, d.toordinal()) ! fromord = self.theclass.fromordinal(n) ! self.assertEqual(d, fromord) ! if hasattr(fromord, "hour"): ! # if we're checking something fancier than a date, verify ! # the extra fields have been zeroed out ! self.assertEqual(fromord.hour, 0) ! self.assertEqual(fromord.minute, 0) ! self.assertEqual(fromord.second, 0) ! self.assertEqual(fromord.microsecond, 0) # Check first and last days of year spottily across the whole From tim_one@users.sourceforge.net Fri Dec 6 00:20:36 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 05 Dec 2002 16:20:36 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime doc.txt,1.14,1.15 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv11684 Modified Files: doc.txt Log Message: Fixed some more cut-n-paste datetime docs. Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.14 retrieving revision 1.15 diff -C2 -d -r1.14 -r1.15 *** doc.txt 5 Dec 2002 23:27:06 -0000 1.14 --- doc.txt 6 Dec 2002 00:20:33 -0000 1.15 *************** *** 320,324 **** a date object and a time object. Like a date object, datetime assumes the current Gregorian calendar extended in both directions; like a time ! object, datetime assumes there are exact 3600*24 seconds in every day. Constructor: --- 320,324 ---- a date object and a time object. Like a date object, datetime assumes the current Gregorian calendar extended in both directions; like a time ! object, datetime assumes there are exactly 3600*24 seconds in every day. Constructor: *************** *** 407,431 **** MINYEAR or larger than MAXYEAR. - XXX NOTHING BELOW THIS POINT HAS BEEN CHECKED, AND MUCH IS CERTAINLY - XXX WRONG (CUT & PASTE ERRORS MOSTLY) AND/OR MISIMPLEMENTED. - - date1 - timedelta -> date2 ! Computes the date2 such that date2 + timedelta == date1. This ! isn't quite equivalent to date1 + (-timedelta), because -timedelta ! in isolation can overflow in cases where date1 - timedelta does ! not. timedelta.seconds and timedelta.microseconds are ignored. ! - date1 - date2 -> timedelta ! This is exact, and cannot overflow. timedelta.seconds and ! timedelta.microseconds are 0, and date2 + timedelta == date1 ! after. ! - comparison of date to date, where date1 is considered less than ! date2 when date1 precedes date2 in time. In other words, ! date1 < date2 if and only if date1.toordinal() < date2.toordinal(). - hash, use as dict key - pickling Instance methods: --- 407,429 ---- MINYEAR or larger than MAXYEAR. - date1 - timedelta -> date2 ! Computes the datetime2 such that datetime2 + timedelta == datetime1. ! This isn't quite equivalent to datetime1 + (-timedelta), because ! -timedelta in isolation can overflow in cases where ! datetime1 - timedelta does not. ! - datetime1 - datetime2 -> timedelta ! This is exact, and cannot overflow. ! datetime2 + timedelta == datetime1 after. ! - comparison of datetime1 to datetime, where datetime1 is considered ! less than datetime2 when datetime1 precedes datetime2 in time. - hash, use as dict key - pickling + + XXX NOTHING BELOW THIS POINT HAS BEEN CHECKED, AND MUCH IS CERTAINLY + XXX WRONG (CUT & PASTE ERRORS MOSTLY) AND/OR MISIMPLEMENTED. Instance methods: From tim_one@users.sourceforge.net Fri Dec 6 00:55:30 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 05 Dec 2002 16:55:30 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime doc.txt,1.15,1.16 obj_datetime.c,1.20,1.21 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv22096 Modified Files: doc.txt obj_datetime.c Log Message: Rearranged the datetime code so that related functions are grouped next to each other. Got rid of datetime_nonzero, and reused date_nonzero for it (they both return true regardless of input). Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.15 retrieving revision 1.16 diff -C2 -d -r1.15 -r1.16 *** doc.txt 6 Dec 2002 00:20:33 -0000 1.15 --- doc.txt 6 Dec 2002 00:55:28 -0000 1.16 *************** *** 417,421 **** datetime2 + timedelta == datetime1 after. ! - comparison of datetime1 to datetime, where datetime1 is considered less than datetime2 when datetime1 precedes datetime2 in time. --- 417,421 ---- datetime2 + timedelta == datetime1 after. ! - comparison of datetime to datetime, where datetime1 is considered less than datetime2 when datetime1 precedes datetime2 in time. Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.20 retrieving revision 1.21 diff -C2 -d -r1.20 -r1.21 *** obj_datetime.c 5 Dec 2002 23:15:59 -0000 1.20 --- obj_datetime.c 6 Dec 2002 00:55:28 -0000 1.21 *************** *** 3,181 **** */ ! /* Force all the datetime fields into range. The parameters are both ! * inputs and outputs. Returns < 0 on error. ! */ ! static int ! normalize_datetime(long *year, long *month, long *day, ! long *hour, long *minute, long *second, ! long *microsecond) ! { ! normalize_pair(second, microsecond, 1000000); ! normalize_pair(minute, second, 60); ! normalize_pair(hour, minute, 60); ! normalize_pair(day, hour, 24); ! return normalize_date(year, month, day); ! } ! ! static PyObject * ! add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta) ! { ! /* Note that the C-level additions can't overflow, because of ! * invariant bounds on the member values. ! */ ! long year = GET_YEAR(date); ! long month = GET_MONTH(date); ! long day = GET_DAY(date) + GET_TD_DAYS(delta); ! long hour = GET_HOUR(date); ! long minute = GET_MINUTE(date); ! long second = GET_SECOND(date) + GET_TD_SECONDS(delta); ! long microsecond = GET_MICROSECOND(date) + GET_TD_MICROSECONDS(delta); ! ! if (normalize_datetime(&year, &month, &day, ! &hour, &minute, &second, µsecond) < 0) ! return NULL; ! else ! return new_datetime(year, month, day, ! hour, minute, second, microsecond); ! } ! ! static PyObject * ! sub_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta) ! { ! /* Note that the C-level subtractions can't overflow, because of ! * invariant bounds on the member values. ! */ ! long year = GET_YEAR(date); ! long month = GET_MONTH(date); ! long day = GET_DAY(date) - GET_TD_DAYS(delta); ! long hour = GET_HOUR(date); ! long minute = GET_MINUTE(date); ! long second = GET_SECOND(date) - GET_TD_SECONDS(delta); ! long microsecond = GET_MICROSECOND(date) - GET_TD_MICROSECONDS(delta); ! ! if (normalize_datetime(&year, &month, &day, ! &hour, &minute, &second, µsecond) < 0) ! return NULL; ! else ! return new_datetime(year, month, day, ! hour, minute, second, microsecond); ! } static PyObject * ! sub_datetime_datetime(PyDateTime_DateTime *left, PyDateTime_DateTime *right) { ! long days1 = ymd_to_ord(GET_YEAR(left), ! GET_MONTH(left), ! GET_DAY(left)); ! long days2 = ymd_to_ord(GET_YEAR(right), ! GET_MONTH(right), ! GET_DAY(right)); ! ! /* These can't overflow, since the values are normalized. At most ! * this gives the number of seconds in one day. ! */ ! long seconds1 = (GET_HOUR(left) * 60 + GET_MINUTE(left)) * 60 + ! GET_SECOND(left); ! long seconds2 = (GET_HOUR(right) * 60 + GET_MINUTE(right)) * 60 + ! GET_SECOND(right); ! long delta_us = GET_MICROSECOND(left) - GET_MICROSECOND(right); ! ! return new_delta(days1 - days2, seconds1 - seconds2, delta_us, 1); } static PyObject * ! datetime_add(PyObject *left, PyObject *right) { ! PyTypeObject *left_type = left->ob_type; ! PyTypeObject *right_type = right->ob_type; ! ! if (PyType_IsSubtype(left_type, &PyDateTime_DateTimeType)) { ! /* datetime + ??? */ ! if (PyType_IsSubtype(right_type, &PyDateTime_DeltaType)) ! /* datetime + delta */ ! return add_datetime_timedelta( ! (PyDateTime_DateTime *)left, ! (PyDateTime_Delta *)right); ! } ! else if (PyType_IsSubtype(left_type, &PyDateTime_DeltaType)) { ! /* delta + datetime */ ! return add_datetime_timedelta((PyDateTime_DateTime *) right, ! (PyDateTime_Delta *) left); ! } ! Py_INCREF(Py_NotImplemented); ! return Py_NotImplemented; } static PyObject * ! datetime_subtract(PyObject *left, PyObject *right) { ! PyTypeObject *left_type = left->ob_type; ! PyTypeObject *right_type = right->ob_type; ! PyObject *result = Py_NotImplemented; ! ! if (PyType_IsSubtype(left_type, &PyDateTime_DateTimeType)) { ! /* datetime - ??? */ ! if (PyType_IsSubtype(right_type, &PyDateTime_DateTimeType)) { ! /* datetime - datetime */ ! result = sub_datetime_datetime( ! (PyDateTime_DateTime *)left, ! (PyDateTime_DateTime *)right); ! } ! else if (PyType_IsSubtype(right_type, &PyDateTime_DeltaType)) { ! /* datetime - delta */ ! result = sub_datetime_timedelta( ! (PyDateTime_DateTime *)left, ! (PyDateTime_Delta *)right); ! } ! } ! ! if (result == Py_NotImplemented) ! Py_INCREF(result); ! 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 * ! datetime_richcompare(PyDateTime_DateTime *self, PyObject *other, int op) { ! long diff; ! ! if (!PyType_IsSubtype(other->ob_type, &PyDateTime_DateTimeType)) { ! PyErr_Format(PyExc_TypeError, ! "can't compare datetime to %s instance", ! other->ob_type->tp_name); ! return NULL; ! } ! diff = memcmp(self->data, ((PyDateTime_DateTime *)other)->data, ! _PyDateTime_DATETIME_DATA_SIZE); ! return diff_to_bool(diff, op); } ! static PyObject * ! datetime_ctime(PyDateTime_DateTime *self) ! { ! return format_ctime((PyDateTime_Date *)self, ! GET_HOUR(self), GET_MINUTE(self), GET_SECOND(self)); ! } ! static long ! datetime_hash(PyDateTime_DateTime *self) ! { ! if (self->hashcode == -1) { ! PyObject *temp; ! temp = Py_BuildValue("lllllll", GET_YEAR(self), ! GET_MONTH(self), GET_DAY(self), ! GET_HOUR(self), GET_MINUTE(self), ! GET_SECOND(self), GET_MICROSECOND(self)); ! if (temp != NULL) { ! self->hashcode = PyObject_Hash(temp); ! Py_DECREF(temp); ! } ! } ! return self->hashcode; ! } static PyObject * --- 3,41 ---- */ ! /* Accessor properties. */ static PyObject * ! datetime_hour(PyDateTime_DateTime *self, void *unused) { ! return PyInt_FromLong(GET_HOUR(self)); } static PyObject * ! datetime_minute(PyDateTime_DateTime *self, void *unused) { ! return PyInt_FromLong(GET_MINUTE(self)); } static PyObject * ! datetime_second(PyDateTime_DateTime *self, void *unused) { ! return PyInt_FromLong(GET_SECOND(self)); } static PyObject * ! datetime_microsecond(PyDateTime_DateTime *self, void *unused) { ! return PyInt_FromLong(GET_MICROSECOND(self)); } ! static PyGetSetDef datetime_getset[] = { ! {"hour", (getter)datetime_hour}, ! {"minute", (getter)datetime_minute}, ! {"second", (getter)datetime_second}, ! {"microsecond", (getter)datetime_microsecond}, ! {NULL} ! }; ! /* Constructors. */ static PyObject * *************** *** 333,367 **** } static PyObject * ! datetime_hour(PyDateTime_DateTime *self, void *unused) { ! return PyInt_FromLong(GET_HOUR(self)); } static PyObject * ! datetime_minute(PyDateTime_DateTime *self, void *unused) { ! return PyInt_FromLong(GET_MINUTE(self)); } static PyObject * ! datetime_second(PyDateTime_DateTime *self, void *unused) { ! return PyInt_FromLong(GET_SECOND(self)); } static PyObject * ! datetime_microsecond(PyDateTime_DateTime *self, void *unused) { ! return PyInt_FromLong(GET_MICROSECOND(self)); } ! static PyGetSetDef datetime_getset[] = { ! {"hour", (getter)datetime_hour}, ! {"minute", (getter)datetime_minute}, ! {"second", (getter)datetime_second}, ! {"microsecond", (getter)datetime_microsecond}, ! {NULL} ! }; static PyObject * --- 193,331 ---- } + /* datetime arithmetic. */ + + /* Force all the datetime fields into range. The parameters are both + * inputs and outputs. Returns < 0 on error. + */ + static int + normalize_datetime(long *year, long *month, long *day, + long *hour, long *minute, long *second, + long *microsecond) + { + normalize_pair(second, microsecond, 1000000); + normalize_pair(minute, second, 60); + normalize_pair(hour, minute, 60); + normalize_pair(day, hour, 24); + return normalize_date(year, month, day); + } + static PyObject * ! add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta) { ! /* Note that the C-level additions can't overflow, because of ! * invariant bounds on the member values. ! */ ! long year = GET_YEAR(date); ! long month = GET_MONTH(date); ! long day = GET_DAY(date) + GET_TD_DAYS(delta); ! long hour = GET_HOUR(date); ! long minute = GET_MINUTE(date); ! long second = GET_SECOND(date) + GET_TD_SECONDS(delta); ! long microsecond = GET_MICROSECOND(date) + GET_TD_MICROSECONDS(delta); ! ! if (normalize_datetime(&year, &month, &day, ! &hour, &minute, &second, µsecond) < 0) ! return NULL; ! else ! return new_datetime(year, month, day, ! hour, minute, second, microsecond); } static PyObject * ! sub_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta) { ! /* Note that the C-level subtractions can't overflow, because of ! * invariant bounds on the member values. ! */ ! long year = GET_YEAR(date); ! long month = GET_MONTH(date); ! long day = GET_DAY(date) - GET_TD_DAYS(delta); ! long hour = GET_HOUR(date); ! long minute = GET_MINUTE(date); ! long second = GET_SECOND(date) - GET_TD_SECONDS(delta); ! long microsecond = GET_MICROSECOND(date) - GET_TD_MICROSECONDS(delta); ! ! if (normalize_datetime(&year, &month, &day, ! &hour, &minute, &second, µsecond) < 0) ! return NULL; ! else ! return new_datetime(year, month, day, ! hour, minute, second, microsecond); } static PyObject * ! sub_datetime_datetime(PyDateTime_DateTime *left, PyDateTime_DateTime *right) { ! long days1 = ymd_to_ord(GET_YEAR(left), ! GET_MONTH(left), ! GET_DAY(left)); ! long days2 = ymd_to_ord(GET_YEAR(right), ! GET_MONTH(right), ! GET_DAY(right)); ! ! /* These can't overflow, since the values are normalized. At most ! * this gives the number of seconds in one day. ! */ ! long seconds1 = (GET_HOUR(left) * 60 + GET_MINUTE(left)) * 60 + ! GET_SECOND(left); ! long seconds2 = (GET_HOUR(right) * 60 + GET_MINUTE(right)) * 60 + ! GET_SECOND(right); ! long delta_us = GET_MICROSECOND(left) - GET_MICROSECOND(right); ! ! return new_delta(days1 - days2, seconds1 - seconds2, delta_us, 1); } static PyObject * ! datetime_add(PyObject *left, PyObject *right) { ! PyTypeObject *left_type = left->ob_type; ! PyTypeObject *right_type = right->ob_type; ! ! if (PyType_IsSubtype(left_type, &PyDateTime_DateTimeType)) { ! /* datetime + ??? */ ! if (PyType_IsSubtype(right_type, &PyDateTime_DeltaType)) ! /* datetime + delta */ ! return add_datetime_timedelta( ! (PyDateTime_DateTime *)left, ! (PyDateTime_Delta *)right); ! } ! else if (PyType_IsSubtype(left_type, &PyDateTime_DeltaType)) { ! /* delta + datetime */ ! return add_datetime_timedelta((PyDateTime_DateTime *) right, ! (PyDateTime_Delta *) left); ! } ! Py_INCREF(Py_NotImplemented); ! return Py_NotImplemented; } ! static PyObject * ! datetime_subtract(PyObject *left, PyObject *right) ! { ! PyTypeObject *left_type = left->ob_type; ! PyTypeObject *right_type = right->ob_type; ! PyObject *result = Py_NotImplemented; ! ! if (PyType_IsSubtype(left_type, &PyDateTime_DateTimeType)) { ! /* datetime - ??? */ ! if (PyType_IsSubtype(right_type, &PyDateTime_DateTimeType)) { ! /* datetime - datetime */ ! result = sub_datetime_datetime( ! (PyDateTime_DateTime *)left, ! (PyDateTime_DateTime *)right); ! } ! else if (PyType_IsSubtype(right_type, &PyDateTime_DeltaType)) { ! /* datetime - delta */ ! result = sub_datetime_timedelta( ! (PyDateTime_DateTime *)left, ! (PyDateTime_Delta *)right); ! } ! } ! ! if (result == Py_NotImplemented) ! Py_INCREF(result); ! return result; ! } ! ! /* Various ways to turn a datetime into a string. */ static PyObject * *************** *** 431,439 **** } ! static int ! datetime_nonzero(PyDateTime_DateTime *self) { ! assert(GET_YEAR(self) >= 1); ! return 1; } --- 395,444 ---- } ! static PyObject * ! datetime_ctime(PyDateTime_DateTime *self) { ! return format_ctime((PyDateTime_Date *)self, ! GET_HOUR(self), ! GET_MINUTE(self), ! GET_SECOND(self)); ! } ! ! /* 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) ! { ! long diff; ! ! if (!PyType_IsSubtype(other->ob_type, &PyDateTime_DateTimeType)) { ! PyErr_Format(PyExc_TypeError, ! "can't compare datetime to %s instance", ! other->ob_type->tp_name); ! return NULL; ! } ! diff = memcmp(self->data, ((PyDateTime_DateTime *)other)->data, ! _PyDateTime_DATETIME_DATA_SIZE); ! return diff_to_bool(diff, op); ! } ! ! static long ! datetime_hash(PyDateTime_DateTime *self) ! { ! if (self->hashcode == -1) { ! PyObject *temp; ! temp = Py_BuildValue("lllllll", GET_YEAR(self), ! GET_MONTH(self), GET_DAY(self), ! GET_HOUR(self), GET_MINUTE(self), ! GET_SECOND(self), GET_MICROSECOND(self)); ! if (temp != NULL) { ! self->hashcode = PyObject_Hash(temp); ! Py_DECREF(temp); ! } ! } ! return self->hashcode; } *************** *** 529,542 **** static PyNumberMethods datetime_as_number = { datetime_add, /* nb_add */ ! datetime_subtract, /* nb_subtract */ ! 0, /* nb_multiply */ ! 0, /* nb_divide */ ! 0, /* nb_remainder */ ! 0, /* nb_divmod */ ! 0, /* nb_power */ ! 0, /* nb_negative */ ! 0, /* nb_positive */ ! 0, /* nb_absolute */ ! (inquiry)datetime_nonzero, /* nb_nonzero */ }; --- 534,547 ---- static PyNumberMethods datetime_as_number = { datetime_add, /* nb_add */ ! datetime_subtract, /* nb_subtract */ ! 0, /* nb_multiply */ ! 0, /* nb_divide */ ! 0, /* nb_remainder */ ! 0, /* nb_divmod */ ! 0, /* nb_power */ ! 0, /* nb_negative */ ! 0, /* nb_positive */ ! 0, /* nb_absolute */ ! (inquiry)date_nonzero, /* nb_nonzero */ }; From tim_one@users.sourceforge.net Fri Dec 6 02:17:44 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 05 Dec 2002 18:17:44 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime doc.txt,1.16,1.17 obj_datetime.c,1.21,1.22 test_both.py,1.40,1.41 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv16588 Modified Files: doc.txt obj_datetime.c test_both.py Log Message: Implemented datetime.utcfromtimestamp, and added a test. Reworked the test for datetime.fromtimestamp to match. Reworked the internals so that the timestamp constructors could share more tedious code. At considerable cost, made datetime.today() work the way it's documented to work. Exporting time.time in a more reasonable way (for access from C code) would eliminate the artificial expense. Reworked the today() test to try to be robust against several legitimate failure modes (having to do with systems resetting their clocks, time.time() having extremely fine resolution, and time.time() having poor resolution). Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.16 retrieving revision 1.17 diff -C2 -d -r1.16 -r1.17 *** doc.txt 6 Dec 2002 00:55:28 -0000 1.16 --- doc.txt 6 Dec 2002 02:17:42 -0000 1.17 *************** *** 346,349 **** --- 346,350 ---- Return the current local datetime. This is equivalent to datetime.fromtimestamp(time.time()). + See also now(). - now() *************** *** 352,364 **** possible, supplies more precision than can be gotten from going through a time.time() timestamp. XXX It currently doesn't. - fromtimestamp(timestamp) ! Return the local datetime corresponding to the POSIX timestamp, such as ! is returned by time.time(). This may raise ValueError, if the timestamp is out of the range of values supported by the platform C localtime() function. It's common for this to be restricted to years in 1970 through 2038. - fromordinal(ordinal) --- 353,375 ---- possible, supplies more precision than can be gotten from going through a time.time() timestamp. + See also today(). XXX It currently doesn't. - fromtimestamp(timestamp) ! Return the local datetime corresponding to the POSIX timestamp, such ! as is returned by time.time(). This may raise ValueError, if the timestamp is out of the range of values supported by the platform C localtime() function. It's common for this to be restricted to years in 1970 through 2038. + See also utcfromtimestamp(). + + - utcfromtimestamp(timestamp) + + Return the UTC datetime corresponding to the POSIX timestamp. + This may raise ValueError, if the timestamp is out of the range of + values supported by the platform C gmtime() function. It's common + for this to be restricted to years in 1970 through 2038. + See also fromtimestamp(). - fromordinal(ordinal) Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.21 retrieving revision 1.22 diff -C2 -d -r1.21 -r1.22 *** obj_datetime.c 6 Dec 2002 00:55:28 -0000 1.21 --- obj_datetime.c 6 Dec 2002 02:17:42 -0000 1.22 *************** *** 100,112 **** } static PyObject * ! datetime_local_from_time_t(PyObject *cls, time_t t) { struct tm *tm; PyObject *result = NULL; ! tm = localtime(&t); if (tm) ! result = PyObject_CallFunction(cls, "llllll", tm->tm_year + 1900, tm->tm_mon + 1, --- 100,118 ---- } + + /* TM_FUNC is the shared type of localtime() and gmtime(). */ + typedef struct tm *(*TM_FUNC)(const time_t *timer); + static PyObject * ! datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp) { struct tm *tm; + time_t timet = (time_t)timestamp; + long us = (long)((timestamp - (double)timet) * 1e6); PyObject *result = NULL; ! tm = f(&timet); if (tm) ! result = PyObject_CallFunction(cls, "lllllll", tm->tm_year + 1900, tm->tm_mon + 1, *************** *** 114,126 **** tm->tm_hour, tm->tm_min, ! tm->tm_sec); else PyErr_SetString(PyExc_ValueError, "timestamp out of range for " ! "platform localtime() function"); return result; } ! /* Return new datetime from given timestamp (Python timestamp -- a double). */ static PyObject * datetime_fromtimestamp(PyObject *self, PyObject *args) --- 120,133 ---- tm->tm_hour, tm->tm_min, ! tm->tm_sec, ! us); else PyErr_SetString(PyExc_ValueError, "timestamp out of range for " ! "platform localtime()/gmtime() function"); return result; } ! /* Return new local datetime from timestamp (Python timestamp -- a double). */ static PyObject * datetime_fromtimestamp(PyObject *self, PyObject *args) *************** *** 131,135 **** if (PyArg_ParseTuple(args, "Od:fromtimestamp", &cls, ×tamp)) ! result = datetime_local_from_time_t(cls, (time_t)timestamp); return result; } --- 138,155 ---- if (PyArg_ParseTuple(args, "Od:fromtimestamp", &cls, ×tamp)) ! result = datetime_from_timestamp(cls, localtime, timestamp); ! return result; ! } ! ! /* Return new UTC datetime from timestamp (Python timestamp -- a double). */ ! static PyObject * ! datetime_utcfromtimestamp(PyObject *self, PyObject *args) ! { ! PyObject *cls; ! double timestamp; ! PyObject *result = NULL; ! ! if (PyArg_ParseTuple(args, "Od:utcfromtimestamp", &cls, ×tamp)) ! result = datetime_from_timestamp(cls, gmtime, timestamp); return result; } *************** *** 178,194 **** } static PyObject * datetime_today(PyObject *self, PyObject *cls) { ! struct tm *tm; ! time_t timet; ! time(&timet); ! tm = localtime(&timet); ! return PyObject_CallFunction(cls, "llllll", ! tm->tm_year + 1900, tm->tm_mon + 1, ! tm->tm_mday, tm->tm_hour, ! tm->tm_min, tm->tm_sec); } --- 198,233 ---- } + /* Well, we say this is equivalent to fromtimestamp(time.time()), and the + * only way to be sure of that is to *call* time.time(). That's not + * generally the same as calling C's time. + * XXX Expose the time module's C code in a saner way. + */ static PyObject * datetime_today(PyObject *self, PyObject *cls) { ! PyObject *time; ! PyObject *time_time; ! PyObject *result; ! double timestamp; ! time = PyImport_ImportModule("time"); ! if (time == NULL) ! return NULL; ! time_time = PyObject_GetAttrString(time, "time"); ! Py_DECREF(time); ! if (time_time == NULL) ! return NULL; ! ! time = PyObject_CallObject(time_time, NULL); ! Py_DECREF(time_time); ! if (time == NULL) ! return NULL; ! ! timestamp = PyFloat_AsDouble(time); ! Py_DECREF(time); ! if (timestamp == -1.0 && PyErr_Occurred()) ! return NULL; ! return datetime_from_timestamp(cls, localtime, timestamp); } *************** *** 444,447 **** --- 483,487 ---- /* Pickle support. Quite a maze! */ + static PyObject * datetime_getstate(PyDateTime_DateTime *self) *************** *** 510,513 **** --- 550,558 ---- METH_CLASS, "timestamp -> local datetime from a POSIX timestamp " + "(like time.time())."}, + + {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp, + METH_VARARGS | METH_CLASS, + "timestamp -> UTC datetime from a POSIX timestamp " "(like time.time())."}, Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.40 retrieving revision 1.41 diff -C2 -d -r1.40 -r1.41 *** test_both.py 6 Dec 2002 00:15:28 -0000 1.40 --- test_both.py 6 Dec 2002 02:17:42 -0000 1.41 *************** *** 574,580 **** import time ! count = 0 ! while count < 3: ! count += 1 today = self.theclass.today() ts = time.time() --- 574,580 ---- import time ! # We claim that today() is like fromtimestamp(time.time()), so ! # prove it. ! for dummy in range(3): today = self.theclass.today() ts = time.time() *************** *** 582,592 **** if today == todayagain: break ! # It's possible that equality fails if we're running at a ! # midnight boundary, and also possible that it fails if we're ! # testing datetime and it takes more than a second between ! # operations above. Wait a little and try again. ! time.sleep(1) ! self.assertEqual(today, todayagain) def test_weekday(self): --- 582,601 ---- if today == todayagain: break ! # There are several legit reasons that could fail: ! # 1. It recently became midnight, between the today() and the ! # time() calls. ! # 2. The platform time() has such fine resolution that we'll ! # never get the same value twice. ! # 3. The platform time() has poor resolution, and we just ! # happened to call today() right before a resolution quantum ! # boundary. ! # 4. The system clock got fiddled between calls. ! # In any case, wait a little while and try again. ! time.sleep(0.1) ! # It worked or it didn't. If it didn't, assume it's reason #2, and ! # let the test pass if they're within half a second of each other. ! self.failUnless(today == todayagain or ! abs(todayagain - today) < timedelta(seconds=0.5)) def test_weekday(self): *************** *** 1028,1045 **** self.assertEqual(cmp(t2, t1), 1) def test_fromtimestamp(self): import time ! # Try an arbitrary fixed value. ! year, month, day = 1999, 9, 19 ! hour, minute, second = 22, 17, 36 ! ts = time.mktime((year, month, day, hour, minute, second, 0, 0, -1)) ! d = self.theclass.fromtimestamp(ts) ! self.assertEqual(d.year, year) ! self.assertEqual(d.month, month) ! self.assertEqual(d.day, day) ! self.assertEqual(d.hour, hour) ! self.assertEqual(d.minute, minute) ! self.assertEqual(d.second, second) def test_suite(): --- 1037,1066 ---- self.assertEqual(cmp(t2, t1), 1) + + # A helper for timestamp constructor tests. + def verify_field_equality(self, expected, got): + self.assertEqual(expected.tm_year, got.year) + self.assertEqual(expected.tm_mon, got.month) + self.assertEqual(expected.tm_mday, got.day) + self.assertEqual(expected.tm_hour, got.hour) + self.assertEqual(expected.tm_min, got.minute) + self.assertEqual(expected.tm_sec, got.second) + def test_fromtimestamp(self): import time ! ts = time.time() ! expected = time.localtime(ts) ! got = self.theclass.fromtimestamp(ts) ! self.verify_field_equality(expected, got) ! ! def test_utcfromtimestamp(self): ! import time ! ! ts = time.time() ! expected = time.gmtime(ts) ! got = self.theclass.utcfromtimestamp(ts) ! self.verify_field_equality(expected, got) ! def test_suite(): From tim_one@users.sourceforge.net Fri Dec 6 02:42:09 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 05 Dec 2002 18:42:09 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime doc.txt,1.17,1.18 obj_datetime.c,1.22,1.23 test_both.py,1.41,1.42 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv25138 Modified Files: doc.txt obj_datetime.c test_both.py Log Message: Implemented timedelta.utc_now(), and wrote a test, docs, etc. Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.17 retrieving revision 1.18 diff -C2 -d -r1.17 -r1.18 *** doc.txt 6 Dec 2002 02:17:42 -0000 1.17 --- doc.txt 6 Dec 2002 02:42:06 -0000 1.18 *************** *** 346,350 **** Return the current local datetime. This is equivalent to datetime.fromtimestamp(time.time()). ! See also now(). - now() --- 346,350 ---- Return the current local datetime. This is equivalent to datetime.fromtimestamp(time.time()). ! See also now(), fromtimestamp(). - now() *************** *** 353,358 **** possible, supplies more precision than can be gotten from going through a time.time() timestamp. ! See also today(). ! XXX It currently doesn't. - fromtimestamp(timestamp) --- 353,364 ---- possible, supplies more precision than can be gotten from going through a time.time() timestamp. ! XXX It currently doesn't. To the contrary, it's currently worse. ! See also today(), utcnow(). ! ! - utcnow() ! ! Return the current UTC datetime. This is like now(), but returns ! the current UTC date and time. ! See also now(). - fromtimestamp(timestamp) *************** *** 379,385 **** unless 1 <= ordinal <= datetime.max.toordinal(). The hour, minute, second and microsecond of the result are all 0. - - XXX THERE ARE A SLEW OF OTHER CONSTRUCTORS IN THE PYTHON IMPLEMENTATION - XXX THAT DON'T EXIST YET IN THE C IMPLEMENTATION. Class attributes: --- 385,388 ---- Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.22 retrieving revision 1.23 diff -C2 -d -r1.22 -r1.23 *** obj_datetime.c 6 Dec 2002 02:17:42 -0000 1.22 --- obj_datetime.c 6 Dec 2002 02:42:06 -0000 1.23 *************** *** 198,201 **** --- 198,219 ---- } + static PyObject * + datetime_utcnow(PyObject *self, PyObject *cls) + { + /* XXX Like datetime_now, this would like to do better than + * XXX 1-second resolution. + */ + struct tm *tm; + time_t timet; + + time(&timet); + tm = gmtime(&timet); + + return PyObject_CallFunction(cls, "llllll", + tm->tm_year + 1900, tm->tm_mon + 1, + tm->tm_mday, tm->tm_hour, tm->tm_min, + tm->tm_sec); + } + /* Well, we say this is equivalent to fromtimestamp(time.time()), and the * only way to be sure of that is to *call* time.time(). That's not *************** *** 541,557 **** static PyMethodDef datetime_methods[] = { /* Class methods: */ ! {"now", (PyCFunction)datetime_now, METH_O | METH_CLASS, ! "Return a new datetime that represents the current time."}, ! {"today", (PyCFunction)datetime_today, METH_O | METH_CLASS, ! "Return a new datetime that represents the current date."}, ! {"fromtimestamp", (PyCFunction)datetime_fromtimestamp, METH_VARARGS | ! METH_CLASS, "timestamp -> local datetime from a POSIX timestamp " "(like time.time())."}, {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp, ! METH_VARARGS | METH_CLASS, "timestamp -> UTC datetime from a POSIX timestamp " "(like time.time())."}, --- 559,581 ---- static PyMethodDef datetime_methods[] = { /* Class methods: */ ! {"now", (PyCFunction)datetime_now, ! METH_O | METH_CLASS, ! "Return a new datetime representing local day and time."}, ! {"utcnow", (PyCFunction)datetime_utcnow, ! METH_O | METH_CLASS, ! "Return a new datetime representing UTC day and time."}, ! {"today", (PyCFunction)datetime_today, ! METH_O | METH_CLASS, ! "Return a new datetime representing local day and time."}, ! ! {"fromtimestamp", (PyCFunction)datetime_fromtimestamp, ! METH_VARARGS | METH_CLASS, "timestamp -> local datetime from a POSIX timestamp " "(like time.time())."}, {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp, ! METH_VARARGS | METH_CLASS, "timestamp -> UTC datetime from a POSIX timestamp " "(like time.time())."}, Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.41 retrieving revision 1.42 diff -C2 -d -r1.41 -r1.42 *** test_both.py 6 Dec 2002 02:17:42 -0000 1.41 --- test_both.py 6 Dec 2002 02:42:06 -0000 1.42 *************** *** 1063,1066 **** --- 1063,1079 ---- self.verify_field_equality(expected, got) + def test_utcnow(self): + import time + + # Call it a succes if utcnow*( and utcfromtimestamp() are within + # a second of each other. + tolerance = timedelta(seconds=1) + for dummy in range(3): + from_now = self.theclass.utcnow() + from_timestamp = self.theclass.utcfromtimestamp(time.time()) + if abs(from_timestamp - from_now) <= tolerance: + break + # Else try again a few times. + self.failUnless(abs(from_timestamp - from_now) <= tolerance) def test_suite(): From tim_one@users.sourceforge.net Fri Dec 6 02:43:04 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 05 Dec 2002 18:43:04 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime test_both.py,1.42,1.43 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv25409 Modified Files: test_both.py Log Message: Typo repair. Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.42 retrieving revision 1.43 diff -C2 -d -r1.42 -r1.43 *** test_both.py 6 Dec 2002 02:42:06 -0000 1.42 --- test_both.py 6 Dec 2002 02:43:02 -0000 1.43 *************** *** 1066,1070 **** import time ! # Call it a succes if utcnow*( and utcfromtimestamp() are within # a second of each other. tolerance = timedelta(seconds=1) --- 1066,1070 ---- import time ! # Call it a succes if utcnow() and utcfromtimestamp() are within # a second of each other. tolerance = timedelta(seconds=1) From tim_one@users.sourceforge.net Fri Dec 6 02:49:22 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 05 Dec 2002 18:49:22 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_datetime.c,1.23,1.24 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv27181 Modified Files: obj_datetime.c Log Message: datetime_today(): Removed unused vrbl. Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.23 retrieving revision 1.24 diff -C2 -d -r1.23 -r1.24 *** obj_datetime.c 6 Dec 2002 02:42:06 -0000 1.23 --- obj_datetime.c 6 Dec 2002 02:49:20 -0000 1.24 *************** *** 226,230 **** PyObject *time; PyObject *time_time; - PyObject *result; double timestamp; --- 226,229 ---- From tim_one@users.sourceforge.net Fri Dec 6 02:55:35 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 05 Dec 2002 18:55:35 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.c,1.42,1.43 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv28541 Modified Files: datetime.c Log Message: Repaired typos in comments. Index: datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.c,v retrieving revision 1.42 retrieving revision 1.43 diff -C2 -d -r1.42 -r1.43 *** datetime.c 5 Dec 2002 05:04:09 -0000 1.42 --- datetime.c 6 Dec 2002 02:55:32 -0000 1.43 *************** *** 149,153 **** } ! /* month, year -> number of days in that month in that year */ static int days_in_month(int year, int month) --- 149,153 ---- } ! /* year, month -> number of days in that month in that year */ static int days_in_month(int year, int month) *************** *** 161,165 **** } ! /* month, year -> number of days in year preceeding first day of month */ static int days_before_month(int year, int month) --- 161,165 ---- } ! /* year, month -> number of days in year preceeding first day of month */ static int days_before_month(int year, int month) From tim_one@users.sourceforge.net Fri Dec 6 04:17:50 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 05 Dec 2002 20:17:50 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_date.c,1.29,1.30 obj_datetime.c,1.24,1.25 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv18826 Modified Files: obj_date.c obj_datetime.c Log Message: Got rid of the C function datetime_today. date_today now passes on the value of time.time() to the correct fromtimestamp class method. This is less efficient, and much less efficient for date.today(), but I don't care -- it's the right way to do it, and should work smoothly with subclasses without more hacks. Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.29 retrieving revision 1.30 diff -C2 -d -r1.29 -r1.30 *** obj_date.c 5 Dec 2002 21:29:36 -0000 1.29 --- obj_date.c 6 Dec 2002 04:17:45 -0000 1.30 *************** *** 224,235 **** } ! /* Return new date from current time. */ static PyObject * date_today(PyObject *self, PyObject *cls) { ! time_t timet; ! time(&timet); ! return date_local_from_time_t(cls, timet); } --- 224,263 ---- } ! /* Return new date from current time. ! * We say this is equivalent to fromtimestamp(time.time()), and the ! * only way to be sure of that is to *call* time.time(). That's not ! * generally the same as calling C's time. ! * XXX Expose the time module's C code in a saner way. ! */ static PyObject * date_today(PyObject *self, PyObject *cls) { ! PyObject *time; /* the time module, and later time.time() */ ! PyObject *time_time; /* time.time */ ! PyObject *result; ! time = PyImport_ImportModule("time"); ! if (time == NULL) ! return NULL; ! ! time_time = PyObject_GetAttrString(time, "time"); ! Py_DECREF(time); ! if (time_time == NULL) ! return NULL; ! ! time = PyObject_CallObject(time_time, NULL); ! Py_DECREF(time_time); ! if (time == NULL) ! return NULL; ! ! /* Note well: today() is a class method, so this may not call ! * date.fromtimestamp. For example, it may call ! * datetime.fromtimestamp. That's why we need all the accuracy ! * time.time() delivers; if someone were gonzo about optimization, ! * date.today() could get away with plain C time(). ! */ ! result = PyObject_CallMethod(cls, "fromtimestamp", "O", time); ! Py_DECREF(time); ! return result; } *************** *** 457,461 **** {"today", (PyCFunction)date_today, METH_O | METH_CLASS, ! "Construct local date corresponing to current day."}, /* Instance methods: */ --- 485,490 ---- {"today", (PyCFunction)date_today, METH_O | METH_CLASS, ! "Current date or datetime: same as " ! "self.__class__.fromtimestamp(time.time())."}, /* Instance methods: */ Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.24 retrieving revision 1.25 diff -C2 -d -r1.24 -r1.25 *** obj_datetime.c 6 Dec 2002 02:49:20 -0000 1.24 --- obj_datetime.c 6 Dec 2002 04:17:48 -0000 1.25 *************** *** 216,252 **** } - /* Well, we say this is equivalent to fromtimestamp(time.time()), and the - * only way to be sure of that is to *call* time.time(). That's not - * generally the same as calling C's time. - * XXX Expose the time module's C code in a saner way. - */ - static PyObject * - datetime_today(PyObject *self, PyObject *cls) - { - PyObject *time; - PyObject *time_time; - double timestamp; - - time = PyImport_ImportModule("time"); - if (time == NULL) - return NULL; - - time_time = PyObject_GetAttrString(time, "time"); - Py_DECREF(time); - if (time_time == NULL) - return NULL; - - time = PyObject_CallObject(time_time, NULL); - Py_DECREF(time_time); - if (time == NULL) - return NULL; - - timestamp = PyFloat_AsDouble(time); - Py_DECREF(time); - if (timestamp == -1.0 && PyErr_Occurred()) - return NULL; - return datetime_from_timestamp(cls, localtime, timestamp); - } - /* datetime arithmetic. */ --- 216,219 ---- *************** *** 565,572 **** METH_O | METH_CLASS, "Return a new datetime representing UTC day and time."}, - - {"today", (PyCFunction)datetime_today, - METH_O | METH_CLASS, - "Return a new datetime representing local day and time."}, {"fromtimestamp", (PyCFunction)datetime_fromtimestamp, --- 532,535 ---- From tim_one@users.sourceforge.net Fri Dec 6 05:13:43 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 05 Dec 2002 21:13:43 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime doc.txt,1.18,1.19 obj_date.c,1.30,1.31 obj_datetime.c,1.25,1.26 test_both.py,1.43,1.44 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv1161 Modified Files: doc.txt obj_date.c obj_datetime.c test_both.py Log Message: Gave datetime a correct timetuple implementation. The tests didn't catch that it was still using the date timetuple() (which zeroes out hours, minutes, and seconds), so beefed up the test of that too. Changed date.strftime() to call the correct timetuple() method for the object passed to it. Added a new test to ensure that strftime is seeing all the fields it should see for a datetime.strftime(). Updated the datetime docs, to near completion. There are still a couple methods that aren't right. Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** doc.txt 6 Dec 2002 02:42:06 -0000 1.18 --- doc.txt 6 Dec 2002 05:13:40 -0000 1.19 *************** *** 311,315 **** - strftime(format) Return a string representing the date, controlled by an explicit ! format string. d.strftime(f) is the same as time.strftime(f, d.timetuple()). --- 311,316 ---- - strftime(format) Return a string representing the date, controlled by an explicit ! format string. Formats referring to hours, minutes or seconds will ! see 0 values. d.strftime(f) is the same as time.strftime(f, d.timetuple()). *************** *** 438,452 **** - pickling - XXX NOTHING BELOW THIS POINT HAS BEEN CHECKED, AND MUCH IS CERTAINLY - XXX WRONG (CUT & PASTE ERRORS MOSTLY) AND/OR MISIMPLEMENTED. - Instance methods: - timetuple() Return a 9-element tuple of the form returned by time.localtime(). ! The hours, minutes and seconds are 0, and the DST flag is -1. ! d.timetuple() is equivalent to (d.year, d.month, d.day, ! 0, 0, 0, # h, m, s d.weekday(), # 0 is Monday d.toordinal() - date(d.year, 1, 1).toordinal() + 1, # day of year --- 439,449 ---- - pickling Instance methods: - timetuple() Return a 9-element tuple of the form returned by time.localtime(). ! The DST flag is -1. d.timetuple() is equivalent to (d.year, d.month, d.day, ! d.hour, d.minute.d.second, d.weekday(), # 0 is Monday d.toordinal() - date(d.year, 1, 1).toordinal() + 1, # day of year *************** *** 455,464 **** - toordinal() Return the proleptic Gregorian ordinal of the date, where January 1 ! of year 1 has ordinal 1. For any date object d, ! date.fromordinal(d.toordinal()) == d. - weekday() Return the day of the week as an integer, where Monday is 0 and ! Sunday is 6. For example, date(2002, 12, 4).weekday() == 2, a Wednesday. See also isoweekday(). --- 452,460 ---- - toordinal() Return the proleptic Gregorian ordinal of the date, where January 1 ! of year 1 has ordinal 1. - weekday() Return the day of the week as an integer, where Monday is 0 and ! Sunday is 6. For example, datetime(2002, 12, 4).weekday() == 2, a Wednesday. See also isoweekday(). *************** *** 466,470 **** - isoweekday() Return the day of the week as an integer, where Monday is 1 and ! Sunday is 7. For example, date(2002, 12, 4).isoweekday() == 3, a Wednesday. See also weekday() and isocalendar(). --- 462,466 ---- - isoweekday() Return the day of the week as an integer, where Monday is 1 and ! Sunday is 7. For example, datetime(2002, 12, 4).isoweekday() == 3, a Wednesday. See also weekday() and isocalendar(). *************** *** 487,493 **** 2004, so that ! date(2003, 12, 29).isocalendar() == (2004, 1, 1) ! date(2004, 1, 4).isocalendar() == (2004, 1, 7) - isoformat() Return a string representing the date in ISO 8601 format, --- 483,490 ---- 2004, so that ! datetime(2003, 12, 29).isocalendar() == (2004, 1, 1) ! datetime(2004, 1, 4).isocalendar() == (2004, 1, 7) + XXX isoformat() needs work. - isoformat() Return a string representing the date in ISO 8601 format, *************** *** 496,499 **** --- 493,497 ---- str(d) is equivalent to d.isoformat(). + XXX ctime() needs work. - ctime() Return a string representing the date, for example *************** *** 502,507 **** - strftime(format) ! Return a string representing the date, controlled by an explicit ! format string. d.strftime(f) is the same as time.strftime(f, d.timetuple()). --- 500,505 ---- - strftime(format) ! Return a string representing the date and time, controlled by an ! explicit format string. d.strftime(f) is the same as time.strftime(f, d.timetuple()). Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.30 retrieving revision 1.31 diff -C2 -d -r1.30 -r1.31 *** obj_date.c 6 Dec 2002 04:17:45 -0000 1.30 --- obj_date.c 6 Dec 2002 05:13:40 -0000 1.31 *************** *** 136,155 **** date_timetuple(PyDateTime_Date *self) { - PyObject *result; const int year = GET_YEAR(self); const int month = GET_MONTH(self); const int day = GET_DAY(self); ! result = Py_BuildValue("iiiiiiiii", ! year, ! month, ! day, ! 0, ! 0, ! 0, ! weekday(year, month, day), ! days_before_month(year, month) + day, ! -1); ! return result; } --- 136,149 ---- date_timetuple(PyDateTime_Date *self) { const int year = GET_YEAR(self); const int month = GET_MONTH(self); const int day = GET_DAY(self); ! return Py_BuildValue("iiiiiiiii", ! year, month, day, ! 0, 0, 0, ! weekday(year, month, day), ! days_before_month(year, month) + day, ! -1); } *************** *** 394,402 **** date_strftime(PyDateTime_Date *self, PyObject *format) { PyObject *result; ! PyObject *tuple = date_timetuple(self); if (tuple == NULL) return NULL; result = format_strftime(format, tuple); Py_DECREF(tuple); --- 388,400 ---- date_strftime(PyDateTime_Date *self, PyObject *format) { + /* This method can be inherited, and needs to call the + * timetuple() method appropriate to self's class. + */ PyObject *result; ! PyObject *tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()"); if (tuple == NULL) return NULL; + assert(PyTuple_Size(tuple) == 9); result = format_strftime(format, tuple); Py_DECREF(tuple); Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.25 retrieving revision 1.26 diff -C2 -d -r1.25 -r1.26 *** obj_datetime.c 6 Dec 2002 04:17:48 -0000 1.25 --- obj_datetime.c 6 Dec 2002 05:13:40 -0000 1.26 *************** *** 466,469 **** --- 466,486 ---- } + static PyObject * + datetime_timetuple(PyDateTime_DateTime *self) + { + const int year = GET_YEAR(self); + const int month = GET_MONTH(self); + const int day = GET_DAY(self); + + return Py_BuildValue("iiiiiiiii", + year, month, day, + GET_HOUR(self), + GET_MINUTE(self), + GET_SECOND(self), + weekday(year, month, day), + days_before_month(year, month) + day, + -1); + } + /* Pickle support. Quite a maze! */ *************** *** 544,547 **** --- 561,567 ---- /* Instance methods: */ + {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS, + "Return time tuple, compatible with time.localtime()."}, + {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS, "Return ctime() style string."}, Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.43 retrieving revision 1.44 diff -C2 -d -r1.43 -r1.44 *** test_both.py 6 Dec 2002 02:43:02 -0000 1.43 --- test_both.py 6 Dec 2002 05:13:40 -0000 1.44 *************** *** 13,16 **** --- 13,20 ---- # work under both implementations will be *moved* from test_datetime and # test_cdatetime into this file. + # Later: test_cdatetime.py no longer exists. test_datetime.py still + # contains tests of things that exist in the Python implementation but + # not yet in the C implementation. I don't think anyone was within a + # factor of 20 of guessing how many of those there were! import sys *************** *** 1066,1070 **** import time ! # Call it a succes if utcnow() and utcfromtimestamp() are within # a second of each other. tolerance = timedelta(seconds=1) --- 1070,1074 ---- import time ! # Call it a success if utcnow() and utcfromtimestamp() are within # a second of each other. tolerance = timedelta(seconds=1) *************** *** 1076,1079 **** --- 1080,1100 ---- # Else try again a few times. self.failUnless(abs(from_timestamp - from_now) <= tolerance) + + def test_more_timetuple(self): + # This tests fields beyond those tested by the TestDate.test_timetuple. + t = self.theclass(2004, 12, 31, 6, 22, 33) + self.assertEqual(t.timetuple(), (2004, 12, 31, 6, 22, 33, 4, 366, -1)) + self.assertEqual(t.timetuple(), + (t.year, t.month, t.day, + t.hour, t.minute, t.second, + t.weekday(), + t.toordinal() - date(t.year, 1, 1).toordinal() + 1, + -1)) + + def test_more_strftime(self): + # This tests fields beyond those tested by the TestDate.test_strftime. + t = self.theclass(2004, 12, 31, 6, 22, 33) + self.assertEqual(t.strftime("%m %d %y %S %M %H %j"), + "12 31 04 33 22 06 366") def test_suite(): From tim_one@users.sourceforge.net Fri Dec 6 05:21:04 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 05 Dec 2002 21:21:04 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime doc.txt,1.19,1.20 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv3448 Modified Files: doc.txt Log Message: Fixed a typo, and lopped off parts of the datetime docs by referring to the corresponding date docs. Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.19 retrieving revision 1.20 diff -C2 -d -r1.19 -r1.20 *** doc.txt 6 Dec 2002 05:13:40 -0000 1.19 --- doc.txt 6 Dec 2002 05:21:02 -0000 1.20 *************** *** 445,449 **** The DST flag is -1. d.timetuple() is equivalent to (d.year, d.month, d.day, ! d.hour, d.minute.d.second, d.weekday(), # 0 is Monday d.toordinal() - date(d.year, 1, 1).toordinal() + 1, # day of year --- 445,449 ---- The DST flag is -1. d.timetuple() is equivalent to (d.year, d.month, d.day, ! d.hour, d.minute, d.second, d.weekday(), # 0 is Monday d.toordinal() - date(d.year, 1, 1).toordinal() + 1, # day of year *************** *** 451,488 **** - toordinal() ! Return the proleptic Gregorian ordinal of the date, where January 1 ! of year 1 has ordinal 1. - weekday() Return the day of the week as an integer, where Monday is 0 and ! Sunday is 6. For example, datetime(2002, 12, 4).weekday() == 2, a ! Wednesday. See also isoweekday(). - isoweekday() Return the day of the week as an integer, where Monday is 1 and ! Sunday is 7. For example, datetime(2002, 12, 4).isoweekday() == 3, a ! Wednesday. See also weekday() and isocalendar(). - isocalendar() ! Return a 3-tuple, (ISO year, ISO week number, ISO weekday). ! ! The ISO calendar is a widely used variant of the Gregorian calendar. ! See ! for a good explanation. ! ! The ISO year consists of 52 or 53 full weeks, and where a week starts ! on a Monday and ends on a Sunday. The first week of an ISO year is ! the first (Gregorian) calendar week of a year containing a Thursday. ! This is called week number 1, and the ISO year of that Thursday is ! the same as its Gregorian year. ! ! For example, 2004 begins on a Thursday, so the first week of ISO ! year 2004 begins on Monday, 29 Dec 2003 and ends on Sunday, 4 Jan ! 2004, so that ! ! datetime(2003, 12, 29).isocalendar() == (2004, 1, 1) ! datetime(2004, 1, 4).isocalendar() == (2004, 1, 7) XXX isoformat() needs work. --- 451,470 ---- - toordinal() ! Return the proleptic Gregorian ordinal of the date. The same as ! date.toordinal(). - weekday() Return the day of the week as an integer, where Monday is 0 and ! Sunday is 6. The same as date.weekday(). See also isoweekday(). - isoweekday() Return the day of the week as an integer, where Monday is 1 and ! Sunday is 7. The same as date.isoweekday(). See also weekday() and isocalendar(). - isocalendar() ! Return a 3-tuple, (ISO year, ISO week number, ISO weekday). The ! same as date.isocalendar(). XXX isoformat() needs work. From tim_one@users.sourceforge.net Fri Dec 6 05:26:54 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Thu, 05 Dec 2002 21:26:54 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_date.c,1.31,1.32 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv4831 Modified Files: obj_date.c Log Message: Wrapped long line. Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.31 retrieving revision 1.32 diff -C2 -d -r1.31 -r1.32 *** obj_date.c 6 Dec 2002 05:13:40 -0000 1.31 --- obj_date.c 6 Dec 2002 05:26:52 -0000 1.32 *************** *** 392,396 **** */ PyObject *result; ! PyObject *tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()"); if (tuple == NULL) --- 392,397 ---- */ PyObject *result; ! PyObject *tuple = PyObject_CallMethod((PyObject *)self, ! "timetuple", "()"); if (tuple == NULL) From doerwalter@users.sourceforge.net Fri Dec 6 10:09:19 2002 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Fri, 06 Dec 2002 02:09:19 -0800 Subject: [Python-checkins] python/dist/src/Doc/api abstract.tex,1.20,1.21 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/api In directory sc8-pr-cvs1:/tmp/cvs-serv29453/Doc/api Modified Files: abstract.tex Log Message: Document that the second argument to PyObject_IsInstance may be a tuple. This closes SF patch http://www.python.org/sf/649095 Backport to release22-maint will follow. Index: abstract.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/api/abstract.tex,v retrieving revision 1.20 retrieving revision 1.21 diff -C2 -d -r1.20 -r1.21 *** abstract.tex 19 Nov 2002 20:49:12 -0000 1.20 --- abstract.tex 6 Dec 2002 10:09:16 -0000 1.21 *************** *** 176,185 **** \code{-1} and sets an exception. If \var{cls} is a type object rather than a class object, \cfunction{PyObject_IsInstance()} ! returns \code{1} if \var{inst} is of type \var{cls}. If \var{inst} ! is not a class instance and \var{cls} is neither a type object or ! class object, \var{inst} must have a \member{__class__} attribute --- the class relationship of the value of that attribute with \var{cls} will be used to determine the result of this function. \versionadded{2.1} \end{cfuncdesc} --- 176,189 ---- \code{-1} and sets an exception. If \var{cls} is a type object rather than a class object, \cfunction{PyObject_IsInstance()} ! returns \code{1} if \var{inst} is of type \var{cls}. If \var{cls} ! is a tuple, the check will be done against every entry in \var{cls}. ! The result will be \code{1} when at least one of the checks returns ! \code{1}, otherwise it will be \code{0}. If \var{inst} is not a class ! instance and \var{cls} is neither a type object, nor a class object, ! nor a tuple, \var{inst} must have a \member{__class__} attribute --- the class relationship of the value of that attribute with \var{cls} will be used to determine the result of this function. \versionadded{2.1} + \versionchanged[Support for a tuple as the second argument added]{2.2} \end{cfuncdesc} From doerwalter@users.sourceforge.net Fri Dec 6 10:17:38 2002 From: doerwalter@users.sourceforge.net (doerwalter@users.sourceforge.net) Date: Fri, 06 Dec 2002 02:17:38 -0800 Subject: [Python-checkins] python/dist/src/Doc/api abstract.tex,1.8.6.7,1.8.6.8 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/api In directory sc8-pr-cvs1:/tmp/cvs-serv3621/Doc/api Modified Files: Tag: release22-maint abstract.tex Log Message: Backport version 1.21: Document that the second argument to PyObject_IsInstance may be a tuple. This closes SF patch http://www.python.org/sf/649095 Index: abstract.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/api/abstract.tex,v retrieving revision 1.8.6.7 retrieving revision 1.8.6.8 diff -C2 -d -r1.8.6.7 -r1.8.6.8 *** abstract.tex 8 Sep 2002 04:42:16 -0000 1.8.6.7 --- abstract.tex 6 Dec 2002 10:17:35 -0000 1.8.6.8 *************** *** 172,184 **** \begin{cfuncdesc}{int}{PyObject_IsInstance}{PyObject *inst, PyObject *cls} ! Return \code{1} if \var{inst} is an instance of the class \var{cls} ! or a subclass of \var{cls}. If \var{cls} is a type object rather ! than a class object, \cfunction{PyObject_IsInstance()} returns ! \code{1} if \var{inst} is of type \var{cls}. If \var{inst} is not a ! class instance and \var{cls} is neither a type object or class ! object, \var{inst} must have a \member{__class__} attribute --- the ! class relationship of the value of that attribute with \var{cls} ! will be used to determine the result of this function. \versionadded{2.1} \end{cfuncdesc} --- 172,189 ---- \begin{cfuncdesc}{int}{PyObject_IsInstance}{PyObject *inst, PyObject *cls} ! Returns \code{1} if \var{inst} is an instance of the class \var{cls} ! or a subclass of \var{cls}, or \code{0} if not. On error, returns ! \code{-1} and sets an exception. If \var{cls} is a type object ! rather than a class object, \cfunction{PyObject_IsInstance()} ! returns \code{1} if \var{inst} is of type \var{cls}. If \var{cls} ! is a tuple, the check will be done against every entry in \var{cls}. ! The result will be \code{1} when at least one of the checks returns ! \code{1}, otherwise it will be \code{0}. If \var{inst} is not a class ! instance and \var{cls} is neither a type object, nor a class object, ! nor a tuple, \var{inst} must have a \member{__class__} attribute ! --- the class relationship of the value of that attribute with ! \var{cls} will be used to determine the result of this function. \versionadded{2.1} + \versionchanged[Support for a tuple as the second argument added]{2.2} \end{cfuncdesc} From loewis@users.sourceforge.net Fri Dec 6 10:33:47 2002 From: loewis@users.sourceforge.net (loewis@users.sourceforge.net) Date: Fri, 06 Dec 2002 02:33:47 -0800 Subject: [Python-checkins] python/dist/src/Demo/tix tixwidgets.py,1.7,1.8 Message-ID: Update of /cvsroot/python/python/dist/src/Demo/tix In directory sc8-pr-cvs1:/tmp/cvs-serv13675/Demo/tix Modified Files: tixwidgets.py Log Message: Patch #649184: Update to tix-8.1.4 RC3. Index: tixwidgets.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Demo/tix/tixwidgets.py,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** tixwidgets.py 14 Nov 2002 02:44:08 -0000 1.7 --- tixwidgets.py 6 Dec 2002 10:33:45 -0000 1.8 *************** *** 1,4 **** --- 1,5 ---- # -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- # + # Id: tixwidgets.py,v 1.7 2002/11/14 02:44:08 nnorwitz Exp # $Id$ # *************** *** 475,481 **** options='label.padX 4' ! sls = Tix.LabelFrame(w, label='tixScrolledListBox', options=options) ! swn = Tix.LabelFrame(w, label='tixScrolledWindow', options=options) ! stx = Tix.LabelFrame(w, label='tixScrolledText', options=options) MkSList(sls.frame) --- 476,482 ---- options='label.padX 4' ! sls = Tix.LabelFrame(w, label='Tix.ScrolledListBox', options=options) ! swn = Tix.LabelFrame(w, label='Tix.ScrolledWindow', options=options) ! stx = Tix.LabelFrame(w, label='Tix.ScrolledText', options=options) MkSList(sls.frame) *************** *** 605,610 **** options='label.padX 4' ! pane = Tix.LabelFrame(w, label='tixPanedWindow', options=options) ! note = Tix.LabelFrame(w, label='tixNoteBook', options=options) MkPanedWindow(pane.frame) --- 606,611 ---- options='label.padX 4' ! pane = Tix.LabelFrame(w, label='Tix.PanedWindow', options=options) ! note = Tix.LabelFrame(w, label='Tix.NoteBook', options=options) MkPanedWindow(pane.frame) *************** *** 717,722 **** options = "label.padX 4" ! dir = Tix.LabelFrame(w, label='tixDirList', options=options) ! fsbox = Tix.LabelFrame(w, label='tixExFileSelectBox', options=options) MkDirListWidget(dir.frame) MkExFileWidget(fsbox.frame) --- 718,723 ---- options = "label.padX 4" ! dir = Tix.LabelFrame(w, label='Tix.DirList', options=options) ! fsbox = Tix.LabelFrame(w, label='Tix.ExFileSelectBox', options=options) MkDirListWidget(dir.frame) MkExFileWidget(fsbox.frame) From loewis@users.sourceforge.net Fri Dec 6 10:33:47 2002 From: loewis@users.sourceforge.net (loewis@users.sourceforge.net) Date: Fri, 06 Dec 2002 02:33:47 -0800 Subject: [Python-checkins] python/dist/src/Lib/lib-tk Tix.py,1.12,1.13 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/lib-tk In directory sc8-pr-cvs1:/tmp/cvs-serv13675/Lib/lib-tk Modified Files: Tix.py Log Message: Patch #649184: Update to tix-8.1.4 RC3. Index: Tix.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/lib-tk/Tix.py,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** Tix.py 14 Nov 2002 02:43:40 -0000 1.12 --- Tix.py 6 Dec 2002 10:33:44 -0000 1.13 *************** *** 35,40 **** import _tkinter # If this fails your Python may not be configured for Tk - # TixVersion = float(tkinter.TIX_VERSION) # If this fails your Python may not be configured for Tix - # WARNING - TixVersion is a limited precision floating point number # Some more constants (for consistency with Tkinter) --- 35,38 ---- *************** *** 242,246 **** z = z + (self.tk.getint(x),) return z ! self.tk.call('tixForm', 'grid', self._w, xsize, ysize) def info(self, option=None): --- 240,244 ---- z = z + (self.tk.getint(x),) return z ! return self.tk.call('tixForm', 'grid', self._w, xsize, ysize) def info(self, option=None): *************** *** 498,501 **** --- 496,500 ---- message Message""" + # FIXME: It should inherit -superclass tixShell def __init__(self, master=None, cnf={}, **kw): # static seem to be -installcolormap -initwait -statusbar -cursor *************** *** 550,553 **** --- 549,553 ---- cross Button : present if created with the fancy option""" + # FIXME: It should inherit -superclass tixLabelWidget def __init__ (self, master=None, cnf={}, **kw): TixWidget.__init__(self, master, 'tixComboBox', *************** *** 591,594 **** --- 591,595 ---- label Label""" + # FIXME: It should inherit -superclass tixLabelWidget def __init__ (self, master=None, cnf={}, **kw): TixWidget.__init__(self, master, 'tixControl', ['options'], cnf, kw) *************** *** 621,624 **** --- 622,626 ---- vsb Scrollbar""" + # FIXME: It should inherit -superclass tixScrolledHList def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixDirList', ['options'], cnf, kw) *************** *** 642,645 **** --- 644,648 ---- vsb Scrollbar""" + # FIXME: It should inherit -superclass tixScrolledHList def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixDirTree', ['options'], cnf, kw) *************** *** 713,716 **** --- 716,720 ---- dirbox DirSelectDialog""" + # FIXME: It should inherit -superclass tixDialogShell def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixDirSelectDialog', *************** *** 735,738 **** --- 739,743 ---- fsbox ExFileSelectBox""" + # FIXME: It should inherit -superclass tixDialogShell def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixExFileSelectDialog', *************** *** 782,785 **** --- 787,791 ---- fsbox FileSelectBox""" + # FIXME: It should inherit -superclass tixStdDialogShell def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixFileSelectDialog', *************** *** 805,808 **** --- 811,815 ---- entry Entry""" + # FIXME: It should inherit -superclass tixLabelWidget def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixFileEntry', *************** *** 815,819 **** def file_dialog(self): ! # XXX return python object pass --- 822,826 ---- def file_dialog(self): ! # FIXME: return python object pass *************** *** 1004,1008 **** class InputOnly(TixWidget): ! """InputOnly - Invisible widget. Subwidgets - None""" --- 1011,1015 ---- class InputOnly(TixWidget): ! """InputOnly - Invisible widget. Unix only. Subwidgets - None""" *************** *** 1132,1136 **** class NoteBookFrame(TixWidget): ! """Will be added when Tix documentation is available !!!""" pass --- 1139,1143 ---- class NoteBookFrame(TixWidget): ! # FIXME: This is dangerous to expose to be called on its own. pass *************** *** 1224,1227 **** --- 1231,1235 ---- menu Menu""" + # FIXME: It should inherit -superclass tixShell def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixPopupMenu', ['options'], cnf, kw) *************** *** 1240,1244 **** class ResizeHandle(TixWidget): """Internal widget to draw resize handles on Scrolled widgets.""" ! def __init__(self, master, cnf={}, **kw): # There seems to be a Tix bug rejecting the configure method --- 1248,1253 ---- class ResizeHandle(TixWidget): """Internal widget to draw resize handles on Scrolled widgets.""" ! # FIXME: This is dangerous to expose to be called on its own. ! # Perhaps rename ResizeHandle to _ResizeHandle def __init__(self, master, cnf={}, **kw): # There seems to be a Tix bug rejecting the configure method *************** *** 1266,1269 **** --- 1275,1279 ---- """ScrolledHList - HList with automatic scrollbars.""" + # FIXME: It should inherit -superclass tixScrolledWidget def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixScrolledHList', ['options'], *************** *** 1276,1279 **** --- 1286,1290 ---- """ScrolledListBox - Listbox with automatic scrollbars.""" + # FIXME: It should inherit -superclass tixScrolledWidget def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixScrolledListBox', ['options'], cnf, kw) *************** *** 1285,1288 **** --- 1296,1300 ---- """ScrolledText - Text with automatic scrollbars.""" + # FIXME: It should inherit -superclass tixScrolledWidget def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixScrolledText', ['options'], cnf, kw) *************** *** 1294,1297 **** --- 1306,1310 ---- """ScrolledTList - TList with automatic scrollbars.""" + # FIXME: It should inherit -superclass tixScrolledWidget def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixScrolledTList', ['options'], *************** *** 1304,1307 **** --- 1317,1321 ---- """ScrolledWindow - Window with automatic scrollbars.""" + # FIXME: It should inherit -superclass tixScrolledWidget def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixScrolledWindow', ['options'], cnf, kw) *************** *** 1316,1319 **** --- 1330,1334 ---- Subwidgets are buttons added dynamically using the add method.""" + # FIXME: It should inherit -superclass tixLabelWidget def __init__(self, master, cnf={}, **kw): TixWidget.__init__(self, master, 'tixSelect', *************** *** 1348,1351 **** --- 1363,1367 ---- Subwidgets - None""" + # FIXME: It should inherit from Shell def __init__ (self,master=None,cnf={}, **kw): TixWidget.__init__(self, master, *************** *** 1475,1478 **** --- 1491,1495 ---- the view of the tree by opening or closing parts of the tree.""" + # FIXME: It should inherit -superclass tixScrolledWidget def __init__(self, master=None, cnf={}, **kw): TixWidget.__init__(self, master, 'tixTree', *************** *** 1483,1498 **** --- 1500,1531 ---- def autosetmode(self): + '''This command calls the setmode method for all the entries in this + Tree widget: if an entry has no child entries, its mode is set to + none. Otherwise, if the entry has any hidden child entries, its mode is + set to open; otherwise its mode is set to close.''' self.tk.call(self._w, 'autosetmode') def close(self, entrypath): + '''Close the entry given by entryPath if its mode is close.''' self.tk.call(self._w, 'close', entrypath) def getmode(self, entrypath): + '''Returns the current mode of the entry given by entryPath.''' return self.tk.call(self._w, 'getmode', entrypath) def open(self, entrypath): + '''Open the entry given by entryPath if its mode is open.''' self.tk.call(self._w, 'open', entrypath) def setmode(self, entrypath, mode='none'): + '''This command is used to indicate whether the entry given by + entryPath has children entries and whether the children are visible. mode + must be one of open, close or none. If mode is set to open, a (+) + indicator is drawn next the the entry. If mode is set to close, a (-) + indicator is drawn next the the entry. If mode is set to none, no + indicators will be drawn for this entry. The default mode is none. The + open mode indicates the entry has hidden children and this entry can be + opened by the user. The close mode indicates that all the children of the + entry are now visible and the entry can be closed by the user.''' self.tk.call(self._w, 'setmode', entrypath, mode) *************** *** 1505,1509 **** capable of handling many more items than checkbuttons or radiobuttons. """ ! def __init__(self, master=None, cnf={}, **kw): TixWidget.__init__(self, master, 'tixCheckList', --- 1538,1542 ---- capable of handling many more items than checkbuttons or radiobuttons. """ ! # FIXME: It should inherit -superclass tixTree def __init__(self, master=None, cnf={}, **kw): TixWidget.__init__(self, master, 'tixCheckList', *************** *** 1514,1536 **** def autosetmode(self): self.tk.call(self._w, 'autosetmode') def close(self, entrypath): self.tk.call(self._w, 'close', entrypath) def getmode(self, entrypath): return self.tk.call(self._w, 'getmode', entrypath) def open(self, entrypath): self.tk.call(self._w, 'open', entrypath) def getselection(self, mode='on'): ! '''Mode can be on, off, default''' ! self.tk.call(self._w, 'getselection', mode) def getstatus(self, entrypath): ! self.tk.call(self._w, 'getstatus', entrypath) def setstatus(self, entrypath, mode='on'): self.tk.call(self._w, 'setstatus', entrypath, mode) --- 1547,1582 ---- def autosetmode(self): + '''This command calls the setmode method for all the entries in this + Tree widget: if an entry has no child entries, its mode is set to + none. Otherwise, if the entry has any hidden child entries, its mode is + set to open; otherwise its mode is set to close.''' self.tk.call(self._w, 'autosetmode') def close(self, entrypath): + '''Close the entry given by entryPath if its mode is close.''' self.tk.call(self._w, 'close', entrypath) def getmode(self, entrypath): + '''Returns the current mode of the entry given by entryPath.''' return self.tk.call(self._w, 'getmode', entrypath) def open(self, entrypath): + '''Open the entry given by entryPath if its mode is open.''' self.tk.call(self._w, 'open', entrypath) def getselection(self, mode='on'): ! '''Returns a list of items whose status matches status. If status is ! not specified, the list of items in the "on" status will be returned. ! Mode can be on, off, default''' ! c = self.tk.split(self.tk.call(self._w, 'getselection', mode)) ! return self.tk.splitlist(c) def getstatus(self, entrypath): ! '''Returns the current status of entryPath.''' ! return self.tk.call(self._w, 'getstatus', entrypath) def setstatus(self, entrypath, mode='on'): + '''Sets the status of entryPath to be status. A bitmap will be + displayed next to the entry its status is on, off or default.''' self.tk.call(self._w, 'setstatus', entrypath, mode) *************** *** 1691,1694 **** --- 1737,1741 ---- # Still to be done: + # tixIconView class CObjView(TixWidget): """This file implements the Canvas Object View widget. This is a base *************** *** 1698,1700 **** --- 1745,1754 ---- to see all the objects. """ + # FIXME: It should inherit -superclass tixScrolledWidget + pass + + class ScrolledGrid(TixWidget): + '''Scrolled Grid widgets''' + + # FIXME: It should inherit -superclass tixScrolledWidget pass From loewis@users.sourceforge.net Fri Dec 6 10:25:04 2002 From: loewis@users.sourceforge.net (loewis@users.sourceforge.net) Date: Fri, 06 Dec 2002 02:25:04 -0800 Subject: [Python-checkins] python/dist/src setup.py,1.121,1.122 Message-ID: Update of /cvsroot/python/python/dist/src In directory sc8-pr-cvs1:/tmp/cvs-serv10334 Modified Files: setup.py Log Message: Search in standard library and include dirs for Sleepycat stuff. Fixes #590377. Index: setup.py =================================================================== RCS file: /cvsroot/python/python/dist/src/setup.py,v retrieving revision 1.121 retrieving revision 1.122 diff -C2 -d -r1.121 -r1.122 *** setup.py 27 Nov 2002 13:43:46 -0000 1.121 --- setup.py 6 Dec 2002 10:25:02 -0000 1.122 *************** *** 4,8 **** __version__ = "$Revision$" ! import sys, os, getopt, imp from distutils import sysconfig from distutils import text_file --- 4,8 ---- __version__ = "$Revision$" ! import sys, os, getopt, imp, re from distutils import sysconfig from distutils import text_file *************** *** 445,455 **** # similar functionality (but slower of course) implemented in Python. ! # Berkeley DB interface. # ! # This requires the Berkeley DB code, see ! # ftp://ftp.cs.berkeley.edu/pub/4bsd/db.1.85.tar.gz # ! # (See http://pybsddb.sourceforge.net/ for an interface to ! # Berkeley DB 3.x.) # when sorted in reverse order, keys for this dict must appear in the --- 445,458 ---- # similar functionality (but slower of course) implemented in Python. ! # Sleepycat Berkeley DB interface. # ! # This requires the Sleepycat DB code, see ! # http://www.sleepycat.com/ The earliest supported version of ! # that library is 3.0, the latest supported version is 4.0 ! # (4.1 is specifically not supported, as that changes the ! # semantics of transactional databases). A list of available ! # releases can be found at # ! # http://www.sleepycat.com/update/index.html # when sorted in reverse order, keys for this dict must appear in the *************** *** 459,466 **** 'libdirs': ('/usr/local/BerkeleyDB.4.0/lib', '/usr/local/lib', - '/usr/lib', '/opt/sfw', '/sw/lib', - '/lib', ), 'incdirs': ('/usr/local/BerkeleyDB.4.0/include', --- 462,467 ---- *************** *** 469,474 **** '/sw/include/db4', '/usr/include/db4', ! ), ! 'incs': ('db.h',)}, 'db3': {'libs': ('db-3.3', 'db-3.2', 'db-3.1', 'db-3.0'), 'libdirs': ('/usr/local/BerkeleyDB.3.3/lib', --- 470,474 ---- '/sw/include/db4', '/usr/include/db4', ! )}, 'db3': {'libs': ('db-3.3', 'db-3.2', 'db-3.1', 'db-3.0'), 'libdirs': ('/usr/local/BerkeleyDB.3.3/lib', *************** *** 479,484 **** '/opt/sfw', '/sw/lib', - '/usr/lib', - '/lib', ), 'incdirs': ('/usr/local/BerkeleyDB.3.3/include', --- 479,482 ---- *************** *** 490,495 **** '/sw/include/db3', '/usr/include/db3', ! ), ! 'incs': ('db.h',)}, } --- 488,492 ---- '/sw/include/db3', '/usr/include/db3', ! )}, } *************** *** 498,514 **** db_search_order.reverse() - find_lib_file = self.compiler.find_library_file class found(Exception): pass try: for dbkey in db_search_order: dbd = db_try_this[dbkey] for dblib in dbd['libs']: ! for dbinc in dbd['incs']: ! db_incs = find_file(dbinc, [], dbd['incdirs']) ! dblib_dir = find_lib_file(dbd['libdirs'], dblib) ! if db_incs and dblib_dir: ! dblib_dir = os.path.dirname(dblib_dir) ! dblibs = [dblib] ! raise found except found: dblibs = [dblib] --- 495,524 ---- db_search_order.reverse() class found(Exception): pass try: + # See whether there is a Sleepycat header in the standard + # search path. + std_dbinc = None + for d in inc_dirs: + f = os.path.join(d, "db.h") + if os.path.exists(f): + f = open(f).read() + m = re.search(r"#define\WDB_VERSION_MAJOR\W([1-9]+)", f) + if m: + std_dbinc = 'db' + m.group(1) for dbkey in db_search_order: dbd = db_try_this[dbkey] for dblib in dbd['libs']: ! # Prefer version-specific includes over standard ! # include locations. ! db_incs = find_file('db.h', [], dbd['incdirs']) ! dblib_dir = find_library_file(self.compiler, ! dblib, ! lib_dirs, ! list(dbd['libdirs'])) ! if (db_incs or dbkey == std_dbinc) and \ ! dblib_dir is not None: ! dblibs = [dblib] ! raise found except found: dblibs = [dblib] *************** *** 522,527 **** # an NFS server that goes away). exts.append(Extension('_bsddb', ['_bsddb.c'], ! library_dirs=[dblib_dir], ! runtime_library_dirs=[dblib_dir], include_dirs=db_incs, libraries=dblibs)) --- 532,537 ---- # an NFS server that goes away). exts.append(Extension('_bsddb', ['_bsddb.c'], ! library_dirs=dblib_dir, ! runtime_library_dirs=dblib_dir, include_dirs=db_incs, libraries=dblibs)) From loewis@users.sourceforge.net Fri Dec 6 12:49:19 2002 From: loewis@users.sourceforge.net (loewis@users.sourceforge.net) Date: Fri, 06 Dec 2002 04:49:19 -0800 Subject: [Python-checkins] python/dist/src/Include pyerrors.h,2.62,2.63 Message-ID: Update of /cvsroot/python/python/dist/src/Include In directory sc8-pr-cvs1:/tmp/cvs-serv11610/Include Modified Files: pyerrors.h Log Message: Patch #614055: Support OpenVMS. Index: pyerrors.h =================================================================== RCS file: /cvsroot/python/python/dist/src/Include/pyerrors.h,v retrieving revision 2.62 retrieving revision 2.63 diff -C2 -d -r2.62 -r2.63 *** pyerrors.h 21 Nov 2002 20:08:33 -0000 2.62 --- pyerrors.h 6 Dec 2002 12:48:44 -0000 2.63 *************** *** 63,66 **** --- 63,69 ---- PyAPI_DATA(PyObject *) PyExc_WindowsError; #endif + #ifdef __VMS + extern DL_IMPORT(PyObject *) PyExc_VMSError; + #endif PyAPI_DATA(PyObject *) PyExc_MemoryErrorInst; From loewis@users.sourceforge.net Fri Dec 6 12:49:22 2002 From: loewis@users.sourceforge.net (loewis@users.sourceforge.net) Date: Fri, 06 Dec 2002 04:49:22 -0800 Subject: [Python-checkins] python/dist/src/Misc ACKS,1.218,1.219 NEWS,1.552,1.553 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv11610/Misc Modified Files: ACKS NEWS Log Message: Patch #614055: Support OpenVMS. Index: ACKS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/ACKS,v retrieving revision 1.218 retrieving revision 1.219 diff -C2 -d -r1.218 -r1.219 *** ACKS 25 Nov 2002 21:13:13 -0000 1.218 --- ACKS 6 Dec 2002 12:48:46 -0000 1.219 *************** *** 406,409 **** --- 406,410 ---- Christopher J. Phoenix Neale Pickett + Jean-François Piéronne Dan Pierson Martijn Pieters Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.552 retrieving revision 1.553 diff -C2 -d -r1.552 -r1.553 *** NEWS 3 Dec 2002 06:16:08 -0000 1.552 --- NEWS 6 Dec 2002 12:48:47 -0000 1.553 *************** *** 827,830 **** --- 827,832 ---- ------------- + - OpenVMS is now supported. + - AtheOS is now supported. From loewis@users.sourceforge.net Fri Dec 6 12:49:26 2002 From: loewis@users.sourceforge.net (loewis@users.sourceforge.net) Date: Fri, 06 Dec 2002 04:49:26 -0800 Subject: [Python-checkins] python/dist/src/Objects stringobject.c,2.197,2.198 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv11610/Objects Modified Files: stringobject.c Log Message: Patch #614055: Support OpenVMS. Index: stringobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/stringobject.c,v retrieving revision 2.197 retrieving revision 2.198 diff -C2 -d -r2.197 -r2.198 *** stringobject.c 18 Nov 2002 16:09:38 -0000 2.197 --- stringobject.c 6 Dec 2002 12:48:52 -0000 2.198 *************** *** 766,770 **** } if (flags & Py_PRINT_RAW) { ! fwrite(op->ob_sval, 1, (int) op->ob_size, fp); return 0; } --- 766,774 ---- } if (flags & Py_PRINT_RAW) { ! #ifdef __VMS ! if (op->ob_size) fwrite(op->ob_sval, (int) op->ob_size, 1, fp); ! #else ! fwrite(op->ob_sval, 1, (int) op->ob_size, fp); ! #endif return 0; } From loewis@users.sourceforge.net Fri Dec 6 12:49:27 2002 From: loewis@users.sourceforge.net (loewis@users.sourceforge.net) Date: Fri, 06 Dec 2002 04:49:27 -0800 Subject: [Python-checkins] python/dist/src/Modules _hotshot.c,1.30,1.31 getbuildinfo.c,2.8,2.9 getpath.c,1.42,1.43 main.c,1.70,1.71 posixmodule.c,2.273,2.274 pwdmodule.c,1.36,1.37 socketmodule.c,1.246,1.247 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv11610/Modules Modified Files: _hotshot.c getbuildinfo.c getpath.c main.c posixmodule.c pwdmodule.c socketmodule.c Log Message: Patch #614055: Support OpenVMS. Index: _hotshot.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/_hotshot.c,v retrieving revision 1.30 retrieving revision 1.31 diff -C2 -d -r1.30 -r1.31 *** _hotshot.c 30 Sep 2002 16:19:48 -0000 1.30 --- _hotshot.c 6 Dec 2002 12:48:49 -0000 1.31 *************** *** 948,952 **** #endif } ! #if defined(MS_WINDOWS) || defined(macintosh) || defined(PYOS_OS2) rusage_diff = -1; #else --- 948,953 ---- #endif } ! #if defined(MS_WINDOWS) || defined(macintosh) || defined(PYOS_OS2) || \ ! defined(__VMS) rusage_diff = -1; #else Index: getbuildinfo.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/getbuildinfo.c,v retrieving revision 2.8 retrieving revision 2.9 diff -C2 -d -r2.8 -r2.9 *** getbuildinfo.c 4 Dec 2001 01:11:32 -0000 2.8 --- getbuildinfo.c 6 Dec 2002 12:48:49 -0000 2.9 *************** *** 29,32 **** --- 29,81 ---- #endif + #ifdef __VMS + # ifdef __DECC + # pragma extern_model save + # pragma extern_model strict_refdef + extern long ctl$gl_imghdrbf; + # pragma extern_model restore + # endif + + # ifdef __ALPHA + # define EIHD$L_IMGIDOFF 24 + # define EIHI$Q_LINKTIME 8 + # define _IMGIDOFF EIHD$L_IMGIDOFF + # define _LINKTIME EIHI$Q_LINKTIME + # else + # define IHD$W_IMGIDOFF 6 + # define IHI$Q_LINKTIME 56 + # define _IMGIDOFF IHD$W_IMGIDOFF + # define _LINKTIME IHI$Q_LINKTIME + # endif /* __VMS */ + + long* + vms__get_linktime (void) + { + long* al_imghdrbf; + unsigned short* aw_imgidoff; + unsigned short w_imgidoff; + long* aq_linktime; + unsigned char* ab_ihi; + + al_imghdrbf = &ctl$gl_imghdrbf; + + al_imghdrbf = (long *)*al_imghdrbf; + al_imghdrbf = (long *)*al_imghdrbf; + + aw_imgidoff = (unsigned short *) + ((unsigned char *)al_imghdrbf + _IMGIDOFF); + + w_imgidoff = *aw_imgidoff; + + ab_ihi = (unsigned char *)al_imghdrbf + w_imgidoff; + + aq_linktime = (long *) (ab_ihi + _LINKTIME); + + return aq_linktime; + } /* vms__get_linktime (void) */ + extern void vms__cvt_v2u_time (long * aq_vmstime, time_t * al_unixtime); + /* input , output */ + #endif /* __VMS */ + const char * *************** *** 34,39 **** --- 83,97 ---- { static char buildinfo[50]; + #ifdef __VMS + time_t l_unixtime; + + vms__cvt_v2u_time(vms__get_linktime (), &l_unixtime ); + + memset(buildinfo, 0, 40); + sprintf(buildinfo, "#%d, %.24s", BUILD, ctime (&l_unixtime)); + #else PyOS_snprintf(buildinfo, sizeof(buildinfo), "#%d, %.20s, %.9s", BUILD, DATE, TIME); + #endif return buildinfo; } Index: getpath.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/getpath.c,v retrieving revision 1.42 retrieving revision 1.43 diff -C2 -d -r1.42 -r1.43 *** getpath.c 13 Sep 2002 14:35:56 -0000 1.42 --- getpath.c 6 Dec 2002 12:48:50 -0000 1.43 *************** *** 93,97 **** --- 93,101 ---- #ifndef VERSION + #if defined(__VMS) + #define VERSION "2_1" + #else #define VERSION "2.1" + #endif #endif Index: main.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/main.c,v retrieving revision 1.70 retrieving revision 1.71 diff -C2 -d -r1.70 -r1.71 *** main.c 17 Oct 2002 20:37:50 -0000 1.70 --- main.c 6 Dec 2002 12:48:50 -0000 1.71 *************** *** 5,8 **** --- 5,13 ---- #include "compile.h" /* For CO_FUTURE_DIVISION */ + #ifdef __VMS + extern int PyVMS_init(int* pvi_argc, char*** pvi_argv); + extern PyObject* pyvms_gr_empty_string; + #endif + #if defined(MS_WINDOWS) || defined(__CYGWIN__) #include *************** *** 99,103 **** --- 104,119 ---- fprintf(f, usage_4, DELIM, DELIM, PYTHONHOMEHELP); } + #if defined(__VMS) + if (exitcode == 0) { + /* suppress 'error' message */ + exit(1); + } + else { + /* STS$M_INHIB_MSG + SS$_ABORT */ + exit(0x1000002c); + } + #else exit(exitcode); + #endif /*NOTREACHED*/ } *************** *** 146,150 **** --- 162,171 ---- fprintf(stderr, "%s: can't open file '%s'\n", argv[0], filename); + #if defined(__VMS) + /* STS$M_INHIB_MSG + SS$_ABORT */ + exit(0x1000002c); + #else exit(2); + #endif } } *************** *** 339,350 **** --- 360,407 ---- /* Leave stderr alone - it should be unbuffered anyway. */ } + #ifdef __VMS + else { + setvbuf (stdout, (char *)NULL, _IOLBF, BUFSIZ); + } + #endif /* __VMS */ Py_SetProgramName(argv[0]); + #ifdef __VMS + PyVMS_init(&argc, &argv); + #endif Py_Initialize(); + #ifdef __VMS + /* create an empty string object */ + pyvms_gr_empty_string = Py_BuildValue("s#", Py_None, (unsigned int)0); + #endif + if (Py_VerboseFlag || (command == NULL && filename == NULL && stdin_is_interactive)) + #ifndef __VMS fprintf(stderr, "Python %s on %s\n%s\n", Py_GetVersion(), Py_GetPlatform(), COPYRIGHT); + #else + fprintf(stderr, "Python %s on %s %s (%s_float)\n%s\n", + Py_GetVersion(), Py_GetPlatform(), + # ifdef __ALPHA + "Alpha", + # else + "VAX", + # endif + # if __IEEE_FLOAT + "T", + # else + # if __D_FLOAT + "D", + # else + # if __G_FLOAT + "G", + # endif /* __G_FLOAT */ + # endif /* __D_FLOAT */ + # endif /* __IEEE_FLOAT */ + COPYRIGHT); /* << @@ defined above in this file */ + /* Py_GetCopyright()); */ + #endif /* __VMS */ if (command != NULL) { Index: posixmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/posixmodule.c,v retrieving revision 2.273 retrieving revision 2.274 diff -C2 -d -r2.273 -r2.274 *** posixmodule.c 21 Nov 2002 23:52:35 -0000 2.273 --- posixmodule.c 6 Dec 2002 12:48:50 -0000 2.274 *************** *** 17,20 **** --- 17,47 ---- #include "structseq.h" + #if defined(__VMS) + # include /* tolower() */ + # include /* string descriptors */ + # include /* DVI$_name */ + # include /* -> O_RDWR */ + # include /* JPI$_name */ + # include /* LIB$name */ + # include /* OTS$name */ + # include /* SS$_name */ + # include + # include + # include + /* ----- */ + /* DECC on Alpha does redefine these already */ + # ifndef shell$from_vms + # define shell$from_vms(_p1_,_p2_,_p3_) decc$from_vms(_p1_,_p2_,_p3_) + # endif + # ifndef shell$translate_vms + # define shell$translate_vms(_p1_) decc$translate_vms(_p1_) + # endif + # ifndef shell$to_vms + # define shell$to_vms(_p1_,_p2_,_p3_,_p4_,_p5_) \ + decc$to_vms(_p1_,_p2_,_p3_,_p4_,_p5_) + # endif + # include /* define wait() */ + #endif /* defined(__VMS) */ + PyDoc_STRVAR(posix__doc__, "This module provides access to operating system functionality that is\n\ *************** *** 95,100 **** #define HAVE_CWAIT 1 #else ! #if defined(PYOS_OS2) && defined(PYCC_GCC) ! /* Everything needed is defined in PC/os2emx/pyconfig.h */ #else /* all other compilers */ /* Unix functions that the configure script doesn't check for */ --- 122,127 ---- #define HAVE_CWAIT 1 #else ! #if defined(PYOS_OS2) && defined(PYCC_GCC) || defined(__VMS) ! /* Everything needed is defined in PC/os2emx/pyconfig.h or vms/pyconfig.h */ #else /* all other compilers */ /* Unix functions that the configure script doesn't check for */ *************** *** 305,308 **** --- 332,527 ---- #endif /* !_MSC_VER */ + #if defined(__VMS) + static char psxmod_gt_psxpath[1026]; + + static int + psxmod_from_vms_action (char *spec) + { + (void)strcpy(psxmod_gt_psxpath, spec); + return 1; + } + + /* Return a dictionary corresponding to the VMS 'environment table' */ + static char* at_home = "HOME"; + static char* at_path = "PATH"; + + static char psxmod_t_command [] = "SYS$COMMAND"; + /* add some values to provide a similar environment like POSIX */ + void + psmmod_add_posix_env(PyObject *d) + { + /* -------------------- */ + struct dsc$descriptor_s r_device_name; + long l_devbufsiz; + long l_tt_page; + long l_item_code; + long l_status; + PyObject *o; + struct dsc$descriptor_s r_resultant_string; + char t_resultant_string[13]; /* enough space for username (12)+ '\0' */ + char *at_resultant_string; + short int w_resultant_length; + + /* set up string descriptor */ + r_device_name.dsc$w_length = strlen(psxmod_t_command); + r_device_name.dsc$b_dtype = DSC$K_DTYPE_T; + r_device_name.dsc$b_class = DSC$K_CLASS_S; + r_device_name.dsc$a_pointer = &psxmod_t_command[0]; + + /* -------------------- */ + /* COLUMNS = $getdvi("SYS$COMMAND","DEVBUFSIZ") */ + l_item_code = DVI$_DEVBUFSIZ; + l_status = lib$getdvi(&l_item_code, + 0, /* [channel] */ + &r_device_name, + &l_devbufsiz, /* integer-value */ + 0, /* resultant_string */ + 0); /* resultant_length */ + if (l_status == SS$_NORMAL) { + /* create a string object here to comply with POSIX */ + + /* set up string descriptor */ + r_resultant_string.dsc$w_length = + (sizeof(t_resultant_string) - 1); /* ommit '\0' at end */ + r_resultant_string.dsc$b_dtype = DSC$K_DTYPE_T; + r_resultant_string.dsc$b_class = DSC$K_CLASS_S; + r_resultant_string.dsc$a_pointer = &t_resultant_string[0]; + + /* Convert Signed Integer to Decimal Text */ + l_status = ots$cvt_l_ti(&l_devbufsiz, &r_resultant_string, 1, + 4, 0); + if (l_status == SS$_NORMAL) { + /* terminate string for 'C'-style */ + t_resultant_string[sizeof(t_resultant_string)-1] = '\0'; + /* string appears as: ' value' -- skip ' ' */ + at_resultant_string = &t_resultant_string[0]; + while ((*at_resultant_string == ' ' ) && + (*at_resultant_string != '\0')) { + at_resultant_string++; /* skip prefix spaces */ + } + + o = Py_BuildValue("s", at_resultant_string); + if (o != NULL) { + (void) PyDict_SetItemString(d, "COLUMNS", o); + Py_DECREF(o); + } + } /* (l_status = ots$cvt_l_ti() == SS$_NORMAL) */ + } /* (l_status = lib$getdvi(DVI$_DEVBUFSIZ) == SS$_NORMAL) */ + /* LINES = $getdvi("SYS$COMMAND","TT_PAGE") */ + l_item_code = DVI$_TT_PAGE; + l_status = lib$getdvi(&l_item_code, + 0, /* [channel] */ + &r_device_name, + &l_tt_page, /* integer-value */ + 0, /* resultant_string */ + 0); /* resultant_length */ + if (l_status == SS$_NORMAL) { + /* create a string object here to comply with POSIX */ + + /* set up string descriptor */ + r_resultant_string.dsc$w_length = + (sizeof(t_resultant_string) - 1); /* ommit '\0' at end */ + r_resultant_string.dsc$b_dtype = DSC$K_DTYPE_T; + r_resultant_string.dsc$b_class = DSC$K_CLASS_S; + r_resultant_string.dsc$a_pointer = &t_resultant_string[0]; + + /* Convert Signed Integer to Decimal Text */ + l_status = ots$cvt_l_ti(&l_tt_page, &r_resultant_string, + 1, 4, 0); + if (l_status == SS$_NORMAL) { + /* terminate string for 'C'-style */ + t_resultant_string[sizeof(t_resultant_string)-1] = '\0'; + /* string appears as: ' value' -- skip ' ' */ + at_resultant_string = &t_resultant_string[0]; + while ((*at_resultant_string == ' ' ) && + (*at_resultant_string != '\0')) { + at_resultant_string++; /* skip prefix spaces */ + } + + o = Py_BuildValue("s", at_resultant_string); + if (o != NULL) { + (void)PyDict_SetItemString(d, "LINES", o); + Py_DECREF(o); + } + } /* (l_status = ots$cvt_l_ti() == SS$_NORMAL) */ + } /* (l_status = lib$getdvi(DVI$_TT_PAGE) == SS$_NORMAL) */ + /* else -- ignore error */ + + /* LOGNAME = $getjpi(0,"USERNAME") */ + l_item_code = JPI$_USERNAME; + + /* set up string descriptor */ + r_resultant_string.dsc$w_length = + (sizeof(t_resultant_string) - 1); /* ommit '\0' at end */ + r_resultant_string.dsc$b_dtype = DSC$K_DTYPE_T; + r_resultant_string.dsc$b_class = DSC$K_CLASS_S; + r_resultant_string.dsc$a_pointer = &t_resultant_string[0]; + + l_status = lib$getjpi(&l_item_code, 0, 0, 0, + &r_resultant_string, &w_resultant_length); + if (l_status == SS$_NORMAL){ + t_resultant_string[w_resultant_length] = '\0'; + + /* remove any trailing spaces by replacing 1st one with '\0' */ + at_resultant_string = &t_resultant_string[0]; + while ((*at_resultant_string != ' ' ) && + (*at_resultant_string != '\0')) { + /* lowercase for compatibility with POSIX */ + *at_resultant_string = tolower(*at_resultant_string); + at_resultant_string++; /* skip non-blank */ + } + *at_resultant_string = '\0'; /* terminate */ + + o = Py_BuildValue("s", &t_resultant_string[0]); + if (o != NULL) { + (void) PyDict_SetItemString(d, "LOGNAME", o); + (void) PyDict_SetItemString(d, "USERNAME", o); + Py_DECREF(o); + } + } /* (l_status == SS$_NORMAL) */ + + /* OS = "OpenVMS" */ + o = PyString_FromString ("OpenVMS"); + if (o != NULL) { + (void)PyDict_SetItemString(d, "OS", o); + Py_DECREF(o); + } + } + + /* @@ posix env: + COLUMNS=80 $ write sys$output f$getdvi("SYS$COMMAND","DEVBUFSIZ") + LINES=47 $ write sys$output f$getdvi("SYS$COMMAND","TT_PAGE") + LOGNAME=zessin $ write sys$output f$edit(f$getjpi(0,"username"), - + "collapse,lowercase") + OS=OpenVMS + PS1=HERE $ + + TZ=CET-1:00CET DST,M3.5.0/2:00,M10.5.0/3:00 + $ write sys$output f$trnlnm("POSIX$DEFAULT_TZ") + "CET-1:00CET DST-2:00,M3.5.0/2:00,M10.5.0/3:00" + $ write sys$output f$trnlnm("UCX$TZ") + "MET-1MET_DST-2,M3.5.0/2,M10.5.0/3" + PAGER=more + TERM=vt300_series + SHELL=/bin/sh + HOME=/dka100/user/zessin + _=/bin/env + + >>> for v in os.environ.items(): + ... print v + ... + ('HOME', '/user_here/zessin') + ('COLUMNS', '80') + ('LINES', '24') + ('PATH', '/python_disk/python/python-1_5_2/vms') + ('OS', 'OpenVMS') + ('USER', 'ZESSIN') + ('LOGNAME', 'zessin') + ('TERM', 'vt300-80') + ('USERNAME', 'zessin') + >>> + */ + #endif /* __VMS */ + static PyObject * convertenviron(void) *************** *** 331,335 **** --- 550,566 ---- continue; } + #if defined(__VMS) + if ((strncmp(at_home, *e, sizeof(at_home)) == 0) || + (strncmp(at_path, *e, sizeof(at_path)) == 0)) { + (void)shell$from_vms(p+1, psxmod_from_vms_action, 0); + /* 0 = no wildcard expansion */ + v = PyString_FromString(psxmod_gt_psxpath); + } + else { + v = PyString_FromString(p+1); + } + #else v = PyString_FromString(p+1); + #endif if (v == NULL) { PyErr_Clear(); *************** *** 344,347 **** --- 575,581 ---- Py_DECREF(v); } + #if defined(__VMS) + psmmod_add_posix_env(d); + #endif /* defined(__VMS) */ #if defined(PYOS_OS2) { *************** *** 896,900 **** --- 1130,1138 ---- posix_do_stat(PyObject *self, PyObject *args, char *format, + #ifdef __VMS + int (*statfunc)(const char *, STRUCT_STAT *, ...), + #else int (*statfunc)(const char *, STRUCT_STAT *), + #endif char *wformat, int (*wstatfunc)(const Py_UNICODE *, STRUCT_STAT *)) *************** *** 1049,1053 **** --- 1287,1301 ---- return NULL; + #if defined(__VMS) + /* DECC V5.0 - only about FD= 0 @@ try getname()+$getdvi(dvi$_devnam) */ + if (id == 0) { + ret = ttyname(); + } + else { + ret = NULL; + } + #else ret = ttyname(id); + #endif if (ret == NULL) return(posix_error()); *************** *** 1093,1098 **** --- 1341,1351 ---- return posix_1str(args, "et:chdir", _chdir2, NULL, NULL); #else + #ifdef __VMS + return posix_1str(args, "et:chdir", (int (*)(const char *))chdir, + NULL, NULL); + #else return posix_1str(args, "et:chdir", chdir, NULL, NULL); #endif + #endif } *************** *** 1248,1253 **** --- 1501,1511 ---- res = _getcwd2(buf, sizeof buf); #else + #if defined(__VMS) + /* 0 = force Unix-style path if in the VMS DCL environment! */ + res = getcwd(buf, sizeof buf, 0); + #else res = getcwd(buf, sizeof buf); #endif + #endif Py_END_ALLOW_THREADS if (res == NULL) *************** *** 5116,5120 **** --- 5374,5382 ---- return NULL; Py_BEGIN_ALLOW_THREADS + #if defined(__VMS) + res = pipe(fds,0,2100); /* bigger mailbox quota than 512 */ + #else res = pipe(fds); + #endif Py_END_ALLOW_THREADS if (res != 0) Index: pwdmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/pwdmodule.c,v retrieving revision 1.36 retrieving revision 1.37 diff -C2 -d -r1.36 -r1.37 *** pwdmodule.c 17 Sep 2002 09:34:06 -0000 1.36 --- pwdmodule.c 6 Dec 2002 12:48:51 -0000 1.37 *************** *** 68,75 **** --- 68,83 ---- SETS(setIndex++, p->pw_name); + #ifdef __VMS + SETS(setIndex++, ""); + #else SETS(setIndex++, p->pw_passwd); + #endif SETI(setIndex++, p->pw_uid); SETI(setIndex++, p->pw_gid); + #ifdef __VMS + SETS(setIndex++, ""); + #else SETS(setIndex++, p->pw_gecos); + #endif SETS(setIndex++, p->pw_dir); SETS(setIndex++, p->pw_shell); Index: socketmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/socketmodule.c,v retrieving revision 1.246 retrieving revision 1.247 diff -C2 -d -r1.246 -r1.247 *** socketmodule.c 2 Nov 2002 19:55:21 -0000 1.246 --- socketmodule.c 6 Dec 2002 12:48:51 -0000 1.247 *************** *** 149,152 **** --- 149,161 ---- #endif + #if defined(__VMS) && ! defined(_SOCKADDR_LEN) + # ifdef getaddrinfo + # undef getaddrinfo + # endif + # include "TCPIP_IOCTL_ROUTINE" + #else + # include + #endif + #if defined(PYOS_OS2) # define INCL_DOS *************** *** 271,274 **** --- 280,288 ---- #endif + #ifdef __VMS + /* TCP/IP Services for VMS uses a maximum send/revc buffer length of 65535 */ + #define SEGMENT_SIZE 65535 + #endif + /* XXX There's a problem here: *static* functions are not supposed to have a Py prefix (or use CapitalizedWords). Later... */ *************** *** 486,490 **** block = !block; ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block)); ! #else /* !PYOS_OS2 */ delay_flag = fcntl(s->sock_fd, F_GETFL, 0); if (block) --- 500,507 ---- block = !block; ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block)); ! #elif defined(__VMS) ! block = !block; ! ioctl(s->sock_fd, FIONBIO, (char *)&block); ! #else /* !PYOS_OS2 && !_VMS */ delay_flag = fcntl(s->sock_fd, F_GETFL, 0); if (block) *************** *** 1224,1228 **** --- 1241,1249 ---- return PyInt_FromLong(flag); } + #ifdef __VMS + if (buflen > 1024) { + #else if (buflen <= 0 || buflen > 1024) { + #endif PyErr_SetString(socket_error, "getsockopt buflen out of range"); *************** *** 1561,1567 **** --- 1582,1602 ---- FILE *fp; PyObject *f; + #ifdef __VMS + char *mode_r = "r"; + char *mode_w = "w"; + #endif if (!PyArg_ParseTuple(args, "|si:makefile", &mode, &bufsize)) return NULL; + #ifdef __VMS + if (strcmp(mode,"rb") == 0) { + mode = mode_r; + } + else { + if (strcmp(mode,"wb") == 0) { + mode = mode_w; + } + } + #endif #ifdef MS_WIN32 if (((fd = _open_osfhandle(s->sock_fd, _O_BINARY)) < 0) || *************** *** 1602,1605 **** --- 1637,1644 ---- int len, n, flags = 0; PyObject *buf; + #ifdef __VMS + int read_length; + char *read_buf; + #endif if (!PyArg_ParseTuple(args, "i|i:recv", &len, &flags)) *************** *** 1616,1619 **** --- 1655,1659 ---- return NULL; + #ifndef __VMS Py_BEGIN_ALLOW_THREADS internal_select(s, 0); *************** *** 1627,1630 **** --- 1667,1706 ---- if (n != len) _PyString_Resize(&buf, n); + #else + read_buf = PyString_AsString(buf); + read_length = len; + while (read_length != 0) { + unsigned int segment; + + segment = read_length /SEGMENT_SIZE; + if (segment != 0) { + segment = SEGMENT_SIZE; + } + else { + segment = read_length; + } + + Py_BEGIN_ALLOW_THREADS + internal_select(s, 0); + n = recv(s->sock_fd, read_buf, segment, flags); + Py_END_ALLOW_THREADS + + if (n < 0) { + Py_DECREF(buf); + return s->errorhandler(); + } + if (n != read_length) { + read_buf += n; + break; + } + + read_length -= segment; + read_buf += segment; + } + if (_PyString_Resize(&buf, (read_buf - PyString_AsString(buf))) < 0) + { + return NULL; + } + #endif /* !__VMS */ return buf; } *************** *** 1708,1715 **** --- 1784,1795 ---- char *buf; int len, n, flags = 0; + #ifdef __VMS + int send_length; + #endif if (!PyArg_ParseTuple(args, "s#|i:send", &buf, &len, &flags)) return NULL; + #ifndef __VMS Py_BEGIN_ALLOW_THREADS internal_select(s, 1); *************** *** 1719,1722 **** --- 1799,1827 ---- if (n < 0) return s->errorhandler(); + #else + /* Divide packet into smaller segments for */ + /* TCP/IP Services for OpenVMS */ + send_length = len; + while (send_length != 0) { + unsigned int segment; + + segment = send_length / SEGMENT_SIZE; + if (segment != 0) { + segment = SEGMENT_SIZE; + } + else { + segment = send_length; + } + Py_BEGIN_ALLOW_THREADS + internal_select(s, 1); + n = send(s->sock_fd, buf, segment, flags); + Py_END_ALLOW_THREADS + if (n < 0) { + return s->errorhandler(); + } + send_length -= segment; + buf += segment; + } /* end while */ + #endif /* !__VMS */ return PyInt_FromLong((long)n); } From loewis@users.sourceforge.net Fri Dec 6 12:49:28 2002 From: loewis@users.sourceforge.net (loewis@users.sourceforge.net) Date: Fri, 06 Dec 2002 04:49:28 -0800 Subject: [Python-checkins] python/dist/src/Python exceptions.c,1.41,1.42 import.c,2.211,2.212 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv11610/Python Modified Files: exceptions.c import.c Log Message: Patch #614055: Support OpenVMS. Index: exceptions.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/exceptions.c,v retrieving revision 1.41 retrieving revision 1.42 diff -C2 -d -r1.41 -r1.42 *** exceptions.c 21 Nov 2002 20:08:31 -0000 1.41 --- exceptions.c 6 Dec 2002 12:48:53 -0000 1.42 *************** *** 68,71 **** --- 68,72 ---- | | |\n\ | | +-- WindowsError\n\ + | | +-- VMSError\n\ | |\n\ | +-- EOFError\n\ *************** *** 644,647 **** --- 645,653 ---- #endif /* MS_WINDOWS */ + #ifdef __VMS + static char + VMSError__doc__[] = "OpenVMS OS system call failed."; + #endif + PyDoc_STRVAR(EOFError__doc__, "Read beyond end of file."); *************** *** 1600,1603 **** --- 1606,1612 ---- PyObject *PyExc_WindowsError; #endif + #ifdef __VMS + PyObject *PyExc_VMSError; + #endif /* Pre-computed MemoryError instance. Best to create this as early as *************** *** 1651,1654 **** --- 1660,1667 ---- WindowsError__doc__}, #endif /* MS_WINDOWS */ + #ifdef __VMS + {"VMSError", &PyExc_VMSError, &PyExc_OSError, + VMSError__doc__}, + #endif {"EOFError", &PyExc_EOFError, 0, EOFError__doc__}, {"RuntimeError", &PyExc_RuntimeError, 0, RuntimeError__doc__}, Index: import.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/import.c,v retrieving revision 2.211 retrieving revision 2.212 diff -C2 -d -r2.211 -r2.212 *** import.c 29 Nov 2002 20:47:40 -0000 2.211 --- import.c 6 Dec 2002 12:48:53 -0000 2.212 *************** *** 694,699 **** |O_BINARY /* necessary for Windows */ #endif ! ! , 0666); if (fd < 0) return NULL; --- 694,702 ---- |O_BINARY /* necessary for Windows */ #endif ! #ifdef __VMS ! , 0666, "ctxt=bin", "shr=nil"); ! #else ! , 0666); ! #endif if (fd < 0) return NULL; From loewis@users.sourceforge.net Fri Dec 6 12:57:29 2002 From: loewis@users.sourceforge.net (loewis@users.sourceforge.net) Date: Fri, 06 Dec 2002 04:57:29 -0800 Subject: [Python-checkins] python/dist/src/Modules socketmodule.c,1.247,1.248 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv14859/Modules Modified Files: socketmodule.c Log Message: Don't include unless on __VMS. Index: socketmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/socketmodule.c,v retrieving revision 1.247 retrieving revision 1.248 diff -C2 -d -r1.247 -r1.248 *** socketmodule.c 6 Dec 2002 12:48:51 -0000 1.247 --- socketmodule.c 6 Dec 2002 12:57:26 -0000 1.248 *************** *** 149,153 **** #endif ! #if defined(__VMS) && ! defined(_SOCKADDR_LEN) # ifdef getaddrinfo # undef getaddrinfo --- 149,154 ---- #endif ! #if defined(__VMS) ! #if ! defined(_SOCKADDR_LEN) # ifdef getaddrinfo # undef getaddrinfo *************** *** 156,159 **** --- 157,161 ---- #else # include + #endif #endif From mwh@users.sourceforge.net Fri Dec 6 15:33:04 2002 From: mwh@users.sourceforge.net (mwh@users.sourceforge.net) Date: Fri, 06 Dec 2002 07:33:04 -0800 Subject: [Python-checkins] python/dist/src setup.py,1.73.4.11,1.73.4.12 Message-ID: Update of /cvsroot/python/python/dist/src In directory sc8-pr-cvs1:/tmp/cvs-serv12328 Modified Files: Tag: release22-maint setup.py Log Message: Fix bugs: [ 534748 ] Removing _tkinter considered harmful [ 645383 ] Give some clue why modules fail... by slapping the code from the trunk across to the release22-maint branch. Index: setup.py =================================================================== RCS file: /cvsroot/python/python/dist/src/setup.py,v retrieving revision 1.73.4.11 retrieving revision 1.73.4.12 diff -C2 -d -r1.73.4.11 -r1.73.4.12 *** setup.py 10 Oct 2002 00:59:16 -0000 1.73.4.11 --- setup.py 6 Dec 2002 15:33:01 -0000 1.73.4.12 *************** *** 165,187 **** __import__(ext.name) except ImportError: ! self.announce('WARNING: removing "%s" since importing it failed' % ! ext.name) ! assert not self.inplace ! fullname = self.get_ext_fullname(ext.name) ! ext_filename = os.path.join(self.build_lib, ! self.get_ext_filename(fullname)) ! os.remove(ext_filename) ! # XXX -- This relies on a Vile HACK in ! # distutils.command.build_ext.build_extension(). The ! # _built_objects attribute is stored there strictly for ! # use here. ! # If there is a failure, _built_objects may not be there, ! # so catch the AttributeError and move on. ! try: ! for filename in self._built_objects: ! os.remove(filename) ! except AttributeError: ! self.announce('unable to remove files (ignored)') def get_platform (self): --- 165,191 ---- __import__(ext.name) except ImportError: ! if 1: ! self.announce('*** WARNING: renaming "%s" since importing it' ! ' failed: %s' % (ext.name, why)) ! assert not self.inplace ! basename, tail = os.path.splitext(ext_filename) ! newname = basename + "_failed" + tail ! if os.path.exists(newname): os.remove(newname) ! os.rename(ext_filename, newname) ! # XXX -- This relies on a Vile HACK in ! # distutils.command.build_ext.build_extension(). The ! # _built_objects attribute is stored there strictly for ! # use here. ! # If there is a failure, _built_objects may not be there, ! # so catch the AttributeError and move on. ! try: ! for filename in self._built_objects: ! os.remove(filename) ! except AttributeError: ! self.announce('unable to remove files (ignored)') ! else: ! self.announce('*** WARNING: importing extension "%s" ' ! 'failed: %s' % (ext.name, why)) def get_platform (self): From fdrake@users.sourceforge.net Fri Dec 6 16:44:11 2002 From: fdrake@users.sourceforge.net (fdrake@users.sourceforge.net) Date: Fri, 06 Dec 2002 08:44:11 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libos.tex,1.74.2.1.2.8,1.74.2.1.2.9 libpopen2.tex,1.15.12.2,1.15.12.3 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv8759/lib Modified Files: Tag: release22-maint libos.tex libpopen2.tex Log Message: Typo: "dead lock" --> "deadlock" Index: libos.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libos.tex,v retrieving revision 1.74.2.1.2.8 retrieving revision 1.74.2.1.2.9 diff -C2 -d -r1.74.2.1.2.8 -r1.74.2.1.2.9 *** libos.tex 12 Nov 2002 22:07:48 -0000 1.74.2.1.2.8 --- libos.tex 6 Dec 2002 16:43:48 -0000 1.74.2.1.2.9 *************** *** 332,336 **** module; these are only available on \UNIX. ! For a discussion of possible dead lock conditions related to the use of these functions, see ``\ulink{Flow Control Issues}{popen2-flow-control.html}'' --- 332,336 ---- module; these are only available on \UNIX. ! For a discussion of possible deadlock conditions related to the use of these functions, see ``\ulink{Flow Control Issues}{popen2-flow-control.html}'' Index: libpopen2.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libpopen2.tex,v retrieving revision 1.15.12.2 retrieving revision 1.15.12.3 diff -C2 -d -r1.15.12.2 -r1.15.12.3 *** libpopen2.tex 18 Jun 2002 20:38:43 -0000 1.15.12.2 --- libpopen2.tex 6 Dec 2002 16:43:58 -0000 1.15.12.3 *************** *** 130,134 **** When reading output from a child process that writes a lot of data to standard error while the parent is reading from the child's standard ! out, a dead lock can occur. A similar situation can occur with other combinations of reads and writes. The essential factors are that more than \constant{_PC_PIPE_BUF} bytes are being written by one process in --- 130,134 ---- When reading output from a child process that writes a lot of data to standard error while the parent is reading from the child's standard ! out, a deadlock can occur. A similar situation can occur with other combinations of reads and writes. The essential factors are that more than \constant{_PC_PIPE_BUF} bytes are being written by one process in From fdrake@users.sourceforge.net Fri Dec 6 16:45:17 2002 From: fdrake@users.sourceforge.net (fdrake@users.sourceforge.net) Date: Fri, 06 Dec 2002 08:45:17 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libos.tex,1.103,1.104 libpopen2.tex,1.17,1.18 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv9390/lib Modified Files: libos.tex libpopen2.tex Log Message: Typo: "dead lock" --> "deadlock" Index: libos.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libos.tex,v retrieving revision 1.103 retrieving revision 1.104 diff -C2 -d -r1.103 -r1.104 *** libos.tex 12 Nov 2002 22:07:11 -0000 1.103 --- libos.tex 6 Dec 2002 16:45:00 -0000 1.104 *************** *** 345,349 **** module; these are only available on \UNIX. ! For a discussion of possible dead lock conditions related to the use of these functions, see ``\ulink{Flow Control Issues}{popen2-flow-control.html}'' --- 345,349 ---- module; these are only available on \UNIX. ! For a discussion of possible deadlock conditions related to the use of these functions, see ``\ulink{Flow Control Issues}{popen2-flow-control.html}'' Index: libpopen2.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libpopen2.tex,v retrieving revision 1.17 retrieving revision 1.18 diff -C2 -d -r1.17 -r1.18 *** libpopen2.tex 18 Jun 2002 20:38:05 -0000 1.17 --- libpopen2.tex 6 Dec 2002 16:45:05 -0000 1.18 *************** *** 130,134 **** When reading output from a child process that writes a lot of data to standard error while the parent is reading from the child's standard ! out, a dead lock can occur. A similar situation can occur with other combinations of reads and writes. The essential factors are that more than \constant{_PC_PIPE_BUF} bytes are being written by one process in --- 130,134 ---- When reading output from a child process that writes a lot of data to standard error while the parent is reading from the child's standard ! out, a deadlock can occur. A similar situation can occur with other combinations of reads and writes. The essential factors are that more than \constant{_PC_PIPE_BUF} bytes are being written by one process in From tim_one@users.sourceforge.net Fri Dec 6 17:06:31 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 06 Dec 2002 09:06:31 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.c,1.43,1.44 obj_date.c,1.32,1.33 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv16549 Modified Files: datetime.c obj_date.c Log Message: Fred pointed out that PyObject_CallMethod can be used to call a module function too, so exploited that to save some tedious boilerplate code. Index: datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.c,v retrieving revision 1.43 retrieving revision 1.44 diff -C2 -d -r1.43 -r1.44 *** datetime.c 6 Dec 2002 02:55:32 -0000 1.43 --- datetime.c 6 Dec 2002 17:04:58 -0000 1.44 *************** *** 340,344 **** { PyObject *time; - PyObject *time_strftime; PyObject *result; --- 340,343 ---- *************** *** 349,359 **** return NULL; ! time_strftime = PyObject_GetAttrString(time, "strftime"); ! Py_DECREF(time); ! if (time_strftime == NULL) ! return NULL; ! ! result = PyObject_CallFunction(time_strftime, "OO", format, tuple); ! Py_DECREF(time_strftime); return result; } --- 348,353 ---- return NULL; ! result = PyObject_CallMethod(time, "strftime", "OO", format, tuple); ! Py_DECREF(time); return result; } *************** *** 743,754 **** { PyObject *temp; - PyObject *copyreg_pickle; PyObject *pickler; ! temp = PyImport_ImportModule("copy_reg"); ! assert(temp); ! copyreg_pickle = PyObject_GetAttrString(temp, "pickle"); ! assert(copyreg_pickle); ! Py_DECREF(temp); pickler = PyObject_GetAttrString(m, "_date_pickler"); --- 737,744 ---- { PyObject *temp; PyObject *pickler; + PyObject *copyreg = PyImport_ImportModule("copy_reg"); ! assert(copyreg); pickler = PyObject_GetAttrString(m, "_date_pickler"); *************** *** 757,764 **** "_date_unpickler"); assert(date_unpickler_object); ! temp = PyObject_CallFunction(copyreg_pickle, "OOO", ! &PyDateTime_DateType, ! pickler, ! date_unpickler_object); assert(temp); Py_DECREF(temp); --- 747,754 ---- "_date_unpickler"); assert(date_unpickler_object); ! temp = PyObject_CallMethod(copyreg, "pickle", "OOO", ! &PyDateTime_DateType, ! pickler, ! date_unpickler_object); assert(temp); Py_DECREF(temp); *************** *** 770,782 **** "_datetime_unpickler"); assert(datetime_unpickler_object); ! temp = PyObject_CallFunction(copyreg_pickle, "OOO", ! &PyDateTime_DateTimeType, ! pickler, ! datetime_unpickler_object); assert(temp); Py_DECREF(temp); Py_DECREF(pickler); ! Py_DECREF(copyreg_pickle); } } --- 760,772 ---- "_datetime_unpickler"); assert(datetime_unpickler_object); ! temp = PyObject_CallMethod(copyreg, "pickle", "OOO", ! &PyDateTime_DateTimeType, ! pickler, ! datetime_unpickler_object); assert(temp); Py_DECREF(temp); Py_DECREF(pickler); ! Py_DECREF(copyreg); } } Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.32 retrieving revision 1.33 diff -C2 -d -r1.32 -r1.33 *** obj_date.c 6 Dec 2002 05:26:52 -0000 1.32 --- obj_date.c 6 Dec 2002 17:05:13 -0000 1.33 *************** *** 227,232 **** date_today(PyObject *self, PyObject *cls) { ! PyObject *time; /* the time module, and later time.time() */ ! PyObject *time_time; /* time.time */ PyObject *result; --- 227,232 ---- date_today(PyObject *self, PyObject *cls) { ! PyObject *time; /* the time module) */ ! PyObject *time_time; /* time.time() */ PyObject *result; *************** *** 235,246 **** return NULL; ! time_time = PyObject_GetAttrString(time, "time"); Py_DECREF(time); ! if (time_time == NULL) ! return NULL; ! ! time = PyObject_CallObject(time_time, NULL); ! Py_DECREF(time_time); ! if (time == NULL) return NULL; --- 235,241 ---- return NULL; ! time_time = PyObject_CallMethod(time, "time", "()"); Py_DECREF(time); ! if (time_time == NULL) return NULL; *************** *** 251,256 **** * date.today() could get away with plain C time(). */ ! result = PyObject_CallMethod(cls, "fromtimestamp", "O", time); ! Py_DECREF(time); return result; } --- 246,251 ---- * date.today() could get away with plain C time(). */ ! result = PyObject_CallMethod(cls, "fromtimestamp", "O", time_time); ! Py_DECREF(time_time); return result; } From tim_one@users.sourceforge.net Fri Dec 6 17:14:39 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 06 Dec 2002 09:14:39 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_date.c,1.33,1.34 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv19571 Modified Files: obj_date.c Log Message: Cleanup: rearranged the date code to follow the same ordering of functions as was previously established for the datetime code. Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.33 retrieving revision 1.34 diff -C2 -d -r1.33 -r1.34 *** obj_date.c 6 Dec 2002 17:05:13 -0000 1.33 --- obj_date.c 6 Dec 2002 17:14:21 -0000 1.34 *************** *** 3,166 **** */ ! /* Fiddle out-of-bounds months and days so that the result makes some kind ! * of sense. The parameters are both inputs and outputs. Returns < 0 on ! * failure, where failure means the adjusted year is out of bounds. ! */ ! static int ! normalize_date(long *year, long *month, long *day) ! { ! int result; ! ! normalize_y_m_d(year, month, day); ! if (MINYEAR <= *year && *year <= MAXYEAR) ! result = 0; ! else { ! PyErr_SetString(PyExc_OverflowError, ! "date value out of range"); ! result = -1; ! } ! return result; ! } ! ! /* date + timedelta -> date. If arg negate is true, subtract the timedelta ! * instead. ! */ ! static PyObject * ! add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate) ! { ! PyObject *result = NULL; ! long year = GET_YEAR(date); ! long month = GET_MONTH(date); ! long deltadays = GET_TD_DAYS(delta); ! /* C-level overflow is impossible because |deltadays| < 1e9. */ ! long day = GET_DAY(date) + (negate ? -deltadays : deltadays); ! ! if (normalize_date(&year, &month, &day) >= 0) ! result = new_date(year, month, day); ! return result; ! } ! ! static PyObject * ! date_add(PyObject *left, PyObject *right) ! { ! PyTypeObject *left_type = left->ob_type; ! PyTypeObject *right_type = right->ob_type; ! ! if (PyType_IsSubtype(left_type, &PyDateTime_DateTimeType) ! || PyType_IsSubtype(right_type, &PyDateTime_DateTimeType)) { ! Py_INCREF(Py_NotImplemented); ! return Py_NotImplemented; ! } ! if (PyType_IsSubtype(left_type, &PyDateTime_DateType)) { ! /* date + ??? */ ! if (PyType_IsSubtype(right_type, &PyDateTime_DeltaType)) ! /* date + delta */ ! return add_date_timedelta((PyDateTime_Date *) left, ! (PyDateTime_Delta *) right, ! 0); ! } ! else { ! /* ??? + date ! * 'right' must be one of us, or we wouldn't have been called ! */ ! if (PyType_IsSubtype(left_type, &PyDateTime_DeltaType)) ! /* delta + date */ ! return add_date_timedelta((PyDateTime_Date *) right, ! (PyDateTime_Delta *) left, ! 0); ! } ! Py_INCREF(Py_NotImplemented); ! return Py_NotImplemented; ! } ! ! static PyObject * ! date_subtract(PyObject *left, PyObject *right) ! { ! PyTypeObject *left_type = left->ob_type; ! PyTypeObject *right_type = right->ob_type; ! ! if (PyType_IsSubtype(left_type, &PyDateTime_DateTimeType) ! || PyType_IsSubtype(right_type, &PyDateTime_DateTimeType)) { ! Py_INCREF(Py_NotImplemented); ! return Py_NotImplemented; ! } ! if (PyType_IsSubtype(left_type, &PyDateTime_DateType)) { ! if (PyType_IsSubtype(right_type, &PyDateTime_DateType)) { ! /* date - date */ ! long left_ord = ymd_to_ord(GET_YEAR(left), ! GET_MONTH(left), ! GET_DAY(left)); ! long right_ord = ymd_to_ord(GET_YEAR(right), ! GET_MONTH(right), ! GET_DAY(right)); ! return new_delta(left_ord - right_ord, 0, 0, 0); ! } ! if (PyType_IsSubtype(right_type, &PyDateTime_DeltaType)) { ! /* date - delta */ ! return add_date_timedelta((PyDateTime_Date *) left, ! (PyDateTime_Delta *) right, ! 1); ! } ! } ! Py_INCREF(Py_NotImplemented); ! return Py_NotImplemented; ! } - /* 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) { ! long diff; ! ! if (! PyType_IsSubtype(other->ob_type, &PyDateTime_DateType)) { ! PyErr_Format(PyExc_TypeError, ! "can't compare date to %s instance", ! other->ob_type->tp_name); ! return NULL; ! } ! diff = memcmp(self->data, ((PyDateTime_Date *)other)->data, ! _PyDateTime_DATE_DATA_SIZE); ! return diff_to_bool(diff, op); } static PyObject * ! date_ctime(PyDateTime_Date *self) { ! return format_ctime(self, 0, 0, 0); } static PyObject * ! date_timetuple(PyDateTime_Date *self) { ! const int year = GET_YEAR(self); ! const int month = GET_MONTH(self); ! const int day = GET_DAY(self); ! ! return Py_BuildValue("iiiiiiiii", ! year, month, day, ! 0, 0, 0, ! weekday(year, month, day), ! days_before_month(year, month) + day, ! -1); } ! static long ! date_hash(PyDateTime_Date *self) ! { ! if (self->hashcode == -1) { ! PyObject *temp = Py_BuildValue("lll", GET_YEAR(self), ! GET_MONTH(self), GET_DAY(self)); ! if (temp != NULL) { ! self->hashcode = PyObject_Hash(temp); ! Py_DECREF(temp); ! } ! } ! return self->hashcode; ! } ! /* Constructor. */ static PyObject * --- 3,34 ---- */ ! /* Accessor properties. */ static PyObject * ! date_year(PyDateTime_Date *self, void *unused) { ! return (PyInt_FromLong(GET_YEAR(self))); } static PyObject * ! date_month(PyDateTime_Date *self, void *unused) { ! return (PyInt_FromLong(GET_MONTH(self))); } static PyObject * ! date_day(PyDateTime_Date *self, void *unused) { ! return (PyInt_FromLong(GET_DAY(self))); } ! static PyGetSetDef date_getset[] = { ! {"year", (getter)date_year}, ! {"month", (getter)date_month}, ! {"day", (getter)date_day}, ! {NULL} ! }; ! /* Constructors. */ static PyObject * *************** *** 196,201 **** } - /* Class-method constructors. */ - /* Return new date from localtime(t). */ static PyObject * --- 64,67 ---- *************** *** 227,231 **** date_today(PyObject *self, PyObject *cls) { ! PyObject *time; /* the time module) */ PyObject *time_time; /* time.time() */ PyObject *result; --- 93,97 ---- date_today(PyObject *self, PyObject *cls) { ! PyObject *time; /* the time module */ PyObject *time_time; /* time.time() */ PyObject *result; *************** *** 292,358 **** } ! /* Attributes. */ ! static PyObject * ! date_year(PyDateTime_Date *self, void *unused) { ! return (PyInt_FromLong(GET_YEAR(self))); ! } ! static PyObject * ! date_month(PyDateTime_Date *self, void *unused) ! { ! return (PyInt_FromLong(GET_MONTH(self))); } static PyObject * ! date_day(PyDateTime_Date *self, void *unused) { ! return (PyInt_FromLong(GET_DAY(self))); ! } ! static PyGetSetDef date_getset[] = { ! {"year", (getter)date_year}, ! {"month", (getter)date_month}, ! {"day", (getter)date_day}, ! {NULL} ! }; static PyObject * ! date_isocalendar(PyDateTime_Date *self) { ! int year = GET_YEAR(self); ! int week1_monday = iso_week1_monday(year); ! long today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self)); ! long week; ! long day; ! week = divmod(today - week1_monday, 7, &day); ! if (week < 0) { ! --year; ! week1_monday = iso_week1_monday(year); ! week = divmod(today - week1_monday, 7, &day); } ! else if (week >= 52 && today >= iso_week1_monday(year + 1)) { ! ++year; ! week = 0; } ! return Py_BuildValue("iii", year, (int)week + 1, (int)day + 1); } static PyObject * ! date_isoweekday(PyDateTime_Date *self) { ! int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self)); ! return PyInt_FromLong(dow + 1); } ! static int ! date_nonzero(PyDateTime_Date *self) ! { ! assert(GET_YEAR(self) >= 1); ! return 1; ! } static PyObject * --- 158,269 ---- } ! /* date arithmetic. */ ! /* Fiddle out-of-bounds months and days so that the result makes some kind ! * of sense. The parameters are both inputs and outputs. Returns < 0 on ! * failure, where failure means the adjusted year is out of bounds. ! */ ! static int ! normalize_date(long *year, long *month, long *day) { ! int result; ! normalize_y_m_d(year, month, day); ! if (MINYEAR <= *year && *year <= MAXYEAR) ! result = 0; ! else { ! PyErr_SetString(PyExc_OverflowError, ! "date value out of range"); ! result = -1; ! } ! return result; } + /* date + timedelta -> date. If arg negate is true, subtract the timedelta + * instead. + */ static PyObject * ! add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate) { ! PyObject *result = NULL; ! long year = GET_YEAR(date); ! long month = GET_MONTH(date); ! long deltadays = GET_TD_DAYS(delta); ! /* C-level overflow is impossible because |deltadays| < 1e9. */ ! long day = GET_DAY(date) + (negate ? -deltadays : deltadays); ! if (normalize_date(&year, &month, &day) >= 0) ! result = new_date(year, month, day); ! return result; ! } static PyObject * ! date_add(PyObject *left, PyObject *right) { ! PyTypeObject *left_type = left->ob_type; ! PyTypeObject *right_type = right->ob_type; ! if (PyType_IsSubtype(left_type, &PyDateTime_DateTimeType) ! || PyType_IsSubtype(right_type, &PyDateTime_DateTimeType)) { ! Py_INCREF(Py_NotImplemented); ! return Py_NotImplemented; } ! if (PyType_IsSubtype(left_type, &PyDateTime_DateType)) { ! /* date + ??? */ ! if (PyType_IsSubtype(right_type, &PyDateTime_DeltaType)) ! /* date + delta */ ! return add_date_timedelta((PyDateTime_Date *) left, ! (PyDateTime_Delta *) right, ! 0); } ! else { ! /* ??? + date ! * 'right' must be one of us, or we wouldn't have been called ! */ ! if (PyType_IsSubtype(left_type, &PyDateTime_DeltaType)) ! /* delta + date */ ! return add_date_timedelta((PyDateTime_Date *) right, ! (PyDateTime_Delta *) left, ! 0); ! } ! Py_INCREF(Py_NotImplemented); ! return Py_NotImplemented; } static PyObject * ! date_subtract(PyObject *left, PyObject *right) { ! PyTypeObject *left_type = left->ob_type; ! PyTypeObject *right_type = right->ob_type; ! if (PyType_IsSubtype(left_type, &PyDateTime_DateTimeType) ! || PyType_IsSubtype(right_type, &PyDateTime_DateTimeType)) { ! Py_INCREF(Py_NotImplemented); ! return Py_NotImplemented; ! } ! if (PyType_IsSubtype(left_type, &PyDateTime_DateType)) { ! if (PyType_IsSubtype(right_type, &PyDateTime_DateType)) { ! /* date - date */ ! long left_ord = ymd_to_ord(GET_YEAR(left), ! GET_MONTH(left), ! GET_DAY(left)); ! long right_ord = ymd_to_ord(GET_YEAR(right), ! GET_MONTH(right), ! GET_DAY(right)); ! return new_delta(left_ord - right_ord, 0, 0, 0); ! } ! if (PyType_IsSubtype(right_type, &PyDateTime_DeltaType)) { ! /* date - delta */ ! return add_date_timedelta((PyDateTime_Date *) left, ! (PyDateTime_Delta *) right, ! 1); ! } ! } ! Py_INCREF(Py_NotImplemented); ! return Py_NotImplemented; } ! ! /* Various ways to turn a date into a string. */ static PyObject * *************** *** 381,384 **** --- 292,301 ---- static PyObject * + date_ctime(PyDateTime_Date *self) + { + return format_ctime(self, 0, 0, 0); + } + + static PyObject * date_strftime(PyDateTime_Date *self, PyObject *format) { *************** *** 398,401 **** --- 315,408 ---- } + /* ISO methods. */ + + static PyObject * + date_isoweekday(PyDateTime_Date *self) + { + int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self)); + + return PyInt_FromLong(dow + 1); + } + + static PyObject * + date_isocalendar(PyDateTime_Date *self) + { + int year = GET_YEAR(self); + int week1_monday = iso_week1_monday(year); + long today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self)); + long week; + long day; + + week = divmod(today - week1_monday, 7, &day); + if (week < 0) { + --year; + week1_monday = iso_week1_monday(year); + week = divmod(today - week1_monday, 7, &day); + } + else if (week >= 52 && today >= iso_week1_monday(year + 1)) { + ++year; + week = 0; + } + return Py_BuildValue("iii", year, (int)week + 1, (int)day + 1); + } + + /* 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) + { + long diff; + + if (! PyType_IsSubtype(other->ob_type, &PyDateTime_DateType)) { + PyErr_Format(PyExc_TypeError, + "can't compare date to %s instance", + other->ob_type->tp_name); + return NULL; + } + diff = memcmp(self->data, ((PyDateTime_Date *)other)->data, + _PyDateTime_DATE_DATA_SIZE); + return diff_to_bool(diff, op); + } + + static PyObject * + date_timetuple(PyDateTime_Date *self) + { + const int year = GET_YEAR(self); + const int month = GET_MONTH(self); + const int day = GET_DAY(self); + + return Py_BuildValue("iiiiiiiii", + year, month, day, + 0, 0, 0, + weekday(year, month, day), + days_before_month(year, month) + day, + -1); + } + + static long + date_hash(PyDateTime_Date *self) + { + if (self->hashcode == -1) { + PyObject *temp = Py_BuildValue("lll", GET_YEAR(self), + GET_MONTH(self), GET_DAY(self)); + if (temp != NULL) { + self->hashcode = PyObject_Hash(temp); + Py_DECREF(temp); + } + } + return self->hashcode; + } + + static int + date_nonzero(PyDateTime_Date *self) + { + assert(GET_YEAR(self) >= 1); + return 1; + } + static PyObject * date_toordinal(PyDateTime_Date *self) *************** *** 414,417 **** --- 421,425 ---- /* Pickle support. Quite a maze! */ + static PyObject * date_getstate(PyDateTime_Date *self) *************** *** 467,471 **** } - /* XXX strftime is missing. */ static PyMethodDef date_methods[] = { /* Class methods: */ --- 475,478 ---- From tim_one@users.sourceforge.net Fri Dec 6 17:21:45 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 06 Dec 2002 09:21:45 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_date.c,1.34,1.35 obj_datetime.c,1.26,1.27 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv21912 Modified Files: obj_date.c obj_datetime.c Log Message: Added XXX comments about the METH_CLASS bug. Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.34 retrieving revision 1.35 diff -C2 -d -r1.34 -r1.35 *** obj_date.c 6 Dec 2002 17:14:21 -0000 1.34 --- obj_date.c 6 Dec 2002 17:20:58 -0000 1.35 *************** *** 477,480 **** --- 477,485 ---- static PyMethodDef date_methods[] = { /* Class methods: */ + /* XXX METH_CLASS is implemented incorrectly: + * XXX http://www.python.org/sf/548651 + * XXX The signatures of these methods will need to change (for + * XXX the better) when that's fixed. + */ {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS | METH_CLASS, Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.26 retrieving revision 1.27 diff -C2 -d -r1.26 -r1.27 *** obj_datetime.c 6 Dec 2002 05:13:40 -0000 1.26 --- obj_datetime.c 6 Dec 2002 17:21:15 -0000 1.27 *************** *** 542,545 **** --- 542,550 ---- static PyMethodDef datetime_methods[] = { /* Class methods: */ + /* XXX METH_CLASS is implemented incorrectly: + * XXX http://www.python.org/sf/548651 + * XXX The signatures of these methods will need to change (for + * XXX the better) when that's fixed. + */ {"now", (PyCFunction)datetime_now, METH_O | METH_CLASS, From fdrake@users.sourceforge.net Fri Dec 6 18:52:11 2002 From: fdrake@users.sourceforge.net (fdrake@users.sourceforge.net) Date: Fri, 06 Dec 2002 10:52:11 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libdifflib.tex,1.11,1.11.6.1 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv21481 Modified Files: Tag: release22-maint libdifflib.tex Log Message: Remove extra ")" in example. Index: libdifflib.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libdifflib.tex,v retrieving revision 1.11 retrieving revision 1.11.6.1 diff -C2 -d -r1.11 -r1.11.6.1 *** libdifflib.tex 29 Nov 2001 19:04:50 -0000 1.11 --- libdifflib.tex 6 Dec 2002 18:52:07 -0000 1.11.6.1 *************** *** 107,111 **** \begin{verbatim} >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1), ! ... 'ore\ntree\nemu\n'.splitlines(1))) >>> print ''.join(diff), - one --- 107,111 ---- \begin{verbatim} >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1), ! ... 'ore\ntree\nemu\n'.splitlines(1)) >>> print ''.join(diff), - one From fdrake@users.sourceforge.net Fri Dec 6 18:52:31 2002 From: fdrake@users.sourceforge.net (fdrake@users.sourceforge.net) Date: Fri, 06 Dec 2002 10:52:31 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libdifflib.tex,1.12,1.13 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv21597 Modified Files: libdifflib.tex Log Message: Remove extra ")" in example. Index: libdifflib.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libdifflib.tex,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** libdifflib.tex 29 Apr 2002 01:37:31 -0000 1.12 --- libdifflib.tex 6 Dec 2002 18:52:28 -0000 1.13 *************** *** 113,117 **** \begin{verbatim} >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1), ! ... 'ore\ntree\nemu\n'.splitlines(1))) >>> print ''.join(diff), - one --- 113,117 ---- \begin{verbatim} >>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1), ! ... 'ore\ntree\nemu\n'.splitlines(1)) >>> print ''.join(diff), - one From tim_one@users.sourceforge.net Fri Dec 6 20:26:28 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 06 Dec 2002 12:26:28 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime doc.txt,1.20,1.21 test_both.py,1.44,1.45 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv28407 Modified Files: doc.txt test_both.py Log Message: Finished datetime.ctime() work. Doing so turned up that MSVC 6's ctime() function doesn't conform to the C std, so that Python's time.ctime() doesn't either, but date.ctime() and datetime.ctime() do. Noted this irritation in the docs. Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.20 retrieving revision 1.21 diff -C2 -d -r1.20 -r1.21 *** doc.txt 6 Dec 2002 05:21:02 -0000 1.20 --- doc.txt 6 Dec 2002 20:26:23 -0000 1.21 *************** *** 307,311 **** Return a string representing the date, for example date(2002, 12, 4).ctime() == 'Wed Dec 4 00:00:00 2002'. ! d.ctime() is equivalent to time.ctime(time.mktime(d.timetuple())). - strftime(format) --- 307,314 ---- Return a string representing the date, for example date(2002, 12, 4).ctime() == 'Wed Dec 4 00:00:00 2002'. ! d.ctime() is equivalent to time.ctime(time.mktime(d.timetuple())) ! on platforms where the native C ctime() function (which time.ctime() ! invokes, but which date.ctime() does not invoke) conforms to the ! C standard. - strftime(format) *************** *** 475,483 **** str(d) is equivalent to d.isoformat(). - XXX ctime() needs work. - ctime() Return a string representing the date, for example ! date(2002, 12, 4).ctime() == 'Wed Dec 4 00:00:00 2002'. ! d.ctime() is equivalent to time.ctime(time.mktime(d.timetuple())). - strftime(format) --- 478,488 ---- str(d) is equivalent to d.isoformat(). - ctime() Return a string representing the date, for example ! datetime(2002, 12, 4, 20, 30, 40).ctime() == 'Wed Dec 4 20:30:40 2002'. ! d.ctime() is equivalent to time.ctime(time.mktime(d.timetuple())) ! on platforms where the native C ctime() function (which time.ctime() ! invokes, but which datetime.ctime() does not invoke) conforms to the ! C standard. - strftime(format) Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.44 retrieving revision 1.45 diff -C2 -d -r1.44 -r1.45 *** test_both.py 6 Dec 2002 05:13:40 -0000 1.44 --- test_both.py 6 Dec 2002 20:26:24 -0000 1.45 *************** *** 833,839 **** self.assertEqual(str(t), "0002-03-02 04:05:01.000123") ! def test_ctime(self): t = self.theclass(2002, 3, 2, 18, 3, 5, 123) self.assertEqual(t.ctime(), "Sat Mar 2 18:03:05 2002") def test_tz_independent_comparing(self): --- 833,847 ---- self.assertEqual(str(t), "0002-03-02 04:05:01.000123") ! def test_more_ctime(self): ! # Test fields that TestDate doesn't touch. ! import time ! t = self.theclass(2002, 3, 2, 18, 3, 5, 123) self.assertEqual(t.ctime(), "Sat Mar 2 18:03:05 2002") + # Oops! The next line fails on Win2K under MSVC 6, so it's commented + # out. The difference is that t.ctime() produces " 2" for the day, + # but platform ctime() produces "02" for the day. According to + # C99, t.ctime() is correct here. + # self.assertEqual(t.ctime(), time.ctime(time.mktime(t.timetuple()))) def test_tz_independent_comparing(self): From tim_one@users.sourceforge.net Fri Dec 6 20:32:32 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 06 Dec 2002 12:32:32 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime test_both.py,1.45,1.46 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv31223 Modified Files: test_both.py Log Message: Added a ctime() test that doesn't care about the platform differences in time.ctime(). Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.45 retrieving revision 1.46 diff -C2 -d -r1.45 -r1.46 *** test_both.py 6 Dec 2002 20:26:24 -0000 1.45 --- test_both.py 6 Dec 2002 20:32:23 -0000 1.46 *************** *** 845,848 **** --- 845,852 ---- # self.assertEqual(t.ctime(), time.ctime(time.mktime(t.timetuple()))) + # So test a case where that difference doesn't matter. + t = self.theclass(2002, 3, 22, 18, 3, 5, 123) + self.assertEqual(t.ctime(), time.ctime(time.mktime(t.timetuple()))) + def test_tz_independent_comparing(self): dt1 = self.theclass(2002, 3, 1, 9, 0, 0) From tim_one@users.sourceforge.net Fri Dec 6 21:03:18 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 06 Dec 2002 13:03:18 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime doc.txt,1.21,1.22 obj_datetime.c,1.27,1.28 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv7634 Modified Files: doc.txt obj_datetime.c Log Message: Finished datetime.isoformat. Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.21 retrieving revision 1.22 diff -C2 -d -r1.21 -r1.22 *** doc.txt 6 Dec 2002 20:26:23 -0000 1.21 --- doc.txt 6 Dec 2002 21:03:07 -0000 1.22 *************** *** 471,480 **** same as date.isocalendar(). ! XXX isoformat() needs work. ! - isoformat() ! Return a string representing the date in ISO 8601 format, ! 'YYYY-MM-DD'. For example, ! date(2002, 12, 4).isoformat() == '2002-12-04'. ! str(d) is equivalent to d.isoformat(). - ctime() --- 471,482 ---- same as date.isocalendar(). ! - isoformat(sep='T') ! Return a string representing the date and time in ISO 8601 format, ! YYYY-MM-DDTHH:MM:SS.mmmmmm ! Optional argument sep (default 'T') is a one-character separator, ! placed between the date and time portions of the result. For example, ! datetime(2002, 12, 4, 1, 2, 3, 4).isoformat(' ') == ! '2002-12-04 01:02:03.000004' ! str(d) is equivalent to d.isoformat(' '). - ctime() Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.27 retrieving revision 1.28 diff -C2 -d -r1.27 -r1.28 *** obj_datetime.c 6 Dec 2002 17:21:15 -0000 1.27 --- obj_datetime.c 6 Dec 2002 21:03:09 -0000 1.28 *************** *** 356,362 **** { char buffer[1000]; ! char *typename; - typename = self->ob_type->tp_name; if (GET_MICROSECOND(self)) { PyOS_snprintf(buffer, sizeof(buffer), --- 356,361 ---- { char buffer[1000]; ! char *typename = self->ob_type->tp_name; if (GET_MICROSECOND(self)) { PyOS_snprintf(buffer, sizeof(buffer), *************** *** 388,392 **** datetime_isoformat_helper(PyDateTime_DateTime *self, char sep) { ! char buffer[128]; char *cp; --- 387,391 ---- datetime_isoformat_helper(PyDateTime_DateTime *self, char sep) { ! char buffer[100]; char *cp; From theller@users.sourceforge.net Fri Dec 6 22:42:15 2002 From: theller@users.sourceforge.net (theller@users.sourceforge.net) Date: Fri, 06 Dec 2002 14:42:15 -0800 Subject: [Python-checkins] python/dist/src/Doc/api exceptions.tex,1.12,1.13 init.tex,1.4,1.5 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/api In directory sc8-pr-cvs1:/tmp/cvs-serv21911 Modified Files: exceptions.tex init.tex Log Message: Typo: propogate -> propagate Bugfix candidate. Index: exceptions.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/api/exceptions.tex,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** exceptions.tex 24 Oct 2002 20:54:18 -0000 1.12 --- exceptions.tex 6 Dec 2002 22:42:13 -0000 1.13 *************** *** 20,24 **** error. If returning due to an error, it is important to indicate to the caller that an error has been set. If the error is not handled or ! carefully propogated, additional calls into the Python/C API may not behave as intended and may fail in mysterious ways. --- 20,24 ---- error. If returning due to an error, it is important to indicate to the caller that an error has been set. If the error is not handled or ! carefully propagated, additional calls into the Python/C API may not behave as intended and may fail in mysterious ways. Index: init.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/api/init.tex,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** init.tex 10 Oct 2002 18:24:50 -0000 1.4 --- init.tex 6 Dec 2002 22:42:13 -0000 1.5 *************** *** 658,662 **** store state in the dictionary. If this function returns \NULL, an exception has been raised and the caller should allow it to ! propogate. \end{cfuncdesc} --- 658,662 ---- store state in the dictionary. If this function returns \NULL, an exception has been raised and the caller should allow it to ! propagate. \end{cfuncdesc} *************** *** 716,720 **** being executed. The effect of this is that as exception propogation causes the Python stack to unwind, the callback is called upon ! return to each frame as the exception propogates. Only trace functions receives these events; they are not needed by the profiler. --- 716,720 ---- being executed. The effect of this is that as exception propogation causes the Python stack to unwind, the callback is called upon ! return to each frame as the exception propagates. Only trace functions receives these events; they are not needed by the profiler. From tim_one@users.sourceforge.net Fri Dec 6 23:38:07 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 06 Dec 2002 15:38:07 -0800 Subject: [Python-checkins] python/dist/src/Objects typeobject.c,2.194,2.195 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv18384/python/Objects Modified Files: typeobject.c Log Message: slot_tp_hash(): In the normal path, this leaked a reference to the integer hash object returned by __hash__(). This accounts for some of the "mystery leaks" in the sandbox datetime tests, but probably not all of them. Index: typeobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/typeobject.c,v retrieving revision 2.194 retrieving revision 2.195 diff -C2 -d -r2.194 -r2.195 *** typeobject.c 27 Nov 2002 16:29:25 -0000 2.194 --- typeobject.c 6 Dec 2002 23:38:02 -0000 2.195 *************** *** 3942,3948 **** slot_tp_hash(PyObject *self) { ! PyObject *func, *res; static PyObject *hash_str, *eq_str, *cmp_str; - long h; --- 3942,3947 ---- slot_tp_hash(PyObject *self) { ! PyObject *func; static PyObject *hash_str, *eq_str, *cmp_str; long h; *************** *** 3950,3958 **** if (func != NULL) { ! res = PyEval_CallObject(func, NULL); Py_DECREF(func); if (res == NULL) return -1; h = PyInt_AsLong(res); } else { --- 3949,3958 ---- if (func != NULL) { ! PyObject *res = PyEval_CallObject(func, NULL); Py_DECREF(func); if (res == NULL) return -1; h = PyInt_AsLong(res); + Py_DECREF(res); } else { From tim_one@users.sourceforge.net Sat Dec 7 02:12:34 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 06 Dec 2002 18:12:34 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime test_both.py,1.46,1.47 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv13915 Modified Files: test_both.py Log Message: Added refcount-based leak detection as discussed on Python-Dev. Pass option--leak under a debug build to trigger this (it will run the tests in an infinite loop then, and print stuff after each run). Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.46 retrieving revision 1.47 diff -C2 -d -r1.46 -r1.47 *** test_both.py 6 Dec 2002 20:32:23 -0000 1.46 --- test_both.py 7 Dec 2002 02:12:31 -0000 1.47 *************** *** 5,8 **** --- 5,11 ---- Pass c on the cmdline to test the C implementation; else the Python implementation is tested. + + Run with --leak under a debug build to get some simple but powerful leak + detection. """ *************** *** 1122,1128 **** def test_main(): r = unittest.TextTestRunner(stream=sys.stdout, verbosity=2) s = test_suite() ! r.run(s) if __name__ == "__main__": --- 1125,1150 ---- def test_main(): + import gc + import sys + r = unittest.TextTestRunner(stream=sys.stdout, verbosity=2) s = test_suite() ! lastrc = None ! while True: ! r.run(s) ! gc.collect() ! if gc.garbage: ! raise SystemError("gc.garbage not empty after test run: %r" % ! gc.garbage) ! if hasattr(sys, 'gettotalrefcount'): ! thisrc = sys.gettotalrefcount() ! print '*' * 10, 'total refs:', thisrc, ! if lastrc: ! print 'delta:', thisrc - lastrc ! else: ! print ! lastrc = thisrc ! if '--leak' not in sys.argv: ! break if __name__ == "__main__": From tim_one@users.sourceforge.net Sat Dec 7 02:23:10 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 06 Dec 2002 18:23:10 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.c,1.44,1.45 obj_delta.c,1.22,1.23 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv17644 Modified Files: datetime.c obj_delta.c Log Message: Fixed mismatches between integer format codes and integer args, as Jeremy helpfully passed on via gcc wngs. If you see a wng in this code, pass it on! "No warnings" is a goal. Index: datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.c,v retrieving revision 1.44 retrieving revision 1.45 diff -C2 -d -r1.44 -r1.45 *** datetime.c 6 Dec 2002 17:04:58 -0000 1.44 --- datetime.c 7 Dec 2002 02:23:08 -0000 1.45 *************** *** 116,120 **** * on boxes where sizeof(long) > sizeof(int). So roll our own. */ ! PyOS_snprintf(buf, sizeof(buf), "days=%ld; must have magnitude <= %ld", days, MAX_DELTA_DAYS); PyErr_SetString(exception, buf); --- 116,120 ---- * on boxes where sizeof(long) > sizeof(int). So roll our own. */ ! PyOS_snprintf(buf, sizeof(buf), "days=%ld; must have magnitude <= %d", days, MAX_DELTA_DAYS); PyErr_SetString(exception, buf); Index: obj_delta.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_delta.c,v retrieving revision 1.22 retrieving revision 1.23 diff -C2 -d -r1.22 -r1.23 *** obj_delta.c 5 Dec 2002 04:49:42 -0000 1.22 --- obj_delta.c 7 Dec 2002 02:23:08 -0000 1.23 *************** *** 554,567 **** if (days) { ! i += sprintf(buf + i, "%d day%s, ", days, (days == 1 || days == -1) ? "" : "s"); assert(i < sizeof(buf)); } ! i += sprintf(buf + i, "%d:%02d:%02d", hours, minutes, seconds); assert(i < sizeof(buf)); if (us) { ! i += sprintf(buf + i, ".%06d", us); assert(i < sizeof(buf)); } --- 554,568 ---- if (days) { ! i += sprintf(buf + i, "%d day%s, ", (int)days, (days == 1 || days == -1) ? "" : "s"); assert(i < sizeof(buf)); } ! i += sprintf(buf + i, "%d:%02d:%02d", (int)hours, (int)minutes, ! (int)seconds); assert(i < sizeof(buf)); if (us) { ! i += sprintf(buf + i, ".%06d", (int)us); assert(i < sizeof(buf)); } From tim_one@users.sourceforge.net Sat Dec 7 02:28:20 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 06 Dec 2002 18:28:20 -0800 Subject: [Python-checkins] python/dist/src/Objects typeobject.c,2.126.4.28,2.126.4.29 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv20552/22/Objects Modified Files: Tag: release22-maint typeobject.c Log Message: Backport from head. slot_tp_hash(): In the normal path, this leaked a reference to the integer hash object returned by __hash__(). Index: typeobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/typeobject.c,v retrieving revision 2.126.4.28 retrieving revision 2.126.4.29 diff -C2 -d -r2.126.4.28 -r2.126.4.29 *** typeobject.c 18 Oct 2002 16:45:38 -0000 2.126.4.28 --- typeobject.c 7 Dec 2002 02:28:17 -0000 2.126.4.29 *************** *** 3279,3285 **** slot_tp_hash(PyObject *self) { ! PyObject *func, *res; static PyObject *hash_str, *eq_str, *cmp_str; - long h; --- 3279,3284 ---- slot_tp_hash(PyObject *self) { ! PyObject *func; static PyObject *hash_str, *eq_str, *cmp_str; long h; *************** *** 3287,3295 **** if (func != NULL) { ! res = PyEval_CallObject(func, NULL); Py_DECREF(func); if (res == NULL) return -1; h = PyInt_AsLong(res); } else { --- 3286,3295 ---- if (func != NULL) { ! PyObject *res = PyEval_CallObject(func, NULL); Py_DECREF(func); if (res == NULL) return -1; h = PyInt_AsLong(res); + Py_DECREF(res); } else { From tim_one@users.sourceforge.net Sat Dec 7 02:43:31 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 06 Dec 2002 18:43:31 -0800 Subject: [Python-checkins] python/dist/src/Modules cPickle.c,2.96,2.97 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv25859/python/Modules Modified Files: cPickle.c Log Message: A patch from Kevin Jacobs, plugging several leaks discovered when running the sandbox datetime tests. Bugfix candidate. Index: cPickle.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/cPickle.c,v retrieving revision 2.96 retrieving revision 2.97 diff -C2 -d -r2.96 -r2.97 *** cPickle.c 16 Sep 2002 17:26:23 -0000 2.96 --- cPickle.c 7 Dec 2002 02:43:28 -0000 2.97 *************** *** 226,233 **** } - #define PDATA_APPEND_(D,O,ER) { \ - if (Pdata_Append(((Pdata*)(D)), O) < 0) return ER; \ - } - #define PDATA_APPEND(D,O,ER) { \ if (((Pdata*)(D))->length == ((Pdata*)(D))->size && \ --- 226,229 ---- *************** *** 898,901 **** --- 894,898 ---- return 0; if (PyDict_GetItem(self->fast_memo, key)) { + Py_DECREF(key); PyErr_Format(PyExc_ValueError, "fast mode: can't pickle cyclic objects including object type %s at %p", *************** *** 905,911 **** --- 902,910 ---- } if (PyDict_SetItem(self->fast_memo, key, Py_None) < 0) { + Py_DECREF(key); self->fast_container = -1; return 0; } + Py_DECREF(key); } return 1; *************** *** 920,925 **** --- 919,926 ---- return 0; if (PyDict_DelItem(self->fast_memo, key) < 0) { + Py_DECREF(key); return 0; } + Py_DECREF(key); } return 1; *************** *** 3116,3119 **** --- 3117,3121 ---- return NULL; } + Py_DECREF(safe); } *************** *** 3219,3223 **** if ((len = (*self->readline_func)(self, &s)) >= 0) { ! if (len < 2) return bad_readline(); if ((class_name = PyString_FromStringAndSize(s, len - 1))) { class = find_class(module_name, class_name, --- 3221,3228 ---- if ((len = (*self->readline_func)(self, &s)) >= 0) { ! if (len < 2) { ! Py_DECREF(module_name); ! return bad_readline(); ! } if ((class_name = PyString_FromStringAndSize(s, len - 1))) { class = find_class(module_name, class_name, From tim_one@users.sourceforge.net Sat Dec 7 03:12:59 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 06 Dec 2002 19:12:59 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_date.c,1.35,1.36 obj_datetime.c,1.28,1.29 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv4101 Modified Files: obj_date.c obj_datetime.c Log Message: Fixed leaks in the date and datetime picklers. Along with the leaks in Python that got fixed, there are no leaks visible now in the Python or C implementations. Also reworked all the pickle support functions to raise errors when their arguments suck, instead of just asserting they're correct. While these are intended to be module-private functions, there's really nothing to stop a user from calling them. Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.35 retrieving revision 1.36 diff -C2 -d -r1.35 -r1.36 *** obj_date.c 6 Dec 2002 17:20:58 -0000 1.35 --- obj_date.c 7 Dec 2002 03:12:57 -0000 1.36 *************** *** 435,440 **** unsigned char *pdata = (unsigned char*)PyString_AsString(state); ! assert(len == _PyDateTime_DATE_DATA_SIZE); ! memcpy(self->data, pdata, _PyDateTime_DATE_DATA_SIZE); self->hashcode = -1; --- 435,444 ---- unsigned char *pdata = (unsigned char*)PyString_AsString(state); ! if (! PyString_Check(state) || ! len != _PyDateTime_DATE_DATA_SIZE) { ! PyErr_SetString(PyExc_TypeError, ! "bad argument to date.__setstate__"); ! return NULL; ! } memcpy(self->data, pdata, _PyDateTime_DATE_DATA_SIZE); self->hashcode = -1; *************** *** 451,458 **** PyObject *result = NULL; ! assert(date->ob_type == &PyDateTime_DateType); state = date_getstate(date); ! if (state) result = Py_BuildValue("O(O)", date_unpickler_object, state); return result; } --- 455,469 ---- PyObject *result = NULL; ! if (date->ob_type != &PyDateTime_DateType) { ! PyErr_Format(PyExc_TypeError, ! "bad type passed to date pickler: %s", ! date->ob_type->tp_name); ! return NULL; ! } state = date_getstate(date); ! if (state) { result = Py_BuildValue("O(O)", date_unpickler_object, state); + Py_DECREF(state); + } return result; } *************** *** 464,468 **** if (! PyString_CheckExact(arg)) { ! PyErr_BadInternalCall(); return NULL; } --- 475,481 ---- if (! PyString_CheckExact(arg)) { ! PyErr_Format(PyExc_TypeError, ! "bad type passed to date unpickler: %s", ! arg->ob_type->tp_name); return NULL; } Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.28 retrieving revision 1.29 diff -C2 -d -r1.28 -r1.29 *** obj_datetime.c 6 Dec 2002 21:03:09 -0000 1.28 --- obj_datetime.c 7 Dec 2002 03:12:57 -0000 1.29 *************** *** 497,502 **** unsigned char *pdata = (unsigned char*)PyString_AsString(state); ! assert(len == _PyDateTime_DATETIME_DATA_SIZE); ! memcpy(self->data, pdata, _PyDateTime_DATETIME_DATA_SIZE); self->hashcode = -1; --- 497,506 ---- unsigned char *pdata = (unsigned char*)PyString_AsString(state); ! if (! PyString_Check(state) || ! len != _PyDateTime_DATETIME_DATA_SIZE) { ! PyErr_SetString(PyExc_TypeError, ! "bad argument to datetime.__setstate__"); ! return NULL; ! } memcpy(self->data, pdata, _PyDateTime_DATETIME_DATA_SIZE); self->hashcode = -1; *************** *** 513,522 **** PyObject *result = NULL; ! assert(datetime->ob_type == &PyDateTime_DateTimeType); state = datetime_getstate(datetime); ! if (state) result = Py_BuildValue("O(O)", datetime_unpickler_object, state); return result; } --- 517,533 ---- PyObject *result = NULL; ! if (datetime->ob_type != &PyDateTime_DateTimeType) { ! PyErr_Format(PyExc_TypeError, ! "bad type passed to datetime pickler: %s", ! datetime->ob_type->tp_name); ! return NULL; ! } state = datetime_getstate(datetime); ! if (state) { result = Py_BuildValue("O(O)", datetime_unpickler_object, state); + Py_DECREF(state); + } return result; } *************** *** 528,532 **** if (! PyString_CheckExact(arg)) { ! PyErr_BadInternalCall(); return NULL; } --- 539,545 ---- if (! PyString_CheckExact(arg)) { ! PyErr_Format(PyExc_TypeError, ! "bad type passed to datetime unpickler: %s", ! arg->ob_type->tp_name); return NULL; } From tim_one@users.sourceforge.net Sat Dec 7 05:33:47 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Fri, 06 Dec 2002 21:33:47 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime doc.txt,1.22,1.23 obj_datetime.c,1.29,1.30 test_both.py,1.47,1.48 test_datetime.py,1.54,1.55 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv4986 Modified Files: doc.txt obj_datetime.c test_both.py test_datetime.py Log Message: Implement etc datetime.date(). The portion of test_datetime.py testing this has been moved into test_both.py. Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.22 retrieving revision 1.23 diff -C2 -d -r1.22 -r1.23 *** doc.txt 6 Dec 2002 21:03:07 -0000 1.22 --- doc.txt 7 Dec 2002 05:33:44 -0000 1.23 *************** *** 444,447 **** --- 444,450 ---- Instance methods: + - date() + Return new date object with same year, month and day. + - timetuple() Return a 9-element tuple of the form returned by time.localtime(). Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.29 retrieving revision 1.30 diff -C2 -d -r1.29 -r1.30 *** obj_datetime.c 7 Dec 2002 03:12:57 -0000 1.29 --- obj_datetime.c 7 Dec 2002 05:33:45 -0000 1.30 *************** *** 482,485 **** --- 482,493 ---- } + static PyObject * + datetime_getdate(PyDateTime_DateTime *self) + { + return new_date((int)GET_YEAR(self), + (int)GET_MONTH(self), + (int)GET_DAY(self)); + } + /* Pickle support. Quite a maze! */ *************** *** 580,583 **** --- 588,594 ---- {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS, "Return time tuple, compatible with time.localtime()."}, + + {"date", (PyCFunction)datetime_getdate, METH_NOARGS, + "Return date object with same year, month and day."}, {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS, Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.47 retrieving revision 1.48 diff -C2 -d -r1.47 -r1.48 *** test_both.py 7 Dec 2002 02:12:31 -0000 1.47 --- test_both.py 7 Dec 2002 05:33:45 -0000 1.48 *************** *** 1113,1116 **** --- 1113,1122 ---- "12 31 04 33 22 06 366") + def test_extract(self): + dt = self.theclass(2002, 3, 4, 18, 45, 3, 1234) + self.assertEqual(dt.date(), date(2002, 3, 4)) + # Next line is in test_datetime now. + # self.assertEqual(dt.time(), time(18, 45, 3, 1234)) + def test_suite(): allsuites = [unittest.makeSuite(klass, 'test') Index: test_datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_datetime.py,v retrieving revision 1.54 retrieving revision 1.55 diff -C2 -d -r1.54 -r1.55 *** test_datetime.py 4 Dec 2002 23:08:49 -0000 1.54 --- test_datetime.py 7 Dec 2002 05:33:45 -0000 1.55 *************** *** 194,198 **** def test_extract(self): dt = self.theclass(2002, 3, 4, 18, 45, 3, 1234) ! self.assertEqual(dt.date(), date(2002, 3, 4)) self.assertEqual(dt.time(), time(18, 45, 3, 1234)) --- 194,199 ---- def test_extract(self): dt = self.theclass(2002, 3, 4, 18, 45, 3, 1234) ! # Next line is in test_both now. ! # self.assertEqual(dt.date(), date(2002, 3, 4)) self.assertEqual(dt.time(), time(18, 45, 3, 1234)) From rhettinger@users.sourceforge.net Sat Dec 7 08:10:53 2002 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Sat, 07 Dec 2002 00:10:53 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_types.py,1.43,1.44 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv19914/Lib/test Modified Files: test_types.py Log Message: Remove assumption that cls is a subclass of dict. Simplifies the code and gets Just van Rossum's example to work. Index: test_types.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_types.py,v retrieving revision 1.43 retrieving revision 1.44 diff -C2 -d -r1.43 -r1.44 *** test_types.py 5 Dec 2002 21:32:32 -0000 1.43 --- test_types.py 7 Dec 2002 08:10:51 -0000 1.44 *************** *** 567,573 **** def __new__(cls, *args, **kwargs): return UserDict(*args, **kwargs) ! try: mydict.fromkeys('a b c'.split()) ! except TypeError: pass ! else: raise TestFailed, 'dict.fromkeys() failed to detect non-dict class.' # dict.copy() d = {1:1, 2:2, 3:3} --- 567,573 ---- def __new__(cls, *args, **kwargs): return UserDict(*args, **kwargs) ! ud = mydict.fromkeys('ab') ! if ud != {'a':None, 'b':None} or not isinstance(ud,UserDict): ! raise TestFailed, 'fromkeys did not instantiate using __new__' # dict.copy() d = {1:1, 2:2, 3:3} From rhettinger@users.sourceforge.net Sat Dec 7 08:10:53 2002 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Sat, 07 Dec 2002 00:10:53 -0800 Subject: [Python-checkins] python/dist/src/Objects dictobject.c,2.134,2.135 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv19914/Objects Modified Files: dictobject.c Log Message: Remove assumption that cls is a subclass of dict. Simplifies the code and gets Just van Rossum's example to work. Index: dictobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/dictobject.c,v retrieving revision 2.134 retrieving revision 2.135 diff -C2 -d -r2.134 -r2.135 *** dictobject.c 4 Dec 2002 07:32:25 -0000 2.134 --- dictobject.c 7 Dec 2002 08:10:51 -0000 2.135 *************** *** 980,989 **** if (d == NULL) return NULL; - if (!PyDict_Check(d)) { - Py_DECREF(d); - PyErr_SetString(PyExc_TypeError, - "class constructor must return a subclass of dict"); - return NULL; - } it = PyObject_GetIter(seq); --- 980,983 ---- *************** *** 1000,1004 **** break; } ! status = PyDict_SetItem(d, key, value); Py_DECREF(key); if (status < 0) --- 994,998 ---- break; } ! status = PyObject_SetItem(d, key, value); Py_DECREF(key); if (status < 0) From rhettinger@users.sourceforge.net Sat Dec 7 09:04:31 2002 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Sat, 07 Dec 2002 01:04:31 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_types.py,1.44,1.45 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv9527 Modified Files: test_types.py Log Message: Cleaned up test (removing bogus argument list). Index: test_types.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_types.py,v retrieving revision 1.44 retrieving revision 1.45 diff -C2 -d -r1.44 -r1.45 *** test_types.py 7 Dec 2002 08:10:51 -0000 1.44 --- test_types.py 7 Dec 2002 09:04:29 -0000 1.45 *************** *** 565,570 **** from UserDict import UserDict class mydict(dict): ! def __new__(cls, *args, **kwargs): ! return UserDict(*args, **kwargs) ud = mydict.fromkeys('ab') if ud != {'a':None, 'b':None} or not isinstance(ud,UserDict): --- 565,570 ---- from UserDict import UserDict class mydict(dict): ! def __new__(cls): ! return UserDict() ud = mydict.fromkeys('ab') if ud != {'a':None, 'b':None} or not isinstance(ud,UserDict): From rhettinger@users.sourceforge.net Sat Dec 7 09:25:08 2002 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Sat, 07 Dec 2002 01:25:08 -0800 Subject: [Python-checkins] python/dist/src/Lib random.py,1.39,1.40 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv13570 Modified Files: random.py Log Message: Clarify and speedup test. Index: random.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/random.py,v retrieving revision 1.39 retrieving revision 1.40 diff -C2 -d -r1.39 -r1.40 *** random.py 18 Nov 2002 09:01:21 -0000 1.39 --- random.py 7 Dec 2002 09:25:05 -0000 1.40 *************** *** 775,780 **** for k in xrange(n+1): s = sample(population, k) ! assert len(dict([(elem,True) for elem in s])) == len(s) == k ! assert None not in s def _sample_generator(n, k): --- 775,781 ---- for k in xrange(n+1): s = sample(population, k) ! uniq = dict.fromkeys(s) ! assert len(uniq) == len(s) == k ! assert None not in uniq def _sample_generator(n, k): From rhettinger@users.sourceforge.net Sat Dec 7 09:39:17 2002 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Sat, 07 Dec 2002 01:39:17 -0800 Subject: [Python-checkins] python/dist/src/Doc/ref ref6.tex,1.56,1.57 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/ref In directory sc8-pr-cvs1:/tmp/cvs-serv16226 Modified Files: ref6.tex Log Message: Add __all__ to Reference Manual index. Closes SF 643227. Index: ref6.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/ref/ref6.tex,v retrieving revision 1.56 retrieving revision 1.57 diff -C2 -d -r1.56 -r1.57 *** ref6.tex 18 Oct 2002 15:18:18 -0000 1.56 --- ref6.tex 7 Dec 2002 09:39:15 -0000 1.57 *************** *** 704,707 **** --- 704,708 ---- module's namespace which do not begin with an underscore character (\character{_}). + \index{__all__} The \keyword{from} form with \samp{*} may only occur in a module From rhettinger@users.sourceforge.net Sat Dec 7 09:41:23 2002 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Sat, 07 Dec 2002 01:41:23 -0800 Subject: [Python-checkins] python/dist/src/Doc/ref ref6.tex,1.47.4.4,1.47.4.5 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/ref In directory sc8-pr-cvs1:/tmp/cvs-serv16659 Modified Files: Tag: release22-maint ref6.tex Log Message: Add __all__ to Reference Manual index. Closes SF 643227. Index: ref6.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/ref/ref6.tex,v retrieving revision 1.47.4.4 retrieving revision 1.47.4.5 diff -C2 -d -r1.47.4.4 -r1.47.4.5 *** ref6.tex 18 Oct 2002 15:19:11 -0000 1.47.4.4 --- ref6.tex 7 Dec 2002 09:41:21 -0000 1.47.4.5 *************** *** 704,707 **** --- 704,708 ---- module's namespace which do not begin with an underscore character (\character{_}). + \index{__all__} The \keyword{from} form with \samp{*} may only occur in a module From rhettinger@users.sourceforge.net Sat Dec 7 10:05:29 2002 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Sat, 07 Dec 2002 02:05:29 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_pow.py,1.15,1.16 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv21241/Lib/test Modified Files: test_pow.py Log Message: Fix typo in abstract.c which caused __rpow__ to not be invoked. Added related testcase. Closes SF bug #643260. Index: test_pow.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_pow.py,v retrieving revision 1.15 retrieving revision 1.16 diff -C2 -d -r1.15 -r1.16 *** test_pow.py 23 Jul 2002 19:03:58 -0000 1.15 --- test_pow.py 7 Dec 2002 10:05:27 -0000 1.16 *************** *** 119,120 **** --- 119,125 ---- n = pow(long(i),j,k) if o != n: print 'Integer mismatch:', i,j,k + + class TestRpow: + def __rpow__(self, other): + return None + None ** TestRpow() # Won't fail when __rpow__ invoked. SF bug #643260. From rhettinger@users.sourceforge.net Sat Dec 7 10:05:29 2002 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Sat, 07 Dec 2002 02:05:29 -0800 Subject: [Python-checkins] python/dist/src/Objects abstract.c,2.109,2.110 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv21241/Objects Modified Files: abstract.c Log Message: Fix typo in abstract.c which caused __rpow__ to not be invoked. Added related testcase. Closes SF bug #643260. Index: abstract.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/abstract.c,v retrieving revision 2.109 retrieving revision 2.110 diff -C2 -d -r2.109 -r2.110 *** abstract.c 24 Nov 2002 01:34:49 -0000 2.109 --- abstract.c 7 Dec 2002 10:05:25 -0000 2.110 *************** *** 469,473 **** slotv = NB_TERNOP(mv, op_slot); if (w->ob_type != v->ob_type && ! mv != NULL && NEW_STYLE_NUMBER(w)) { slotw = NB_TERNOP(mw, op_slot); if (slotw == slotv) --- 469,473 ---- slotv = NB_TERNOP(mv, op_slot); if (w->ob_type != v->ob_type && ! mw != NULL && NEW_STYLE_NUMBER(w)) { slotw = NB_TERNOP(mw, op_slot); if (slotw == slotv) From rhettinger@users.sourceforge.net Sat Dec 7 10:15:40 2002 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Sat, 07 Dec 2002 02:15:40 -0800 Subject: [Python-checkins] python/dist/src/Objects abstract.c,2.93.6.8,2.93.6.9 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv23477/Objects Modified Files: Tag: release22-maint abstract.c Log Message: Fix typo in abstract.c which caused __rpow__ to not be invoked. Added related testcase. Closes SF bug #643260. Index: abstract.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/abstract.c,v retrieving revision 2.93.6.8 retrieving revision 2.93.6.9 diff -C2 -d -r2.93.6.8 -r2.93.6.9 *** abstract.c 5 Oct 2002 21:14:12 -0000 2.93.6.8 --- abstract.c 7 Dec 2002 10:15:38 -0000 2.93.6.9 *************** *** 469,473 **** slotv = *NB_TERNOP(mv, op_slot); if (w->ob_type != v->ob_type && ! mv != NULL && NEW_STYLE_NUMBER(w)) { slotw = *NB_TERNOP(mw, op_slot); if (slotw == slotv) --- 469,473 ---- slotv = *NB_TERNOP(mv, op_slot); if (w->ob_type != v->ob_type && ! mw != NULL && NEW_STYLE_NUMBER(w)) { slotw = *NB_TERNOP(mw, op_slot); if (slotw == slotv) From rhettinger@users.sourceforge.net Sat Dec 7 10:15:40 2002 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Sat, 07 Dec 2002 02:15:40 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_pow.py,1.13,1.13.14.1 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv23477/Lib/test Modified Files: Tag: release22-maint test_pow.py Log Message: Fix typo in abstract.c which caused __rpow__ to not be invoked. Added related testcase. Closes SF bug #643260. Index: test_pow.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_pow.py,v retrieving revision 1.13 retrieving revision 1.13.14.1 diff -C2 -d -r1.13 -r1.13.14.1 *** test_pow.py 4 Sep 2001 06:37:28 -0000 1.13 --- test_pow.py 7 Dec 2002 10:15:38 -0000 1.13.14.1 *************** *** 119,120 **** --- 119,125 ---- n = pow(long(i),j,k) if o != n: print 'Integer mismatch:', i,j,k + + class TestRpow: + def __rpow__(self, other): + return None + None ** TestRpow() # Won't fail when __rpow__ invoked. SF bug #643260. From rhettinger@users.sourceforge.net Sat Dec 7 10:33:45 2002 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Sat, 07 Dec 2002 02:33:45 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_heapq.py,1.6,1.7 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv26106 Modified Files: test_heapq.py Log Message: Add another test which exercises the whole suite with a heapsort and verifies the result against list.sort(). Index: test_heapq.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_heapq.py,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** test_heapq.py 3 Aug 2002 10:10:10 -0000 1.6 --- test_heapq.py 7 Dec 2002 10:33:42 -0000 1.7 *************** *** 71,74 **** --- 71,88 ---- heapreplace(heap, item) vereq(list(heapiter(heap)), data_sorted[-10:]) + # 6) Exercise everything with repeated heapsort checks + for trial in xrange(100): + size = random.randrange(50) + data = [random.randrange(25) for i in range(size)] + if trial & 1: # Half of the time, use heapify + heap = data[:] + heapify(heap) + else: # The rest of the time, use heappush + heap = [] + for item in data: + heappush(heap,item) + data.sort() + sorted = [heappop(heap) for i in range(size)] + vereq(data, sorted) # Make user happy if verbose: From loewis@users.sourceforge.net Sat Dec 7 14:41:21 2002 From: loewis@users.sourceforge.net (loewis@users.sourceforge.net) Date: Sat, 07 Dec 2002 06:41:21 -0800 Subject: [Python-checkins] python/dist/src setup.py,1.122,1.123 Message-ID: Update of /cvsroot/python/python/dist/src In directory sc8-pr-cvs1:/tmp/cvs-serv19611 Modified Files: setup.py Log Message: Correct db3 /opt/sfw library path. Link ndbm with libc only if ndbm.h is present and libndbm is not. Add runtime libs to dbm if linked against Berkeley DB. Index: setup.py =================================================================== RCS file: /cvsroot/python/python/dist/src/setup.py,v retrieving revision 1.122 retrieving revision 1.123 diff -C2 -d -r1.122 -r1.123 *** setup.py 6 Dec 2002 10:25:02 -0000 1.122 --- setup.py 7 Dec 2002 14:41:17 -0000 1.123 *************** *** 477,481 **** '/usr/local/BerkeleyDB.3.0/lib', '/usr/local/lib', ! '/opt/sfw', '/sw/lib', ), --- 477,481 ---- '/usr/local/BerkeleyDB.3.0/lib', '/usr/local/lib', ! '/opt/sfw/lib', '/sw/lib', ), *************** *** 543,556 **** # The standard Unix dbm module: if platform not in ['cygwin']: ! if (self.compiler.find_library_file(lib_dirs, 'ndbm') ! and find_file("ndbm.h", inc_dirs, []) is not None): exts.append( Extension('dbm', ['dbmmodule.c'], define_macros=[('HAVE_NDBM_H',None)], ! libraries = ['ndbm'] ) ) ! elif (platform in ['darwin'] ! and find_file("ndbm.h", inc_dirs, []) is not None): ! # Darwin has ndbm in libc ! exts.append( Extension('dbm', ['dbmmodule.c'], ! define_macros=[('HAVE_NDBM_H',None)]) ) elif (self.compiler.find_library_file(lib_dirs, 'gdbm') and find_file("gdbm/ndbm.h", inc_dirs, []) is not None): --- 543,555 ---- # The standard Unix dbm module: if platform not in ['cygwin']: ! if find_file("ndbm.h", inc_dirs, []) is not None: ! # Some systems have -lndbm, others don't ! if self.compiler.find_library_file(lib_dirs, 'ndbm'): ! ndbm_libs = ['ndbm'] ! else: ! ndbm_libs = [] exts.append( Extension('dbm', ['dbmmodule.c'], define_macros=[('HAVE_NDBM_H',None)], ! libraries = ndbm_libs ) ) elif (self.compiler.find_library_file(lib_dirs, 'gdbm') and find_file("gdbm/ndbm.h", inc_dirs, []) is not None): *************** *** 560,564 **** elif db_incs is not None: exts.append( Extension('dbm', ['dbmmodule.c'], ! library_dirs=[dblib_dir], include_dirs=db_incs, define_macros=[('HAVE_BERKDB_H',None), --- 559,564 ---- elif db_incs is not None: exts.append( Extension('dbm', ['dbmmodule.c'], ! library_dirs=dblib_dir, ! runtime_library_dirs=dblib_dir, include_dirs=db_incs, define_macros=[('HAVE_BERKDB_H',None), From loewis@users.sourceforge.net Sat Dec 7 14:56:39 2002 From: loewis@users.sourceforge.net (loewis@users.sourceforge.net) Date: Sat, 07 Dec 2002 06:56:39 -0800 Subject: [Python-checkins] python/dist/src/Modules unicodedata.c,2.26,2.27 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv23799 Modified Files: unicodedata.c Log Message: Remove C++ comment. Index: unicodedata.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/unicodedata.c,v retrieving revision 2.26 retrieving revision 2.27 diff -C2 -d -r2.26 -r2.27 *** unicodedata.c 25 Nov 2002 09:13:35 -0000 2.26 --- unicodedata.c 7 Dec 2002 14:56:36 -0000 2.27 *************** *** 432,436 **** cskipped--; i++; ! goto again; // continue while } } --- 432,436 ---- cskipped--; i++; ! goto again; /* continue while */ } } From loewis@users.sourceforge.net Sat Dec 7 14:57:14 2002 From: loewis@users.sourceforge.net (loewis@users.sourceforge.net) Date: Sat, 07 Dec 2002 06:57:14 -0800 Subject: [Python-checkins] python/dist/src/Modules _tkinter.c,1.134,1.135 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv23895 Modified Files: _tkinter.c Log Message: Remove C++ comment. Silence unsigned char* cast warning. Index: _tkinter.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/_tkinter.c,v retrieving revision 1.134 retrieving revision 1.135 diff -C2 -d -r1.134 -r1.135 *** _tkinter.c 4 Dec 2002 19:54:36 -0000 1.134 --- _tkinter.c 7 Dec 2002 14:57:11 -0000 1.135 *************** *** 807,811 **** if (value->typePtr == app->ByteArrayType) { int size; ! char *data = Tcl_GetByteArrayFromObj(value, &size); return PyString_FromStringAndSize(data, size); } --- 807,811 ---- if (value->typePtr == app->ByteArrayType) { int size; ! char *data = (char*)Tcl_GetByteArrayFromObj(value, &size); return PyString_FromStringAndSize(data, size); } *************** *** 849,853 **** if (value->typePtr == app->ProcBodyType) { ! // fall through: return tcl object } --- 849,853 ---- if (value->typePtr == app->ProcBodyType) { ! /* fall through: return tcl object. */ } From fdrake@users.sourceforge.net Sat Dec 7 15:59:40 2002 From: fdrake@users.sourceforge.net (fdrake@users.sourceforge.net) Date: Sat, 07 Dec 2002 07:59:40 -0800 Subject: [Python-checkins] python/dist/src/Doc/ref ref6.tex,1.47.4.5,1.47.4.6 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/ref In directory sc8-pr-cvs1:/tmp/cvs-serv6154 Modified Files: Tag: release22-maint ref6.tex Log Message: Revise the __all__ index entry a touch. Index: ref6.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/ref/ref6.tex,v retrieving revision 1.47.4.5 retrieving revision 1.47.4.6 diff -C2 -d -r1.47.4.5 -r1.47.4.6 *** ref6.tex 7 Dec 2002 09:41:21 -0000 1.47.4.5 --- ref6.tex 7 Dec 2002 15:59:37 -0000 1.47.4.6 *************** *** 704,708 **** module's namespace which do not begin with an underscore character (\character{_}). ! \index{__all__} The \keyword{from} form with \samp{*} may only occur in a module --- 704,708 ---- module's namespace which do not begin with an underscore character (\character{_}). ! \withsubitem{(optional module attribute)}{\ttindex{__all__}} The \keyword{from} form with \samp{*} may only occur in a module From fdrake@users.sourceforge.net Sat Dec 7 16:00:03 2002 From: fdrake@users.sourceforge.net (fdrake@users.sourceforge.net) Date: Sat, 07 Dec 2002 08:00:03 -0800 Subject: [Python-checkins] python/dist/src/Doc/ref ref6.tex,1.57,1.58 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/ref In directory sc8-pr-cvs1:/tmp/cvs-serv6351 Modified Files: ref6.tex Log Message: Revise the __all__ index entry a touch. Index: ref6.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/ref/ref6.tex,v retrieving revision 1.57 retrieving revision 1.58 diff -C2 -d -r1.57 -r1.58 *** ref6.tex 7 Dec 2002 09:39:15 -0000 1.57 --- ref6.tex 7 Dec 2002 16:00:00 -0000 1.58 *************** *** 704,708 **** module's namespace which do not begin with an underscore character (\character{_}). ! \index{__all__} The \keyword{from} form with \samp{*} may only occur in a module --- 704,708 ---- module's namespace which do not begin with an underscore character (\character{_}). ! \withsubitem{(optional module attribute)}{\ttindex{__all__}} The \keyword{from} form with \samp{*} may only occur in a module From tim_one@users.sourceforge.net Sat Dec 7 16:36:19 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sat, 07 Dec 2002 08:36:19 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_time.c,NONE,1.1 datetime.c,1.45,1.46 datetime.h,1.10,1.11 obj_datetime.c,1.30,1.31 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv14470 Modified Files: datetime.c datetime.h obj_datetime.c Added Files: obj_time.c Log Message: Prepare to implement the time type. This is mostly massive macro renaming, since e.g. the old GET_HOUR will become too ambiguous to tolerate. That in turn triggered another round of long-line folding. The new obj_time.c is just a copy of obj_datetime.c, and isn't yet compiled. Added a struct decl and macros for the time type, so far unreferenced. Moved the struct decl for timedelta into the .h file, since it didn't make sense that it was the only one unexposed. --- NEW FILE: obj_time.c --- /* * PyDateTime_Time implementation. * XXX This is currently a copy of obj_datetime.c, and unused. */ /* Accessor properties. */ static PyObject * datetime_hour(PyDateTime_DateTime *self, void *unused) { return PyInt_FromLong(DATE_GET_HOUR(self)); } static PyObject * datetime_minute(PyDateTime_DateTime *self, void *unused) { return PyInt_FromLong(DATE_GET_MINUTE(self)); } static PyObject * datetime_second(PyDateTime_DateTime *self, void *unused) { return PyInt_FromLong(DATE_GET_SECOND(self)); } static PyObject * datetime_microsecond(PyDateTime_DateTime *self, void *unused) { return PyInt_FromLong(DATE_GET_MICROSECOND(self)); } static PyGetSetDef datetime_getset[] = { {"hour", (getter)datetime_hour}, {"minute", (getter)datetime_minute}, {"second", (getter)datetime_second}, {"microsecond", (getter)datetime_microsecond}, {NULL} }; /* Constructors. */ static PyObject * datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw) { PyObject *self = NULL; long year; long month; long day; long hour = 0; long minute = 0; long second = 0; long usecond = 0; static char *keywords[] = { "year", "month", "day", "hour", "minute", "second", "microsecond", NULL }; if (PyArg_ParseTupleAndKeywords(args, kw, "lll|llll", keywords, &year, &month, &day, &hour, &minute, &second, &usecond)) { if (year < MINYEAR || year > MAXYEAR) { PyErr_SetString(PyExc_ValueError, "year is out of range"); return NULL; } if (month < 1 || month > 12) { PyErr_SetString(PyExc_ValueError, "month must be in 1..12"); return NULL; } if (day < 1 || day > days_in_month(year, month)) { PyErr_SetString(PyExc_ValueError, "day is out of range for month"); return NULL; } if (hour < 0 || hour > 23) { PyErr_SetString(PyExc_ValueError, "hour must be in 0..23"); return NULL; } if (minute < 0 || minute > 59) { PyErr_SetString(PyExc_ValueError, "minute must be in 0..59"); return NULL; } if (second < 0 || second > 59) { PyErr_SetString(PyExc_ValueError, "second must be in 0..59"); return NULL; } if (usecond < 0 || usecond > 999999) { PyErr_SetString(PyExc_ValueError, "microsecond must be in 0..999999"); return NULL; } self = new_datetime(year, month, day, hour, minute, second, usecond); } return self; } /* TM_FUNC is the shared type of localtime() and gmtime(). */ typedef struct tm *(*TM_FUNC)(const time_t *timer); static PyObject * datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp) { struct tm *tm; time_t timet = (time_t)timestamp; long us = (long)((timestamp - (double)timet) * 1e6); PyObject *result = NULL; tm = f(&timet); if (tm) result = PyObject_CallFunction(cls, "lllllll", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, us); else PyErr_SetString(PyExc_ValueError, "timestamp out of range for " "platform localtime()/gmtime() function"); return result; } /* Return new local datetime from timestamp (Python timestamp -- a double). */ static PyObject * datetime_fromtimestamp(PyObject *self, PyObject *args) { PyObject *cls; double timestamp; PyObject *result = NULL; if (PyArg_ParseTuple(args, "Od:fromtimestamp", &cls, ×tamp)) result = datetime_from_timestamp(cls, localtime, timestamp); return result; } /* Return new UTC datetime from timestamp (Python timestamp -- a double). */ static PyObject * datetime_utcfromtimestamp(PyObject *self, PyObject *args) { PyObject *cls; double timestamp; PyObject *result = NULL; if (PyArg_ParseTuple(args, "Od:utcfromtimestamp", &cls, ×tamp)) result = datetime_from_timestamp(cls, gmtime, timestamp); return result; } static PyObject * datetime_now(PyObject *self, PyObject *cls) { /* XXX MAJOR: This needs to get some notion of current time * XXX to better than 1-second resolution. Doing this in a x- * XXX platform way is mondo painful. Maybe floattime() from * XXX timemodule.c is good enough? We're running out of bits * XXX in a typical time_t, though, and gettimeofday() should do * XXX better than floattime() -- but gettimeofday isn't portable. */ #if 0 /* XXX need to create the instance by calling cls(y,mon,d,h,min,s,u) */ struct timeval t; struct tm *tm; time_t timet; #ifdef GETTIMEOFDAY_NO_TZ gettimeofday(&t); #else /* !GETTIMEOFDAY_NO_TZ */ gettimeofday(&t, (struct timezone *)NULL); #endif /* !GETTIMEOFDAY_NO_TZ */ timet = t.tv_sec; tm = localtime(&timet); return PyObject_CallFunction(cls, "iiiiiil", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec, t.tv_usec); #else /* XXX need to create the instance by calling cls(y,mon,d,h,min,s,u) */ struct tm *tm; time_t timet; time(&timet); tm = localtime(&timet); return PyObject_CallFunction(cls, "llllll", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec); #endif } static PyObject * datetime_utcnow(PyObject *self, PyObject *cls) { /* XXX Like datetime_now, this would like to do better than * XXX 1-second resolution. */ struct tm *tm; time_t timet; time(&timet); tm = gmtime(&timet); return PyObject_CallFunction(cls, "llllll", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec); } /* datetime arithmetic. */ /* Force all the datetime fields into range. The parameters are both * inputs and outputs. Returns < 0 on error. */ static int normalize_datetime(long *year, long *month, long *day, long *hour, long *minute, long *second, long *microsecond) { normalize_pair(second, microsecond, 1000000); normalize_pair(minute, second, 60); normalize_pair(hour, minute, 60); normalize_pair(day, hour, 24); return normalize_date(year, month, day); } static PyObject * add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta) { /* Note that the C-level additions can't overflow, because of * invariant bounds on the member values. */ long year = GET_YEAR(date); long month = GET_MONTH(date); long day = GET_DAY(date) + GET_TD_DAYS(delta); long hour = DATE_GET_HOUR(date); long minute = DATE_GET_MINUTE(date); long second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta); long microsecond = DATE_GET_MICROSECOND(date) + GET_TD_MICROSECONDS(delta); if (normalize_datetime(&year, &month, &day, &hour, &minute, &second, µsecond) < 0) return NULL; else return new_datetime(year, month, day, hour, minute, second, microsecond); } static PyObject * sub_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta) { /* Note that the C-level subtractions can't overflow, because of * invariant bounds on the member values. */ long year = GET_YEAR(date); long month = GET_MONTH(date); long day = GET_DAY(date) - GET_TD_DAYS(delta); long hour = DATE_GET_HOUR(date); long minute = DATE_GET_MINUTE(date); long second = DATE_GET_SECOND(date) - GET_TD_SECONDS(delta); long microsecond = DATE_GET_MICROSECOND(date) - GET_TD_MICROSECONDS(delta); if (normalize_datetime(&year, &month, &day, &hour, &minute, &second, µsecond) < 0) return NULL; else return new_datetime(year, month, day, hour, minute, second, microsecond); } static PyObject * sub_datetime_datetime(PyDateTime_DateTime *left, PyDateTime_DateTime *right) { long days1 = ymd_to_ord(GET_YEAR(left), GET_MONTH(left), GET_DAY(left)); long days2 = ymd_to_ord(GET_YEAR(right), GET_MONTH(right), GET_DAY(right)); /* These can't overflow, since the values are normalized. At most * this gives the number of seconds in one day. */ long delta_s = (DATE_GET_HOUR(left) - DATE_GET_HOUR(right)) * 3600 + (DATE_GET_MINUTE(left) - DATE_GET_MINUTE(right)) * 60 + DATE_GET_SECOND(left) - DATE_GET_SECOND(right); long delta_us = DATE_GET_MICROSECOND(left) - DATE_GET_MICROSECOND(right); return new_delta(days1 - days2, delta_s, delta_us, 1); } static PyObject * datetime_add(PyObject *left, PyObject *right) { PyTypeObject *left_type = left->ob_type; PyTypeObject *right_type = right->ob_type; if (PyType_IsSubtype(left_type, &PyDateTime_DateTimeType)) { /* datetime + ??? */ if (PyType_IsSubtype(right_type, &PyDateTime_DeltaType)) /* datetime + delta */ return add_datetime_timedelta( (PyDateTime_DateTime *)left, (PyDateTime_Delta *)right); } else if (PyType_IsSubtype(left_type, &PyDateTime_DeltaType)) { /* delta + datetime */ return add_datetime_timedelta((PyDateTime_DateTime *) right, (PyDateTime_Delta *) left); } Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } static PyObject * datetime_subtract(PyObject *left, PyObject *right) { PyTypeObject *left_type = left->ob_type; PyTypeObject *right_type = right->ob_type; PyObject *result = Py_NotImplemented; if (PyType_IsSubtype(left_type, &PyDateTime_DateTimeType)) { /* datetime - ??? */ if (PyType_IsSubtype(right_type, &PyDateTime_DateTimeType)) { /* datetime - datetime */ result = sub_datetime_datetime( (PyDateTime_DateTime *)left, (PyDateTime_DateTime *)right); } else if (PyType_IsSubtype(right_type, &PyDateTime_DeltaType)) { /* datetime - delta */ result = sub_datetime_timedelta( (PyDateTime_DateTime *)left, (PyDateTime_Delta *)right); } } if (result == Py_NotImplemented) Py_INCREF(result); return result; } /* Various ways to turn a datetime into a string. */ static PyObject * datetime_repr(PyDateTime_DateTime *self) { char buffer[1000]; char *typename = self->ob_type->tp_name; if (DATE_GET_MICROSECOND(self)) { PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d, %d, %d, %d, %d, %d)", typename, GET_YEAR(self), GET_MONTH(self), GET_DAY(self), DATE_GET_HOUR(self), DATE_GET_MINUTE(self), DATE_GET_SECOND(self), DATE_GET_MICROSECOND(self)); } else if (DATE_GET_SECOND(self)) { PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d, %d, %d, %d, %d)", typename, GET_YEAR(self), GET_MONTH(self), GET_DAY(self), DATE_GET_HOUR(self), DATE_GET_MINUTE(self), DATE_GET_SECOND(self)); } else { PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d, %d, %d, %d)", typename, GET_YEAR(self), GET_MONTH(self), GET_DAY(self), DATE_GET_HOUR(self), DATE_GET_MINUTE(self)); } return PyString_FromString(buffer); } static PyObject * datetime_isoformat_helper(PyDateTime_DateTime *self, char sep) { char buffer[100]; char *cp; cp = isoformat_date((PyDateTime_Date *)self, buffer, sizeof(buffer)); assert(cp != NULL); *cp++ = sep; isoformat_time(self, cp, sizeof(buffer) - (cp - buffer)); return PyString_FromString(buffer); } static PyObject * datetime_str(PyDateTime_DateTime *self) { return datetime_isoformat_helper(self, ' '); } static PyObject * datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw) { char sep = 'T'; static char *keywords[] = {"sep", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kw, "|c:isoformat", keywords, &sep)) return NULL; return datetime_isoformat_helper(self, sep); } static PyObject * datetime_ctime(PyDateTime_DateTime *self) { return format_ctime((PyDateTime_Date *)self, DATE_GET_HOUR(self), DATE_GET_MINUTE(self), DATE_GET_SECOND(self)); } /* 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) { long diff; if (!PyType_IsSubtype(other->ob_type, &PyDateTime_DateTimeType)) { PyErr_Format(PyExc_TypeError, "can't compare datetime to %s instance", other->ob_type->tp_name); return NULL; } diff = memcmp(self->data, ((PyDateTime_DateTime *)other)->data, _PyDateTime_DATETIME_DATA_SIZE); return diff_to_bool(diff, op); } static long datetime_hash(PyDateTime_DateTime *self) { if (self->hashcode == -1) { PyObject *temp; temp = Py_BuildValue("lllllll", GET_YEAR(self), GET_MONTH(self), GET_DAY(self), DATE_GET_HOUR(self), DATE_GET_MINUTE(self), DATE_GET_SECOND(self), DATE_GET_MICROSECOND(self)); if (temp != NULL) { self->hashcode = PyObject_Hash(temp); Py_DECREF(temp); } } return self->hashcode; } static PyObject * datetime_timetuple(PyDateTime_DateTime *self) { const int year = GET_YEAR(self); const int month = GET_MONTH(self); const int day = GET_DAY(self); return Py_BuildValue("iiiiiiiii", year, month, day, DATE_GET_HOUR(self), DATE_GET_MINUTE(self), DATE_GET_SECOND(self), weekday(year, month, day), days_before_month(year, month) + day, -1); } static PyObject * datetime_getdate(PyDateTime_DateTime *self) { return new_date((int)GET_YEAR(self), (int)GET_MONTH(self), (int)GET_DAY(self)); } /* Pickle support. Quite a maze! */ static PyObject * datetime_getstate(PyDateTime_DateTime *self) { return PyString_FromStringAndSize(self->data, _PyDateTime_DATETIME_DATA_SIZE); } static PyObject * datetime_setstate(PyDateTime_DateTime *self, PyObject *state) { const int len = PyString_Size(state); unsigned char *pdata = (unsigned char*)PyString_AsString(state); if (! PyString_Check(state) || len != _PyDateTime_DATETIME_DATA_SIZE) { PyErr_SetString(PyExc_TypeError, "bad argument to datetime.__setstate__"); return NULL; } memcpy(self->data, pdata, _PyDateTime_DATETIME_DATA_SIZE); self->hashcode = -1; Py_INCREF(Py_None); return Py_None; } /* XXX This seems a ridiculously inefficient way to pickle a short string. */ static PyObject * datetime_pickler(PyObject *module, PyDateTime_DateTime *datetime) { PyObject *state; PyObject *result = NULL; if (datetime->ob_type != &PyDateTime_DateTimeType) { PyErr_Format(PyExc_TypeError, "bad type passed to datetime pickler: %s", datetime->ob_type->tp_name); return NULL; } state = datetime_getstate(datetime); if (state) { result = Py_BuildValue("O(O)", datetime_unpickler_object, state); Py_DECREF(state); } return result; } static PyObject * datetime_unpickler(PyObject *module, PyObject *arg) { PyDateTime_DateTime *self; if (! PyString_CheckExact(arg)) { PyErr_Format(PyExc_TypeError, "bad type passed to datetime unpickler: %s", arg->ob_type->tp_name); return NULL; } self = PyObject_New(PyDateTime_DateTime, &PyDateTime_DateTimeType); if (self != NULL) { PyObject *res = datetime_setstate(self, arg); Py_XDECREF(res); } return (PyObject *)self; } static PyMethodDef datetime_methods[] = { /* Class methods: */ /* XXX METH_CLASS is implemented incorrectly: * XXX http://www.python.org/sf/548651 * XXX The signatures of these methods will need to change (for * XXX the better) when that's fixed. */ {"now", (PyCFunction)datetime_now, METH_O | METH_CLASS, "Return a new datetime representing local day and time."}, {"utcnow", (PyCFunction)datetime_utcnow, METH_O | METH_CLASS, "Return a new datetime representing UTC day and time."}, {"fromtimestamp", (PyCFunction)datetime_fromtimestamp, METH_VARARGS | METH_CLASS, "timestamp -> local datetime from a POSIX timestamp " "(like time.time())."}, {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp, METH_VARARGS | METH_CLASS, "timestamp -> UTC datetime from a POSIX timestamp " "(like time.time())."}, /* Instance methods: */ {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS, "Return time tuple, compatible with time.localtime()."}, {"date", (PyCFunction)datetime_getdate, METH_NOARGS, "Return date object with same year, month and day."}, {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS, "Return ctime() style string."}, {"isoformat", (PyCFunction)datetime_isoformat, METH_KEYWORDS, "[sep] -> string in ISO 8601 format, YYYY-MM-DDTHH:MM:SS.mmmmmm.\n\n" "sep is used to separate the year from the time, and defaults\n" "to 'T'."}, {"__setstate__", (PyCFunction)datetime_setstate, METH_O, PyDoc_STR("__setstate__(state)")}, {"__getstate__", (PyCFunction)datetime_getstate, METH_NOARGS, PyDoc_STR("__getstate__() -> state")}, {NULL, NULL} }; static char datetime_doc[] = "Basic date/time type."; static PyNumberMethods datetime_as_number = { datetime_add, /* nb_add */ datetime_subtract, /* nb_subtract */ 0, /* nb_multiply */ 0, /* nb_divide */ 0, /* nb_remainder */ 0, /* nb_divmod */ 0, /* nb_power */ 0, /* nb_negative */ 0, /* nb_positive */ 0, /* nb_absolute */ (inquiry)date_nonzero, /* nb_nonzero */ }; statichere PyTypeObject PyDateTime_DateTimeType = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ /* XXX When this module is renamed to datetime, change tp_name. */ "_datetime.datetime", /* tp_name */ sizeof(PyDateTime_DateTime), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)PyObject_Del, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ (reprfunc)datetime_repr, /* tp_repr */ &datetime_as_number, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ (hashfunc)datetime_hash, /* tp_hash */ 0, /* tp_call */ (reprfunc)datetime_str, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES | Py_TPFLAGS_BASETYPE, /* tp_flags */ datetime_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ (richcmpfunc)datetime_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ datetime_methods, /* tp_methods */ 0, /* tp_members */ datetime_getset, /* tp_getset */ &PyDateTime_DateType, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ datetime_new, /* tp_new */ _PyObject_Del, /* tp_free */ }; Index: datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.c,v retrieving revision 1.45 retrieving revision 1.46 diff -C2 -d -r1.45 -r1.46 *** datetime.c 7 Dec 2002 02:23:08 -0000 1.45 --- datetime.c 7 Dec 2002 16:36:16 -0000 1.46 *************** *** 21,43 **** #define MAX_DELTA_DAYS 999999999 - typedef struct - { - PyObject_HEAD - long hashcode; /* -1 when unknown */ - long days; /* -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS */ - long seconds; /* 0 <= seconds < 24*3600 is invariant */ - long microseconds; /* 0 <= microseconds < 1000000 is invariant */ - } PyDateTime_Delta; - /* Rename the long macros in datetime.h to more reasonable short names. */ #define GET_YEAR PyDateTime_GET_YEAR #define GET_MONTH PyDateTime_GET_MONTH #define GET_DAY PyDateTime_GET_DAY ! #define GET_HOUR PyDateTime_GET_HOUR ! #define GET_MINUTE PyDateTime_GET_MINUTE ! #define GET_SECOND PyDateTime_GET_SECOND ! #define GET_MICROSECOND PyDateTime_GET_MICROSECOND ! /* Date accessors. */ #define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \ ((o)->data[1] = ((v) & 0x00ff))) --- 21,34 ---- #define MAX_DELTA_DAYS 999999999 /* Rename the long macros in datetime.h to more reasonable short names. */ #define GET_YEAR PyDateTime_GET_YEAR #define GET_MONTH PyDateTime_GET_MONTH #define GET_DAY PyDateTime_GET_DAY ! #define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR ! #define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE ! #define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND ! #define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND ! /* Date accessors for date and datetime. */ #define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \ ((o)->data[1] = ((v) & 0x00ff))) *************** *** 45,57 **** #define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v)) ! /* Date/Time accessors. */ ! #define SET_HOUR(o, v) (PyDateTime_GET_HOUR(o) = (v)) ! #define SET_MINUTE(o, v) (PyDateTime_GET_MINUTE(o) = (v)) ! #define SET_SECOND(o, v) (PyDateTime_GET_SECOND(o) = (v)) ! #define SET_MICROSECOND(o, v) (((o)->data[7] = ((v) & 0xff0000) >> 16), \ ! ((o)->data[8] = ((v) & 0x00ff00) >> 8), \ ! ((o)->data[9] = ((v) & 0x0000ff))) ! /* Delta accessors. */ #define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days) #define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds) --- 36,58 ---- #define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v)) ! /* Date/Time accessors for datetime. */ ! #define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v)) ! #define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v)) ! #define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v)) ! #define DATE_SET_MICROSECOND(o, v) \ ! (((o)->data[7] = ((v) & 0xff0000) >> 16), \ ! ((o)->data[8] = ((v) & 0x00ff00) >> 8), \ ! ((o)->data[9] = ((v) & 0x0000ff))) ! /* Time accessors for time. */ ! #define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v)) ! #define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v)) ! #define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v)) ! #define TIME_SET_MICROSECOND(o, v) \ ! (((o)->data[7] = ((v) & 0xff0000) >> 16), \ ! ((o)->data[8] = ((v) & 0x00ff00) >> 8), \ ! ((o)->data[9] = ((v) & 0x0000ff))) ! ! /* Delta accessors for timedelta. */ #define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days) #define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds) *************** *** 368,373 **** PyOS_snprintf(buffer, bufflen, "%02d:%02d:%02d.%06d", ! GET_HOUR(dt), GET_MINUTE(dt), GET_SECOND(dt), ! GET_MICROSECOND(dt)); } --- 369,376 ---- PyOS_snprintf(buffer, bufflen, "%02d:%02d:%02d.%06d", ! DATE_GET_HOUR(dt), ! DATE_GET_MINUTE(dt), ! DATE_GET_SECOND(dt), ! DATE_GET_MICROSECOND(dt)); } *************** *** 527,534 **** SET_MONTH(self, month); SET_DAY(self, day); ! SET_HOUR(self, hour); ! SET_MINUTE(self, minute); ! SET_SECOND(self, second); ! SET_MICROSECOND(self, usecond); } return (PyObject *) self; --- 530,537 ---- SET_MONTH(self, month); SET_DAY(self, day); ! DATE_SET_HOUR(self, hour); ! DATE_SET_MINUTE(self, minute); ! DATE_SET_SECOND(self, second); ! DATE_SET_MICROSECOND(self, usecond); } return (PyObject *) self; Index: datetime.h =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.h,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** datetime.h 22 Nov 2002 03:34:42 -0000 1.10 --- datetime.h 7 Dec 2002 16:36:16 -0000 1.11 *************** *** 26,29 **** --- 26,32 ---- #define _PyDateTime_DATETIME_DATA_SIZE 10 + /* # of bytes for hour, minute, second, and usecond. */ + #define _PyDateTime_TIME_DATA_SIZE 6 + typedef struct { *************** *** 40,57 **** } PyDateTime_DateTime; /* Apply for date instances. */ ! #define PyDateTime_GET_YEAR(o) (((PyDateTime_Date*)o)->data[0] << 8 \ ! | ((PyDateTime_Date*)o)->data[1]) #define PyDateTime_GET_MONTH(o) (((PyDateTime_Date*)o)->data[2]) #define PyDateTime_GET_DAY(o) (((PyDateTime_Date*)o)->data[3]) ! /* Apply for datetime instances. */ ! #define PyDateTime_GET_HOUR(o) (((PyDateTime_DateTime*)o)->data[4]) ! #define PyDateTime_GET_MINUTE(o) (((PyDateTime_DateTime*)o)->data[5]) ! #define PyDateTime_GET_SECOND(o) (((PyDateTime_DateTime*)o)->data[6]) ! #define PyDateTime_GET_MICROSECOND(o) \ ((((PyDateTime_DateTime*)o)->data[7] << 16) | \ (((PyDateTime_DateTime*)o)->data[8] << 8) | \ ! ((PyDateTime_DateTime*)o)->data[9]) #endif --- 43,85 ---- } PyDateTime_DateTime; + typedef struct + { + PyObject_HEAD + long hashcode; + unsigned char data[_PyDateTime_TIME_DATA_SIZE]; + } PyDateTime_Time; + + typedef struct + { + PyObject_HEAD + long hashcode; /* -1 when unknown */ + long days; /* -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS */ + long seconds; /* 0 <= seconds < 24*3600 is invariant */ + long microseconds; /* 0 <= microseconds < 1000000 is invariant */ + } PyDateTime_Delta; + /* Apply for date instances. */ ! #define PyDateTime_GET_YEAR(o) ((((PyDateTime_Date*)o)->data[0] << 8) | \ ! ((PyDateTime_Date*)o)->data[1]) #define PyDateTime_GET_MONTH(o) (((PyDateTime_Date*)o)->data[2]) #define PyDateTime_GET_DAY(o) (((PyDateTime_Date*)o)->data[3]) ! /* Apply for datetime and date instances. */ ! #define PyDateTime_DATE_GET_HOUR(o) (((PyDateTime_DateTime*)o)->data[4]) ! #define PyDateTime_DATE_GET_MINUTE(o) (((PyDateTime_DateTime*)o)->data[5]) ! #define PyDateTime_DATE_GET_SECOND(o) (((PyDateTime_DateTime*)o)->data[6]) ! #define PyDateTime_DATE_GET_MICROSECOND(o) \ ((((PyDateTime_DateTime*)o)->data[7] << 16) | \ (((PyDateTime_DateTime*)o)->data[8] << 8) | \ ! ((PyDateTime_DateTime*)o)->data[9]) ! ! /* Apply for time instances. */ ! #define PyDateTime_TIME_GET_HOUR(o) (((PyDateTime_Time*)o)->data[0]) ! #define PyDateTime_TIME_GET_MINUTE(o) (((PyDateTime_Time*)o)->data[1]) ! #define PyDateTime_TIME_GET_SECOND(o) (((PyDateTime_Time*)o)->data[2]) ! #define PyDateTime_TIME_GET_MICROSECOND(o) \ ! ((((PyDateTime_Time*)o)->data[3] << 16) | \ ! (((PyDateTime_Time*)o)->data[4] << 8) | \ ! ((PyDateTime_Time*)o)->data[5]) #endif Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.30 retrieving revision 1.31 diff -C2 -d -r1.30 -r1.31 *** obj_datetime.c 7 Dec 2002 05:33:45 -0000 1.30 --- obj_datetime.c 7 Dec 2002 16:36:16 -0000 1.31 *************** *** 8,12 **** datetime_hour(PyDateTime_DateTime *self, void *unused) { ! return PyInt_FromLong(GET_HOUR(self)); } --- 8,12 ---- datetime_hour(PyDateTime_DateTime *self, void *unused) { ! return PyInt_FromLong(DATE_GET_HOUR(self)); } *************** *** 14,18 **** datetime_minute(PyDateTime_DateTime *self, void *unused) { ! return PyInt_FromLong(GET_MINUTE(self)); } --- 14,18 ---- datetime_minute(PyDateTime_DateTime *self, void *unused) { ! return PyInt_FromLong(DATE_GET_MINUTE(self)); } *************** *** 20,24 **** datetime_second(PyDateTime_DateTime *self, void *unused) { ! return PyInt_FromLong(GET_SECOND(self)); } --- 20,24 ---- datetime_second(PyDateTime_DateTime *self, void *unused) { ! return PyInt_FromLong(DATE_GET_SECOND(self)); } *************** *** 26,30 **** datetime_microsecond(PyDateTime_DateTime *self, void *unused) { ! return PyInt_FromLong(GET_MICROSECOND(self)); } --- 26,30 ---- datetime_microsecond(PyDateTime_DateTime *self, void *unused) { ! return PyInt_FromLong(DATE_GET_MICROSECOND(self)); } *************** *** 242,249 **** long month = GET_MONTH(date); long day = GET_DAY(date) + GET_TD_DAYS(delta); ! long hour = GET_HOUR(date); ! long minute = GET_MINUTE(date); ! long second = GET_SECOND(date) + GET_TD_SECONDS(delta); ! long microsecond = GET_MICROSECOND(date) + GET_TD_MICROSECONDS(delta); if (normalize_datetime(&year, &month, &day, --- 242,250 ---- long month = GET_MONTH(date); long day = GET_DAY(date) + GET_TD_DAYS(delta); ! long hour = DATE_GET_HOUR(date); ! long minute = DATE_GET_MINUTE(date); ! long second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta); ! long microsecond = DATE_GET_MICROSECOND(date) + ! GET_TD_MICROSECONDS(delta); if (normalize_datetime(&year, &month, &day, *************** *** 264,271 **** long month = GET_MONTH(date); long day = GET_DAY(date) - GET_TD_DAYS(delta); ! long hour = GET_HOUR(date); ! long minute = GET_MINUTE(date); ! long second = GET_SECOND(date) - GET_TD_SECONDS(delta); ! long microsecond = GET_MICROSECOND(date) - GET_TD_MICROSECONDS(delta); if (normalize_datetime(&year, &month, &day, --- 265,273 ---- long month = GET_MONTH(date); long day = GET_DAY(date) - GET_TD_DAYS(delta); ! long hour = DATE_GET_HOUR(date); ! long minute = DATE_GET_MINUTE(date); ! long second = DATE_GET_SECOND(date) - GET_TD_SECONDS(delta); ! long microsecond = DATE_GET_MICROSECOND(date) - ! GET_TD_MICROSECONDS(delta); if (normalize_datetime(&year, &month, &day, *************** *** 286,300 **** GET_MONTH(right), GET_DAY(right)); - /* These can't overflow, since the values are normalized. At most * this gives the number of seconds in one day. */ ! long seconds1 = (GET_HOUR(left) * 60 + GET_MINUTE(left)) * 60 + ! GET_SECOND(left); ! long seconds2 = (GET_HOUR(right) * 60 + GET_MINUTE(right)) * 60 + ! GET_SECOND(right); ! long delta_us = GET_MICROSECOND(left) - GET_MICROSECOND(right); ! return new_delta(days1 - days2, seconds1 - seconds2, delta_us, 1); } --- 288,301 ---- GET_MONTH(right), GET_DAY(right)); /* These can't overflow, since the values are normalized. At most * this gives the number of seconds in one day. */ ! long delta_s = (DATE_GET_HOUR(left) - DATE_GET_HOUR(right)) * 3600 + ! (DATE_GET_MINUTE(left) - DATE_GET_MINUTE(right)) * 60 + ! DATE_GET_SECOND(left) - DATE_GET_SECOND(right); ! long delta_us = DATE_GET_MICROSECOND(left) - ! DATE_GET_MICROSECOND(right); ! return new_delta(days1 - days2, delta_s, delta_us, 1); } *************** *** 358,376 **** char *typename = self->ob_type->tp_name; ! if (GET_MICROSECOND(self)) { PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d, %d, %d, %d, %d, %d)", typename, GET_YEAR(self), GET_MONTH(self), GET_DAY(self), ! GET_HOUR(self), GET_MINUTE(self), ! GET_SECOND(self), GET_MICROSECOND(self)); } ! else if (GET_SECOND(self)) { PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d, %d, %d, %d, %d)", typename, GET_YEAR(self), GET_MONTH(self), GET_DAY(self), ! GET_HOUR(self), GET_MINUTE(self), ! GET_SECOND(self)); } else { --- 359,378 ---- char *typename = self->ob_type->tp_name; ! if (DATE_GET_MICROSECOND(self)) { PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d, %d, %d, %d, %d, %d)", typename, GET_YEAR(self), GET_MONTH(self), GET_DAY(self), ! DATE_GET_HOUR(self), DATE_GET_MINUTE(self), ! DATE_GET_SECOND(self), ! DATE_GET_MICROSECOND(self)); } ! else if (DATE_GET_SECOND(self)) { PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d, %d, %d, %d, %d)", typename, GET_YEAR(self), GET_MONTH(self), GET_DAY(self), ! DATE_GET_HOUR(self), DATE_GET_MINUTE(self), ! DATE_GET_SECOND(self)); } else { *************** *** 379,383 **** typename, GET_YEAR(self), GET_MONTH(self), GET_DAY(self), ! GET_HOUR(self), GET_MINUTE(self)); } return PyString_FromString(buffer); --- 381,385 ---- typename, GET_YEAR(self), GET_MONTH(self), GET_DAY(self), ! DATE_GET_HOUR(self), DATE_GET_MINUTE(self)); } return PyString_FromString(buffer); *************** *** 421,427 **** { return format_ctime((PyDateTime_Date *)self, ! GET_HOUR(self), ! GET_MINUTE(self), ! GET_SECOND(self)); } --- 423,429 ---- { return format_ctime((PyDateTime_Date *)self, ! DATE_GET_HOUR(self), ! DATE_GET_MINUTE(self), ! DATE_GET_SECOND(self)); } *************** *** 455,460 **** temp = Py_BuildValue("lllllll", GET_YEAR(self), GET_MONTH(self), GET_DAY(self), ! GET_HOUR(self), GET_MINUTE(self), ! GET_SECOND(self), GET_MICROSECOND(self)); if (temp != NULL) { self->hashcode = PyObject_Hash(temp); --- 457,463 ---- temp = Py_BuildValue("lllllll", GET_YEAR(self), GET_MONTH(self), GET_DAY(self), ! DATE_GET_HOUR(self), DATE_GET_MINUTE(self), ! DATE_GET_SECOND(self), ! DATE_GET_MICROSECOND(self)); if (temp != NULL) { self->hashcode = PyObject_Hash(temp); *************** *** 474,480 **** return Py_BuildValue("iiiiiiiii", year, month, day, ! GET_HOUR(self), ! GET_MINUTE(self), ! GET_SECOND(self), weekday(year, month, day), days_before_month(year, month) + day, --- 477,483 ---- return Py_BuildValue("iiiiiiiii", year, month, day, ! DATE_GET_HOUR(self), ! DATE_GET_MINUTE(self), ! DATE_GET_SECOND(self), weekday(year, month, day), days_before_month(year, month) + day, From tim_one@users.sourceforge.net Sat Dec 7 18:34:41 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sat, 07 Dec 2002 10:34:41 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.c,1.46,1.47 datetime.h,1.11,1.12 datetime.py,1.78,1.79 doc.txt,1.23,1.24 obj_date.c,1.36,1.37 obj_datetime.c,1.31,1.32 obj_time.c,1.1,1.2 test_both.py,1.48,1.49 test_datetime.py,1.55,1.56 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv21099 Modified Files: datetime.c datetime.h datetime.py doc.txt obj_date.c obj_datetime.c obj_time.c test_both.py test_datetime.py Log Message: Mounds of changes to implement the time type in C. Moved all the time tests from test_datetime.py into test_both.py. More tests are needed (e.g., for pickling of time objects -- this is implemented but not yet tested). The Python implementation had a fancy "pretty" __str__ for time and timetz. I don't know whether or not that's a good idea, as people argue endlessly over what "pretty" means. Since all the other types in this module with an isoformat() method made __str__ a synonym, that's what I did here too, and changed the Python implementation to match. I'm not married to this, I just don't want to endure arguments about this now. Pretty str() for all types or pretty str() for none is what I want to see, the latter is quickest to implement, and if pretty is desired that's not critical to get done before tha alpha release. Index: datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.c,v retrieving revision 1.46 retrieving revision 1.47 diff -C2 -d -r1.46 -r1.47 *** datetime.c 7 Dec 2002 16:36:16 -0000 1.46 --- datetime.c 7 Dec 2002 18:34:39 -0000 1.47 *************** *** 46,56 **** /* Time accessors for time. */ #define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v)) #define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v)) #define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v)) #define TIME_SET_MICROSECOND(o, v) \ ! (((o)->data[7] = ((v) & 0xff0000) >> 16), \ ! ((o)->data[8] = ((v) & 0x00ff00) >> 8), \ ! ((o)->data[9] = ((v) & 0x0000ff))) /* Delta accessors for timedelta. */ --- 46,60 ---- /* Time accessors for time. */ + #define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR + #define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE + #define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND + #define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND #define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v)) #define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v)) #define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v)) #define TIME_SET_MICROSECOND(o, v) \ ! (((o)->data[3] = ((v) & 0xff0000) >> 16), \ ! ((o)->data[4] = ((v) & 0x00ff00) >> 8), \ ! ((o)->data[5] = ((v) & 0x0000ff))) /* Delta accessors for timedelta. */ *************** *** 67,70 **** --- 71,75 ---- static PyTypeObject PyDateTime_DateTimeType; static PyTypeObject PyDateTime_DeltaType; + static PyTypeObject PyDateTime_TimeType; /* *************** *** 538,541 **** --- 543,563 ---- } + /* Create a time instance with no range checking. */ + static PyObject * + new_time(int hour, int minute, int second, int usecond) + { + PyDateTime_Time *self; + + self = PyObject_New(PyDateTime_Time, &PyDateTime_TimeType); + if (self != NULL) { + self->hashcode = -1; + TIME_SET_HOUR(self, hour); + TIME_SET_MINUTE(self, minute); + TIME_SET_SECOND(self, second); + TIME_SET_MICROSECOND(self, usecond); + } + return (PyObject *) self; + } + /* Create a timedelta instance. Normalize the members iff normalize is * true. Passing false is a speed optimization, if you know for sure *************** *** 569,572 **** --- 591,595 ---- static PyObject *date_unpickler_object = NULL; static PyObject *datetime_unpickler_object = NULL; + static PyObject *time_unpickler_object = NULL; /* For obscure reasons, we need to use tp_richcompare instead of tp_compare. *************** *** 598,601 **** --- 621,625 ---- #include "obj_date.c" #include "obj_datetime.c" + #include "obj_time.c" *************** *** 608,611 **** --- 632,637 ---- {"_datetime_pickler", (PyCFunction)datetime_pickler, METH_O, NULL}, {"_datetime_unpickler", (PyCFunction)datetime_unpickler,METH_O, NULL}, + {"_time_pickler", (PyCFunction)time_pickler, METH_O, NULL}, + {"_time_unpickler", (PyCFunction)time_unpickler, METH_O, NULL}, {NULL, NULL} }; *************** *** 630,633 **** --- 656,661 ---- if (PyType_Ready(&PyDateTime_DeltaType) < 0) return; + if (PyType_Ready(&PyDateTime_TimeType) < 0) + return; /* timedelta values */ *************** *** 688,691 **** --- 716,737 ---- Py_DECREF(dt); + /* time values */ + d = PyDateTime_TimeType.tp_dict; + + dt = new_time(0, 0, 0, 0); + if (dt == NULL || PyDict_SetItemString(d, "min", dt) < 0) + return; + Py_DECREF(dt); + + dt = new_time(23, 59, 59, 999999); + if (dt == NULL || PyDict_SetItemString(d, "max", dt) < 0) + return; + Py_DECREF(dt); + + dt = new_delta(0, 0, 1, 0); + if (dt == NULL || PyDict_SetItemString(d, "resolution", dt) < 0) + return; + Py_DECREF(dt); + Py_DECREF(safepickle); *************** *** 695,707 **** PyModule_AddIntConstant(m, "MINYEAR", MINYEAR); PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR); Py_INCREF(&PyDateTime_DateType); ! PyModule_AddObject(m, "date", ! (PyObject *) &PyDateTime_DateType); Py_INCREF(&PyDateTime_DateTimeType); PyModule_AddObject(m, "datetime", (PyObject *) &PyDateTime_DateTimeType); Py_INCREF(&PyDateTime_DeltaType); ! PyModule_AddObject(m, "timedelta", ! (PyObject *) &PyDateTime_DeltaType); --- 741,757 ---- PyModule_AddIntConstant(m, "MINYEAR", MINYEAR); PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR); + Py_INCREF(&PyDateTime_DateType); ! PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType); ! Py_INCREF(&PyDateTime_DateTimeType); PyModule_AddObject(m, "datetime", (PyObject *) &PyDateTime_DateTimeType); + Py_INCREF(&PyDateTime_DeltaType); ! PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType); ! ! Py_INCREF(&PyDateTime_TimeType); ! PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType); *************** *** 767,770 **** --- 817,833 ---- pickler, datetime_unpickler_object); + assert(temp); + Py_DECREF(temp); + Py_DECREF(pickler); + + pickler = PyObject_GetAttrString(m, "_time_pickler"); + assert(pickler); + time_unpickler_object = PyObject_GetAttrString(m, + "_time_unpickler"); + assert(time_unpickler_object); + temp = PyObject_CallMethod(copyreg, "pickle", "OOO", + &PyDateTime_TimeType, + pickler, + time_unpickler_object); assert(temp); Py_DECREF(temp); Index: datetime.h =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.h,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** datetime.h 7 Dec 2002 16:36:16 -0000 1.11 --- datetime.h 7 Dec 2002 18:34:39 -0000 1.12 *************** *** 21,31 **** /* # of bytes for year, month, and day. */ ! #define _PyDateTime_DATE_DATA_SIZE 4 ! ! /* # of bytes for year, month, day, hour, minute, second, and usecond. */ ! #define _PyDateTime_DATETIME_DATA_SIZE 10 /* # of bytes for hour, minute, second, and usecond. */ ! #define _PyDateTime_TIME_DATA_SIZE 6 typedef struct --- 21,31 ---- /* # of bytes for year, month, and day. */ ! #define _PyDateTime_DATE_DATASIZE 4 /* # of bytes for hour, minute, second, and usecond. */ ! #define _PyDateTime_TIME_DATASIZE 6 ! ! /* # of bytes for year, month, day, hour, minute, second, and usecond. */ ! #define _PyDateTime_DATETIME_DATASIZE 10 typedef struct *************** *** 33,38 **** PyObject_HEAD long hashcode; ! unsigned char data[_PyDateTime_DATE_DATA_SIZE]; ! } PyDateTime_Date; typedef struct --- 33,38 ---- PyObject_HEAD long hashcode; ! unsigned char data[_PyDateTime_DATE_DATASIZE]; ! } PyDateTime_Date; typedef struct *************** *** 40,45 **** PyObject_HEAD long hashcode; ! unsigned char data[_PyDateTime_DATETIME_DATA_SIZE]; ! } PyDateTime_DateTime; typedef struct --- 40,45 ---- PyObject_HEAD long hashcode; ! unsigned char data[_PyDateTime_DATETIME_DATASIZE]; ! } PyDateTime_DateTime; typedef struct *************** *** 47,52 **** PyObject_HEAD long hashcode; ! unsigned char data[_PyDateTime_TIME_DATA_SIZE]; ! } PyDateTime_Time; typedef struct --- 47,52 ---- PyObject_HEAD long hashcode; ! unsigned char data[_PyDateTime_TIME_DATASIZE]; ! } PyDateTime_Time; typedef struct Index: datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.py,v retrieving revision 1.78 retrieving revision 1.79 diff -C2 -d -r1.78 -r1.79 *** datetime.py 5 Dec 2002 19:45:03 -0000 1.78 --- datetime.py 7 Dec 2002 18:34:39 -0000 1.79 *************** *** 789,792 **** --- 789,805 ---- self.__hour, self.__minute, s) + def isoformat(self): + """Return the time formatted according to ISO. + + This is 'HH:MM:SS.mmmmmm'. + """ + return "%02d:%02d:%02d.%06d" % ( + self.__hour, self.__minute, self.__second, + self.__microsecond) + + # XXX All other types in this module that define isoformat make __str__ + # XXX a synonym, so for now I'm overriding this "pretty string" oddball + # XXX to do likewise. The last thing I need right now is to spend days + # XXX arguing about what "pretty" means in 6 distinct types <0.5 wink>. def __str__(self): """Convert to pretty string, for str().""" *************** *** 805,816 **** return pretty ! def isoformat(self): ! """Return the time formatted according to ISO. ! ! This is 'HH:MM:SS.mmmmmm'. ! """ ! return "%02d:%02d:%02d.%06d" % ( ! self.__hour, self.__minute, self.__second, ! self.__microsecond) def strftime(self, fmt): --- 818,822 ---- return pretty ! __str__ = isoformat def strftime(self, fmt): *************** *** 937,947 **** return s - def __str__(self): - """Convert to pretty string, for str().""" - s = super(timetz, self).__str__() - tz = self._tzstr() - if tz: s = "%s %s" % (s, tz) - return s - def isoformat(self): """Return the time formatted according to ISO. --- 943,946 ---- *************** *** 953,956 **** --- 952,965 ---- if tz: s += tz return s + + # XXX As for time, I'm making __str__ a synonym for isoformat for now. + def __str__(self): + """Convert to pretty string, for str().""" + s = super(timetz, self).__str__() + tz = self._tzstr() + if tz: s = "%s %s" % (s, tz) + return s + + __str__ = isoformat def strftime(self, fmt): Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.23 retrieving revision 1.24 diff -C2 -d -r1.23 -r1.24 *** doc.txt 7 Dec 2002 05:33:44 -0000 1.23 --- doc.txt 7 Dec 2002 18:34:39 -0000 1.24 *************** *** 503,506 **** --- 503,567 ---- class time ========== + A time object represents an idealized time of day, independent of day + and timezone. + + Constructor: + + time(hour=0, minute=0, second=0, microsecond=0) + + All arguments are optional. The may be ints or longs, in the + following ranges: + + 0 <= hour < 24 + 0 <= minute < 60 + 0 <= second < 60 + 0 <= microsecond < 1000000 + + If an argument outside those ranges is given, ValueError is raised. + + Other constructors (class methods): + + None + + Class attributes: + + .min + The earliest representable time, time(0, 0, 0). + + .max + The latest representable time, time(23, 59, 59). + + .resolution + The smallest possible difference between non-equal time + objects, timedelta(microseconds=1). + + Instance attributes (read-only): + + .hour in range(24) + .minute in range(60) + .second in range(60) + .microsecond in range(1000000) + + Supported operations: + + - comparison of time to time, where time1 is considered + less than time2 when time1 precedes time2 in time. + + - hash, use as dict key + + - pickling + + Instance methods: + + - isoformat() + Return a string representing the time in ISO 8601 format, + HH:MM:SS.mmmmmm + str(t) is equivalent to t.isoformat(). + + - strftime(format) + Return a string representing the time, controlled by an explicit + format string. Format codes for any fields other than hour, minute + and second should not be used, since a time object has meaningful + values only for those fields. Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.36 retrieving revision 1.37 diff -C2 -d -r1.36 -r1.37 *** obj_date.c 7 Dec 2002 03:12:57 -0000 1.36 --- obj_date.c 7 Dec 2002 18:34:39 -0000 1.37 *************** *** 365,369 **** } diff = memcmp(self->data, ((PyDateTime_Date *)other)->data, ! _PyDateTime_DATE_DATA_SIZE); return diff_to_bool(diff, op); } --- 365,369 ---- } diff = memcmp(self->data, ((PyDateTime_Date *)other)->data, ! _PyDateTime_DATE_DATASIZE); return diff_to_bool(diff, op); } *************** *** 426,430 **** { return PyString_FromStringAndSize(self->data, ! _PyDateTime_DATE_DATA_SIZE); } --- 426,430 ---- { return PyString_FromStringAndSize(self->data, ! _PyDateTime_DATE_DATASIZE); } *************** *** 436,445 **** if (! PyString_Check(state) || ! len != _PyDateTime_DATE_DATA_SIZE) { PyErr_SetString(PyExc_TypeError, "bad argument to date.__setstate__"); return NULL; } ! memcpy(self->data, pdata, _PyDateTime_DATE_DATA_SIZE); self->hashcode = -1; --- 436,445 ---- if (! PyString_Check(state) || ! len != _PyDateTime_DATE_DATASIZE) { PyErr_SetString(PyExc_TypeError, "bad argument to date.__setstate__"); return NULL; } ! memcpy(self->data, pdata, _PyDateTime_DATE_DATASIZE); self->hashcode = -1; Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.31 retrieving revision 1.32 diff -C2 -d -r1.31 -r1.32 *** obj_datetime.c 7 Dec 2002 16:36:16 -0000 1.31 --- obj_datetime.c 7 Dec 2002 18:34:39 -0000 1.32 *************** *** 446,450 **** } diff = memcmp(self->data, ((PyDateTime_DateTime *)other)->data, ! _PyDateTime_DATETIME_DATA_SIZE); return diff_to_bool(diff, op); } --- 446,450 ---- } diff = memcmp(self->data, ((PyDateTime_DateTime *)other)->data, ! _PyDateTime_DATETIME_DATASIZE); return diff_to_bool(diff, op); } *************** *** 499,503 **** { return PyString_FromStringAndSize(self->data, ! _PyDateTime_DATETIME_DATA_SIZE); } --- 499,503 ---- { return PyString_FromStringAndSize(self->data, ! _PyDateTime_DATETIME_DATASIZE); } *************** *** 509,518 **** if (! PyString_Check(state) || ! len != _PyDateTime_DATETIME_DATA_SIZE) { PyErr_SetString(PyExc_TypeError, "bad argument to datetime.__setstate__"); return NULL; } ! memcpy(self->data, pdata, _PyDateTime_DATETIME_DATA_SIZE); self->hashcode = -1; --- 509,518 ---- if (! PyString_Check(state) || ! len != _PyDateTime_DATETIME_DATASIZE) { PyErr_SetString(PyExc_TypeError, "bad argument to datetime.__setstate__"); return NULL; } ! memcpy(self->data, pdata, _PyDateTime_DATETIME_DATASIZE); self->hashcode = -1; Index: obj_time.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_time.c,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** obj_time.c 7 Dec 2002 16:36:16 -0000 1.1 --- obj_time.c 7 Dec 2002 18:34:39 -0000 1.2 *************** *** 1,5 **** /* * PyDateTime_Time implementation. - * XXX This is currently a copy of obj_datetime.c, and unused. */ --- 1,4 ---- *************** *** 7,38 **** static PyObject * ! datetime_hour(PyDateTime_DateTime *self, void *unused) { ! return PyInt_FromLong(DATE_GET_HOUR(self)); } static PyObject * ! datetime_minute(PyDateTime_DateTime *self, void *unused) { ! return PyInt_FromLong(DATE_GET_MINUTE(self)); } static PyObject * ! datetime_second(PyDateTime_DateTime *self, void *unused) { ! return PyInt_FromLong(DATE_GET_SECOND(self)); } static PyObject * ! datetime_microsecond(PyDateTime_DateTime *self, void *unused) { ! return PyInt_FromLong(DATE_GET_MICROSECOND(self)); } ! static PyGetSetDef datetime_getset[] = { ! {"hour", (getter)datetime_hour}, ! {"minute", (getter)datetime_minute}, ! {"second", (getter)datetime_second}, ! {"microsecond", (getter)datetime_microsecond}, {NULL} }; --- 6,37 ---- static PyObject * ! time_hour(PyDateTime_Time *self, void *unused) { ! return PyInt_FromLong(TIME_GET_HOUR(self)); } static PyObject * ! time_minute(PyDateTime_Time *self, void *unused) { ! return PyInt_FromLong(TIME_GET_MINUTE(self)); } static PyObject * ! time_second(PyDateTime_Time *self, void *unused) { ! return PyInt_FromLong(TIME_GET_SECOND(self)); } static PyObject * ! time_microsecond(PyDateTime_Time *self, void *unused) { ! return PyInt_FromLong(TIME_GET_MICROSECOND(self)); } ! static PyGetSetDef time_getset[] = { ! {"hour", (getter)time_hour}, ! {"minute", (getter)time_minute}, ! {"second", (getter)time_second}, ! {"microsecond", (getter)time_microsecond}, {NULL} }; *************** *** 41,50 **** static PyObject * ! datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw) { PyObject *self = NULL; - long year; - long month; - long day; long hour = 0; long minute = 0; --- 40,46 ---- static PyObject * ! time_new(PyTypeObject *type, PyObject *args, PyObject *kw) { PyObject *self = NULL; long hour = 0; long minute = 0; *************** *** 53,78 **** static char *keywords[] = { ! "year", "month", "day", "hour", "minute", "second", ! "microsecond", NULL }; ! if (PyArg_ParseTupleAndKeywords(args, kw, "lll|llll", keywords, ! &year, &month, &day, &hour, &minute, ! &second, &usecond)) { ! if (year < MINYEAR || year > MAXYEAR) { ! PyErr_SetString(PyExc_ValueError, ! "year is out of range"); ! return NULL; ! } ! if (month < 1 || month > 12) { ! PyErr_SetString(PyExc_ValueError, ! "month must be in 1..12"); ! return NULL; ! } ! if (day < 1 || day > days_in_month(year, month)) { ! PyErr_SetString(PyExc_ValueError, ! "day is out of range for month"); ! return NULL; ! } if (hour < 0 || hour > 23) { PyErr_SetString(PyExc_ValueError, --- 49,57 ---- static char *keywords[] = { ! "hour", "minute", "second", "microsecond", NULL }; ! if (PyArg_ParseTupleAndKeywords(args, kw, "|llll", keywords, ! &hour, &minute, &second, &usecond)) { if (hour < 0 || hour > 23) { PyErr_SetString(PyExc_ValueError, *************** *** 95,430 **** return NULL; } ! self = new_datetime(year, month, day, hour, minute, second, ! usecond); } return self; } ! ! /* TM_FUNC is the shared type of localtime() and gmtime(). */ ! typedef struct tm *(*TM_FUNC)(const time_t *timer); ! ! static PyObject * ! datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp) ! { ! struct tm *tm; ! time_t timet = (time_t)timestamp; ! long us = (long)((timestamp - (double)timet) * 1e6); ! PyObject *result = NULL; ! ! tm = f(&timet); ! if (tm) ! result = PyObject_CallFunction(cls, "lllllll", ! tm->tm_year + 1900, ! tm->tm_mon + 1, ! tm->tm_mday, ! tm->tm_hour, ! tm->tm_min, ! tm->tm_sec, ! us); ! else ! PyErr_SetString(PyExc_ValueError, ! "timestamp out of range for " ! "platform localtime()/gmtime() function"); ! return result; ! } ! ! /* Return new local datetime from timestamp (Python timestamp -- a double). */ ! static PyObject * ! datetime_fromtimestamp(PyObject *self, PyObject *args) ! { ! PyObject *cls; ! double timestamp; ! PyObject *result = NULL; ! ! if (PyArg_ParseTuple(args, "Od:fromtimestamp", &cls, ×tamp)) ! result = datetime_from_timestamp(cls, localtime, timestamp); ! return result; ! } ! ! /* Return new UTC datetime from timestamp (Python timestamp -- a double). */ ! static PyObject * ! datetime_utcfromtimestamp(PyObject *self, PyObject *args) ! { ! PyObject *cls; ! double timestamp; ! PyObject *result = NULL; ! ! if (PyArg_ParseTuple(args, "Od:utcfromtimestamp", &cls, ×tamp)) ! result = datetime_from_timestamp(cls, gmtime, timestamp); ! return result; ! } ! ! static PyObject * ! datetime_now(PyObject *self, PyObject *cls) ! { ! /* XXX MAJOR: This needs to get some notion of current time ! * XXX to better than 1-second resolution. Doing this in a x- ! * XXX platform way is mondo painful. Maybe floattime() from ! * XXX timemodule.c is good enough? We're running out of bits ! * XXX in a typical time_t, though, and gettimeofday() should do ! * XXX better than floattime() -- but gettimeofday isn't portable. ! */ ! #if 0 ! /* XXX need to create the instance by calling cls(y,mon,d,h,min,s,u) */ ! struct timeval t; ! struct tm *tm; ! time_t timet; ! ! #ifdef GETTIMEOFDAY_NO_TZ ! gettimeofday(&t); ! #else /* !GETTIMEOFDAY_NO_TZ */ ! gettimeofday(&t, (struct timezone *)NULL); ! #endif /* !GETTIMEOFDAY_NO_TZ */ ! timet = t.tv_sec; ! tm = localtime(&timet); ! ! return PyObject_CallFunction(cls, "iiiiiil", ! tm->tm_year + 1900, tm->tm_mon + 1, ! tm->tm_mday, tm->tm_hour, tm->tm_min, ! tm->tm_sec, t.tv_usec); ! #else ! /* XXX need to create the instance by calling cls(y,mon,d,h,min,s,u) */ ! struct tm *tm; ! time_t timet; ! ! time(&timet); ! tm = localtime(&timet); ! ! return PyObject_CallFunction(cls, "llllll", ! tm->tm_year + 1900, tm->tm_mon + 1, ! tm->tm_mday, tm->tm_hour, tm->tm_min, ! tm->tm_sec); ! #endif ! } ! ! static PyObject * ! datetime_utcnow(PyObject *self, PyObject *cls) ! { ! /* XXX Like datetime_now, this would like to do better than ! * XXX 1-second resolution. ! */ ! struct tm *tm; ! time_t timet; ! ! time(&timet); ! tm = gmtime(&timet); ! ! return PyObject_CallFunction(cls, "llllll", ! tm->tm_year + 1900, tm->tm_mon + 1, ! tm->tm_mday, tm->tm_hour, tm->tm_min, ! tm->tm_sec); ! } ! ! /* datetime arithmetic. */ ! ! /* Force all the datetime fields into range. The parameters are both ! * inputs and outputs. Returns < 0 on error. ! */ ! static int ! normalize_datetime(long *year, long *month, long *day, ! long *hour, long *minute, long *second, ! long *microsecond) ! { ! normalize_pair(second, microsecond, 1000000); ! normalize_pair(minute, second, 60); ! normalize_pair(hour, minute, 60); ! normalize_pair(day, hour, 24); ! return normalize_date(year, month, day); ! } ! ! static PyObject * ! add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta) ! { ! /* Note that the C-level additions can't overflow, because of ! * invariant bounds on the member values. ! */ ! long year = GET_YEAR(date); ! long month = GET_MONTH(date); ! long day = GET_DAY(date) + GET_TD_DAYS(delta); ! long hour = DATE_GET_HOUR(date); ! long minute = DATE_GET_MINUTE(date); ! long second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta); ! long microsecond = DATE_GET_MICROSECOND(date) + ! GET_TD_MICROSECONDS(delta); ! ! if (normalize_datetime(&year, &month, &day, ! &hour, &minute, &second, µsecond) < 0) ! return NULL; ! else ! return new_datetime(year, month, day, ! hour, minute, second, microsecond); ! } ! ! static PyObject * ! sub_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta) ! { ! /* Note that the C-level subtractions can't overflow, because of ! * invariant bounds on the member values. ! */ ! long year = GET_YEAR(date); ! long month = GET_MONTH(date); ! long day = GET_DAY(date) - GET_TD_DAYS(delta); ! long hour = DATE_GET_HOUR(date); ! long minute = DATE_GET_MINUTE(date); ! long second = DATE_GET_SECOND(date) - GET_TD_SECONDS(delta); ! long microsecond = DATE_GET_MICROSECOND(date) - ! GET_TD_MICROSECONDS(delta); ! ! if (normalize_datetime(&year, &month, &day, ! &hour, &minute, &second, µsecond) < 0) ! return NULL; ! else ! return new_datetime(year, month, day, ! hour, minute, second, microsecond); ! } ! ! static PyObject * ! sub_datetime_datetime(PyDateTime_DateTime *left, PyDateTime_DateTime *right) ! { ! long days1 = ymd_to_ord(GET_YEAR(left), ! GET_MONTH(left), ! GET_DAY(left)); ! long days2 = ymd_to_ord(GET_YEAR(right), ! GET_MONTH(right), ! GET_DAY(right)); ! /* These can't overflow, since the values are normalized. At most ! * this gives the number of seconds in one day. ! */ ! long delta_s = (DATE_GET_HOUR(left) - DATE_GET_HOUR(right)) * 3600 + ! (DATE_GET_MINUTE(left) - DATE_GET_MINUTE(right)) * 60 + ! DATE_GET_SECOND(left) - DATE_GET_SECOND(right); ! long delta_us = DATE_GET_MICROSECOND(left) - ! DATE_GET_MICROSECOND(right); ! ! return new_delta(days1 - days2, delta_s, delta_us, 1); ! } ! ! static PyObject * ! datetime_add(PyObject *left, PyObject *right) ! { ! PyTypeObject *left_type = left->ob_type; ! PyTypeObject *right_type = right->ob_type; ! ! if (PyType_IsSubtype(left_type, &PyDateTime_DateTimeType)) { ! /* datetime + ??? */ ! if (PyType_IsSubtype(right_type, &PyDateTime_DeltaType)) ! /* datetime + delta */ ! return add_datetime_timedelta( ! (PyDateTime_DateTime *)left, ! (PyDateTime_Delta *)right); ! } ! else if (PyType_IsSubtype(left_type, &PyDateTime_DeltaType)) { ! /* delta + datetime */ ! return add_datetime_timedelta((PyDateTime_DateTime *) right, ! (PyDateTime_Delta *) left); ! } ! Py_INCREF(Py_NotImplemented); ! return Py_NotImplemented; ! } ! ! static PyObject * ! datetime_subtract(PyObject *left, PyObject *right) ! { ! PyTypeObject *left_type = left->ob_type; ! PyTypeObject *right_type = right->ob_type; ! PyObject *result = Py_NotImplemented; ! ! if (PyType_IsSubtype(left_type, &PyDateTime_DateTimeType)) { ! /* datetime - ??? */ ! if (PyType_IsSubtype(right_type, &PyDateTime_DateTimeType)) { ! /* datetime - datetime */ ! result = sub_datetime_datetime( ! (PyDateTime_DateTime *)left, ! (PyDateTime_DateTime *)right); ! } ! else if (PyType_IsSubtype(right_type, &PyDateTime_DeltaType)) { ! /* datetime - delta */ ! result = sub_datetime_timedelta( ! (PyDateTime_DateTime *)left, ! (PyDateTime_Delta *)right); ! } ! } ! ! if (result == Py_NotImplemented) ! Py_INCREF(result); ! return result; ! } ! ! /* Various ways to turn a datetime into a string. */ static PyObject * ! datetime_repr(PyDateTime_DateTime *self) { ! char buffer[1000]; char *typename = self->ob_type->tp_name; ! if (DATE_GET_MICROSECOND(self)) { PyOS_snprintf(buffer, sizeof(buffer), ! "%s(%d, %d, %d, %d, %d, %d, %d)", ! typename, ! GET_YEAR(self), GET_MONTH(self), GET_DAY(self), ! DATE_GET_HOUR(self), DATE_GET_MINUTE(self), ! DATE_GET_SECOND(self), ! DATE_GET_MICROSECOND(self)); ! } ! else if (DATE_GET_SECOND(self)) { PyOS_snprintf(buffer, sizeof(buffer), ! "%s(%d, %d, %d, %d, %d, %d)", ! typename, ! GET_YEAR(self), GET_MONTH(self), GET_DAY(self), ! DATE_GET_HOUR(self), DATE_GET_MINUTE(self), ! DATE_GET_SECOND(self)); ! } ! else { PyOS_snprintf(buffer, sizeof(buffer), ! "%s(%d, %d, %d, %d, %d)", ! typename, ! GET_YEAR(self), GET_MONTH(self), GET_DAY(self), ! DATE_GET_HOUR(self), DATE_GET_MINUTE(self)); ! } return PyString_FromString(buffer); } static PyObject * ! datetime_isoformat_helper(PyDateTime_DateTime *self, char sep) { char buffer[100]; ! char *cp; ! cp = isoformat_date((PyDateTime_Date *)self, buffer, sizeof(buffer)); ! assert(cp != NULL); ! *cp++ = sep; ! isoformat_time(self, cp, sizeof(buffer) - (cp - buffer)); return PyString_FromString(buffer); } static PyObject * ! datetime_str(PyDateTime_DateTime *self) ! { ! return datetime_isoformat_helper(self, ' '); ! } ! ! static PyObject * ! datetime_isoformat(PyDateTime_DateTime *self, ! PyObject *args, PyObject *kw) { ! char sep = 'T'; ! static char *keywords[] = {"sep", NULL}; ! ! if (!PyArg_ParseTupleAndKeywords(args, kw, "|c:isoformat", keywords, ! &sep)) return NULL; ! return datetime_isoformat_helper(self, sep); ! } ! ! static PyObject * ! datetime_ctime(PyDateTime_DateTime *self) ! { ! return format_ctime((PyDateTime_Date *)self, ! DATE_GET_HOUR(self), ! DATE_GET_MINUTE(self), ! DATE_GET_SECOND(self)); } --- 74,140 ---- return NULL; } ! self = new_time(hour, minute, second, usecond); } return self; } ! /* Various ways to turn a time into a string. */ static PyObject * ! time_repr(PyDateTime_Time *self) { ! char buffer[100]; char *typename = self->ob_type->tp_name; + int h = TIME_GET_HOUR(self); + int m = TIME_GET_MINUTE(self); + int s = TIME_GET_SECOND(self); + int us = TIME_GET_MICROSECOND(self); ! if (us) PyOS_snprintf(buffer, sizeof(buffer), ! "%s(%d, %d, %d, %d)", typename, h, m, s, us); ! else if (s) PyOS_snprintf(buffer, sizeof(buffer), ! "%s(%d, %d, %d)", typename, h, m, s); ! else PyOS_snprintf(buffer, sizeof(buffer), ! "%s(%d, %d)", typename, h, m); return PyString_FromString(buffer); } + /* time_isoformat is also tp_str */ static PyObject * ! time_isoformat(PyDateTime_Time *self) { char buffer[100]; ! /* Reuse the time format code from the datetime type. */ ! PyDateTime_DateTime datetime; ! PyDateTime_DateTime *pdatetime = &datetime; ! /* Copy over just the time bytes. */ ! memcpy(pdatetime->data + _PyDateTime_DATE_DATASIZE, ! self->data, ! _PyDateTime_TIME_DATASIZE); + isoformat_time(pdatetime, buffer, sizeof(buffer)); return PyString_FromString(buffer); } static PyObject * ! time_strftime(PyDateTime_Time *self, PyObject *format) { ! PyObject *result; ! PyObject *tuple = Py_BuildValue("iiiiiiiii", ! 0, 0, 0, /* year, month, day */ ! TIME_GET_HOUR(self), ! TIME_GET_MINUTE(self), ! TIME_GET_SECOND(self), ! 0, 0, -1); /* weekday, daynum, dst */ ! if (tuple == NULL) return NULL; ! assert(PyTuple_Size(tuple) == 9); ! result = format_strftime(format, tuple); ! Py_DECREF(tuple); ! return result; } *************** *** 436,464 **** */ static PyObject * ! datetime_richcompare(PyDateTime_DateTime *self, PyObject *other, int op) { long diff; ! if (!PyType_IsSubtype(other->ob_type, &PyDateTime_DateTimeType)) { PyErr_Format(PyExc_TypeError, ! "can't compare datetime to %s instance", other->ob_type->tp_name); return NULL; } ! diff = memcmp(self->data, ((PyDateTime_DateTime *)other)->data, ! _PyDateTime_DATETIME_DATA_SIZE); return diff_to_bool(diff, op); } static long ! datetime_hash(PyDateTime_DateTime *self) { if (self->hashcode == -1) { PyObject *temp; ! temp = Py_BuildValue("lllllll", GET_YEAR(self), ! GET_MONTH(self), GET_DAY(self), ! DATE_GET_HOUR(self), DATE_GET_MINUTE(self), ! DATE_GET_SECOND(self), ! DATE_GET_MICROSECOND(self)); if (temp != NULL) { self->hashcode = PyObject_Hash(temp); --- 146,174 ---- */ static PyObject * ! time_richcompare(PyDateTime_Time *self, PyObject *other, int op) { long diff; ! if (!PyType_IsSubtype(other->ob_type, &PyDateTime_TimeType)) { PyErr_Format(PyExc_TypeError, ! "can't compare time to %s instance", other->ob_type->tp_name); return NULL; } ! diff = memcmp(self->data, ((PyDateTime_Time *)other)->data, ! _PyDateTime_TIME_DATASIZE); return diff_to_bool(diff, op); } static long ! time_hash(PyDateTime_Time *self) { if (self->hashcode == -1) { PyObject *temp; ! temp = Py_BuildValue("llll", ! TIME_GET_HOUR(self), ! TIME_GET_MINUTE(self), ! TIME_GET_SECOND(self), ! TIME_GET_MICROSECOND(self)); if (temp != NULL) { self->hashcode = PyObject_Hash(temp); *************** *** 469,495 **** } ! static PyObject * ! datetime_timetuple(PyDateTime_DateTime *self) ! { ! const int year = GET_YEAR(self); ! const int month = GET_MONTH(self); ! const int day = GET_DAY(self); ! ! return Py_BuildValue("iiiiiiiii", ! year, month, day, ! DATE_GET_HOUR(self), ! DATE_GET_MINUTE(self), ! DATE_GET_SECOND(self), ! weekday(year, month, day), ! days_before_month(year, month) + day, ! -1); ! } ! ! static PyObject * ! datetime_getdate(PyDateTime_DateTime *self) { ! return new_date((int)GET_YEAR(self), ! (int)GET_MONTH(self), ! (int)GET_DAY(self)); } --- 179,189 ---- } ! static int ! time_nonzero(PyDateTime_Time *self) { ! return TIME_GET_HOUR(self) || ! TIME_GET_MINUTE(self) || ! TIME_GET_SECOND(self) || ! TIME_GET_MICROSECOND(self); } *************** *** 497,508 **** static PyObject * ! datetime_getstate(PyDateTime_DateTime *self) { return PyString_FromStringAndSize(self->data, ! _PyDateTime_DATETIME_DATA_SIZE); } static PyObject * ! datetime_setstate(PyDateTime_DateTime *self, PyObject *state) { const int len = PyString_Size(state); --- 191,202 ---- static PyObject * ! time_getstate(PyDateTime_Time *self) { return PyString_FromStringAndSize(self->data, ! _PyDateTime_TIME_DATASIZE); } static PyObject * ! time_setstate(PyDateTime_Time *self, PyObject *state) { const int len = PyString_Size(state); *************** *** 510,519 **** if (! PyString_Check(state) || ! len != _PyDateTime_DATETIME_DATA_SIZE) { PyErr_SetString(PyExc_TypeError, ! "bad argument to datetime.__setstate__"); return NULL; } ! memcpy(self->data, pdata, _PyDateTime_DATETIME_DATA_SIZE); self->hashcode = -1; --- 204,213 ---- if (! PyString_Check(state) || ! len != _PyDateTime_TIME_DATASIZE) { PyErr_SetString(PyExc_TypeError, ! "bad argument to time.__setstate__"); return NULL; } ! memcpy(self->data, pdata, _PyDateTime_TIME_DATASIZE); self->hashcode = -1; *************** *** 524,542 **** /* XXX This seems a ridiculously inefficient way to pickle a short string. */ static PyObject * ! datetime_pickler(PyObject *module, PyDateTime_DateTime *datetime) { PyObject *state; PyObject *result = NULL; ! if (datetime->ob_type != &PyDateTime_DateTimeType) { PyErr_Format(PyExc_TypeError, ! "bad type passed to datetime pickler: %s", ! datetime->ob_type->tp_name); return NULL; } ! state = datetime_getstate(datetime); if (state) { result = Py_BuildValue("O(O)", ! datetime_unpickler_object, state); Py_DECREF(state); --- 218,236 ---- /* XXX This seems a ridiculously inefficient way to pickle a short string. */ static PyObject * ! time_pickler(PyObject *module, PyDateTime_Time *time) { PyObject *state; PyObject *result = NULL; ! if (time->ob_type != &PyDateTime_TimeType) { PyErr_Format(PyExc_TypeError, ! "bad type passed to time pickler: %s", ! time->ob_type->tp_name); return NULL; } ! state = time_getstate(time); if (state) { result = Py_BuildValue("O(O)", ! time_unpickler_object, state); Py_DECREF(state); *************** *** 546,562 **** static PyObject * ! datetime_unpickler(PyObject *module, PyObject *arg) { ! PyDateTime_DateTime *self; if (! PyString_CheckExact(arg)) { PyErr_Format(PyExc_TypeError, ! "bad type passed to datetime unpickler: %s", arg->ob_type->tp_name); return NULL; } ! self = PyObject_New(PyDateTime_DateTime, &PyDateTime_DateTimeType); if (self != NULL) { ! PyObject *res = datetime_setstate(self, arg); Py_XDECREF(res); } --- 240,256 ---- static PyObject * ! time_unpickler(PyObject *module, PyObject *arg) { ! PyDateTime_Time *self; if (! PyString_CheckExact(arg)) { PyErr_Format(PyExc_TypeError, ! "bad type passed to time unpickler: %s", arg->ob_type->tp_name); return NULL; } ! self = PyObject_New(PyDateTime_Time, &PyDateTime_TimeType); if (self != NULL) { ! PyObject *res = time_setstate(self, arg); Py_XDECREF(res); } *************** *** 564,621 **** } ! static PyMethodDef datetime_methods[] = { ! /* Class methods: */ ! /* XXX METH_CLASS is implemented incorrectly: ! * XXX http://www.python.org/sf/548651 ! * XXX The signatures of these methods will need to change (for ! * XXX the better) when that's fixed. ! */ ! {"now", (PyCFunction)datetime_now, ! METH_O | METH_CLASS, ! "Return a new datetime representing local day and time."}, ! ! {"utcnow", (PyCFunction)datetime_utcnow, ! METH_O | METH_CLASS, ! "Return a new datetime representing UTC day and time."}, ! ! {"fromtimestamp", (PyCFunction)datetime_fromtimestamp, ! METH_VARARGS | METH_CLASS, ! "timestamp -> local datetime from a POSIX timestamp " ! "(like time.time())."}, ! ! {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp, ! METH_VARARGS | METH_CLASS, ! "timestamp -> UTC datetime from a POSIX timestamp " ! "(like time.time())."}, ! ! /* Instance methods: */ ! {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS, ! "Return time tuple, compatible with time.localtime()."}, ! ! {"date", (PyCFunction)datetime_getdate, METH_NOARGS, ! "Return date object with same year, month and day."}, ! ! {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS, ! "Return ctime() style string."}, ! {"isoformat", (PyCFunction)datetime_isoformat, METH_KEYWORDS, ! "[sep] -> string in ISO 8601 format, YYYY-MM-DDTHH:MM:SS.mmmmmm.\n\n" ! "sep is used to separate the year from the time, and defaults\n" ! "to 'T'."}, ! {"__setstate__", (PyCFunction)datetime_setstate, METH_O, PyDoc_STR("__setstate__(state)")}, ! {"__getstate__", (PyCFunction)datetime_getstate, METH_NOARGS, PyDoc_STR("__getstate__() -> state")}, {NULL, NULL} }; ! static char datetime_doc[] = ! "Basic date/time type."; ! static PyNumberMethods datetime_as_number = { ! datetime_add, /* nb_add */ ! datetime_subtract, /* nb_subtract */ 0, /* nb_multiply */ 0, /* nb_divide */ --- 258,282 ---- } ! static PyMethodDef time_methods[] = { ! {"isoformat", (PyCFunction)time_isoformat, METH_KEYWORDS, ! "Return string in ISO 8601 format, HH:MM:SS.mmmmmm."}, ! {"strftime", (PyCFunction)time_strftime, METH_O, ! "format -> strftime() style string."}, ! {"__setstate__", (PyCFunction)time_setstate, METH_O, PyDoc_STR("__setstate__(state)")}, ! {"__getstate__", (PyCFunction)time_getstate, METH_NOARGS, PyDoc_STR("__getstate__() -> state")}, {NULL, NULL} }; ! static char time_doc[] = ! "Basic time type."; ! static PyNumberMethods time_as_number = { ! 0, /* nb_add */ ! 0, /* nb_subtract */ 0, /* nb_multiply */ 0, /* nb_divide */ *************** *** 626,638 **** 0, /* nb_positive */ 0, /* nb_absolute */ ! (inquiry)date_nonzero, /* nb_nonzero */ }; ! statichere PyTypeObject PyDateTime_DateTimeType = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ /* XXX When this module is renamed to datetime, change tp_name. */ ! "_datetime.datetime", /* tp_name */ ! sizeof(PyDateTime_DateTime), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)PyObject_Del, /* tp_dealloc */ --- 287,299 ---- 0, /* nb_positive */ 0, /* nb_absolute */ ! (inquiry)time_nonzero, /* nb_nonzero */ }; ! statichere PyTypeObject PyDateTime_TimeType = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ /* XXX When this module is renamed to datetime, change tp_name. */ ! "_datetime.time", /* tp_name */ ! sizeof(PyDateTime_Time), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)PyObject_Del, /* tp_dealloc */ *************** *** 641,651 **** 0, /* tp_setattr */ 0, /* tp_compare */ ! (reprfunc)datetime_repr, /* tp_repr */ ! &datetime_as_number, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ ! (hashfunc)datetime_hash, /* tp_hash */ 0, /* tp_call */ ! (reprfunc)datetime_str, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ --- 302,312 ---- 0, /* tp_setattr */ 0, /* tp_compare */ ! (reprfunc)time_repr, /* tp_repr */ ! &time_as_number, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ ! (hashfunc)time_hash, /* tp_hash */ 0, /* tp_call */ ! (reprfunc)time_isoformat, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ *************** *** 653,667 **** Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES | Py_TPFLAGS_BASETYPE, /* tp_flags */ ! datetime_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ ! (richcmpfunc)datetime_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ ! datetime_methods, /* tp_methods */ 0, /* tp_members */ ! datetime_getset, /* tp_getset */ ! &PyDateTime_DateType, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ --- 314,328 ---- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES | Py_TPFLAGS_BASETYPE, /* tp_flags */ ! time_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ ! (richcmpfunc)time_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ ! time_methods, /* tp_methods */ 0, /* tp_members */ ! time_getset, /* tp_getset */ ! 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ *************** *** 670,675 **** 0, /* tp_init */ 0, /* tp_alloc */ ! datetime_new, /* tp_new */ _PyObject_Del, /* tp_free */ }; - --- 331,335 ---- 0, /* tp_init */ 0, /* tp_alloc */ ! time_new, /* tp_new */ _PyObject_Del, /* tp_free */ }; Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.48 retrieving revision 1.49 diff -C2 -d -r1.48 -r1.49 *** test_both.py 7 Dec 2002 05:33:45 -0000 1.48 --- test_both.py 7 Dec 2002 18:34:39 -0000 1.49 *************** *** 40,43 **** --- 40,44 ---- date = datetime.date timedelta = datetime.timedelta + time = datetime.time MINYEAR = datetime.MINYEAR MAXYEAR = datetime.MAXYEAR *************** *** 1119,1122 **** --- 1120,1244 ---- # self.assertEqual(dt.time(), time(18, 45, 3, 1234)) + class TestTime(unittest.TestCase): + + theclass = time + + def test_basic_attributes(self): + t = self.theclass(12, 0) + self.assertEqual(t.hour, 12) + self.assertEqual(t.minute, 0) + self.assertEqual(t.second, 0) + self.assertEqual(t.microsecond, 0) + + def test_basic_attributes_nonzero(self): + # Make sure all attributes are non-zero so bugs in + # bit-shifting access show up. + t = self.theclass(12, 59, 59, 8000) + self.assertEqual(t.hour, 12) + self.assertEqual(t.minute, 59) + self.assertEqual(t.second, 59) + self.assertEqual(t.microsecond, 8000) + + def test_roundtrip(self): + for t in (self.theclass(1, 2, 3, 4),): + # Verify t -> string -> time identity. + s = repr(t) + t2 = eval(s) + self.assertEqual(t, t2) + + # Verify identity via reconstructing from pieces. + t2 = self.theclass(t.hour, t.minute, t.second, + t.microsecond) + self.assertEqual(t, t2) + + def test_comparing(self): + t1 = self.theclass(9, 0, 0) + t2 = self.theclass(10, 0, 0) + t3 = self.theclass(9, 0, 0) + self.assertEqual(t1, t3) + self.assert_(t2 > t3) + + def test_bad_constructor_arguments(self): + # bad hours + self.theclass(0, 0) # no exception + self.theclass(23, 0) # no exception + self.assertRaises(ValueError, self.theclass, -1, 0) + self.assertRaises(ValueError, self.theclass, 24, 0) + # bad minutes + self.theclass(23, 0) # no exception + self.theclass(23, 59) # no exception + self.assertRaises(ValueError, self.theclass, 23, -1) + self.assertRaises(ValueError, self.theclass, 23, 60) + # bad seconds + self.theclass(23, 59, 0) # no exception + self.theclass(23, 59, 59) # no exception + self.assertRaises(ValueError, self.theclass, 23, 59, -1) + self.assertRaises(ValueError, self.theclass, 23, 59, 60) + # bad microseconds + self.theclass(23, 59, 59, 0) # no exception + self.theclass(23, 59, 59, 999999) # no exception + self.assertRaises(ValueError, self.theclass, 23, 59, 59, -1) + self.assertRaises(ValueError, self.theclass, 23, 59, 59, 1000000) + + def test_hash_equality(self): + d = self.theclass(23, 30, 17) + e = self.theclass(23, 30, 17) + self.assertEqual(d, e) + self.assertEqual(hash(d), hash(e)) + + dic = {d: 1} + dic[e] = 2 + self.assertEqual(len(dic), 1) + self.assertEqual(dic[d], 2) + self.assertEqual(dic[e], 2) + + d = self.theclass(0, 5, 17) + e = self.theclass(0, 5, 17) + self.assertEqual(d, e) + self.assertEqual(hash(d), hash(e)) + + dic = {d: 1} + dic[e] = 2 + self.assertEqual(len(dic), 1) + self.assertEqual(dic[d], 2) + self.assertEqual(dic[e], 2) + + def test_isoformat(self): + t = self.theclass(4, 5, 1, 123) + self.assertEqual(t.isoformat(), "04:05:01.000123") + + def test_strftime(self): + t = self.theclass(1, 2, 3, 4) + self.assertEqual(t.strftime('%H %M %S'), "01 02 03") + + def test_str(self): + self.assertEqual(str(self.theclass(1, 2, 3, 4)), "01:02:03.000004") + self.assertEqual(str(self.theclass(10, 2, 3, 4000)), "10:02:03.004000") + self.assertEqual(str(self.theclass(0, 2, 3, 400000)), "00:02:03.400000") + self.assertEqual(str(self.theclass(12, 2, 3, 0)), "12:02:03.000000") + self.assertEqual(str(self.theclass(23, 15, 0, 0)), "23:15:00.000000") + + def test_repr(self): + name = self.theclass.__name__ + if TESTING_C: + name = '_datetime.' + name + + self.assertEqual(repr(self.theclass(1, 2, 3, 4)), + "%s(1, 2, 3, 4)" % name) + self.assertEqual(repr(self.theclass(10, 2, 3, 4000)), + "%s(10, 2, 3, 4000)" % name) + self.assertEqual(repr(self.theclass(0, 2, 3, 400000)), + "%s(0, 2, 3, 400000)" % name) + self.assertEqual(repr(self.theclass(12, 2, 3, 0)), + "%s(12, 2, 3)" % name) + self.assertEqual(repr(self.theclass(23, 15, 0, 0)), + "%s(23, 15)" % name) + + def test_resolution_info(self): + self.assert_(isinstance(self.theclass.min, self.theclass)) + self.assert_(isinstance(self.theclass.max, self.theclass)) + self.assert_(isinstance(self.theclass.resolution, timedelta)) + self.assert_(self.theclass.max > self.theclass.min) + def test_suite(): allsuites = [unittest.makeSuite(klass, 'test') *************** *** 1126,1129 **** --- 1248,1252 ---- TestDate, TestDateTime, + TestTime, ) ] Index: test_datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_datetime.py,v retrieving revision 1.55 retrieving revision 1.56 diff -C2 -d -r1.55 -r1.56 *** test_datetime.py 7 Dec 2002 05:33:45 -0000 1.55 --- test_datetime.py 7 Dec 2002 18:34:39 -0000 1.56 *************** *** 4,7 **** --- 4,13 ---- """ + # XXX When a test passes in both the Python and C implementations, it + # XXX gets moved from this file into test_both.py. + # XXX Eventually (when the C implementation is complete), this file will + # XXX be empty, and at that time test_both.py will be renamed to + # XXX test_datetime.py. + import sys import unittest *************** *** 10,132 **** MINYEAR, MAXYEAR ! class TestTime(unittest.TestCase): ! ! theclass = time ! ! def test_basic_attributes(self): ! t = self.theclass(12, 0) ! self.assertEqual(t.hour, 12) ! self.assertEqual(t.minute, 0) ! self.assertEqual(t.second, 0) ! self.assertEqual(t.microsecond, 0) ! ! def test_basic_attributes_nonzero(self): ! # Make sure all attributes are non-zero so bugs in ! # bit-shifting access show up. ! t = self.theclass(12, 59, 59, 8000) ! self.assertEqual(t.hour, 12) ! self.assertEqual(t.minute, 59) ! self.assertEqual(t.second, 59) ! self.assertEqual(t.microsecond, 8000) ! ! def test_roundtrip(self): ! for t in (self.theclass(1, 2, 3, 4),): ! # Verify t -> string -> time identity. ! s = repr(t) ! t2 = eval(s) ! self.assertEqual(t, t2) ! ! # Verify identity via reconstructing from pieces. ! t2 = self.theclass(t.hour, t.minute, t.second, ! t.microsecond) ! self.assertEqual(t, t2) ! ! def test_comparing(self): ! t1 = self.theclass(9, 0, 0) ! t2 = self.theclass(10, 0, 0) ! t3 = self.theclass(9, 0, 0) ! self.assertEqual(t1, t3) ! self.assert_(t2 > t3) ! ! def test_bad_constructor_arguments(self): ! # bad hours ! self.theclass(0, 0) # no exception ! self.theclass(23, 0) # no exception ! self.assertRaises(ValueError, self.theclass, -1, 0) ! self.assertRaises(ValueError, self.theclass, 24, 0) ! # bad minutes ! self.theclass(23, 0) # no exception ! self.theclass(23, 59) # no exception ! self.assertRaises(ValueError, self.theclass, 23, -1) ! self.assertRaises(ValueError, self.theclass, 23, 60) ! # bad seconds ! self.theclass(23, 59, 0) # no exception ! self.theclass(23, 59, 59) # no exception ! self.assertRaises(ValueError, self.theclass, 23, 59, -1) ! self.assertRaises(ValueError, self.theclass, 23, 59, 60) ! # bad microseconds ! self.theclass(23, 59, 59, 0) # no exception ! self.theclass(23, 59, 59, 999999) # no exception ! self.assertRaises(ValueError, self.theclass, 23, 59, 59, -1) ! self.assertRaises(ValueError, self.theclass, 23, 59, 59, 1000000) ! ! def test_hash_equality(self): ! d = self.theclass(23, 30, 17) ! e = self.theclass(23, 30, 17) ! self.assertEqual(d, e) ! self.assertEqual(hash(d), hash(e)) ! ! dic = {d: 1} ! dic[e] = 2 ! self.assertEqual(len(dic), 1) ! self.assertEqual(dic[d], 2) ! self.assertEqual(dic[e], 2) ! ! d = self.theclass(0, 5, 17) ! e = self.theclass(0, 5, 17) ! self.assertEqual(d, e) ! self.assertEqual(hash(d), hash(e)) ! ! dic = {d: 1} ! dic[e] = 2 ! self.assertEqual(len(dic), 1) ! self.assertEqual(dic[d], 2) ! self.assertEqual(dic[e], 2) ! ! def test_isoformat(self): ! t = self.theclass(4, 5, 1, 123) ! self.assertEqual(t.isoformat(), "04:05:01.000123") ! ! def test_strftime(self): ! t = self.theclass(1, 2, 3, 4) ! self.assertEqual(t.strftime('%H %M %S'), "01 02 03") ! ! def test_str(self): ! self.assertEqual(str(self.theclass(1, 2, 3, 4)), "1:02:03.000004") ! self.assertEqual(str(self.theclass(10, 2, 3, 4000)), "10:02:03.004") ! self.assertEqual(str(self.theclass(0, 2, 3, 400000)), "0:02:03.4") ! self.assertEqual(str(self.theclass(12, 2, 3, 0)), "12:02:03") ! self.assertEqual(str(self.theclass(23, 15, 0, 0)), "23:15") ! ! def test_repr(self): ! self.assertEqual(repr(self.theclass(1, 2, 3, 4)), ! "%s(1, 2, 3, 4)" % self.theclass.__name__) ! self.assertEqual(repr(self.theclass(10, 2, 3, 4000)), ! "%s(10, 2, 3, 4000)" % self.theclass.__name__) ! self.assertEqual(repr(self.theclass(0, 2, 3, 400000)), ! "%s(0, 2, 3, 400000)" % self.theclass.__name__) ! self.assertEqual(repr(self.theclass(12, 2, 3, 0)), ! "%s(12, 2, 3)" % self.theclass.__name__) ! self.assertEqual(repr(self.theclass(23, 15, 0, 0)), ! "%s(23, 15)" % self.theclass.__name__) ! ! def test_resolution_info(self): ! self.assert_(isinstance(self.theclass.min, self.theclass)) ! self.assert_(isinstance(self.theclass.max, self.theclass)) ! self.assert_(isinstance(self.theclass.resolution, timedelta)) ! self.assert_(self.theclass.max > self.theclass.min) ! ! ! class TestTimeTZ(TestTime): theclass = timetz --- 16,20 ---- MINYEAR, MAXYEAR ! class TestTimeTZ(unittest.TestCase): theclass = timetz *************** *** 154,160 **** self.assertEqual(t1, t3) self.assertEqual(t2, t3) ! self.assertEqual(str(t1), "7:47 -05:00") ! self.assertEqual(str(t2), "12:47 +00:00") ! self.assertEqual(str(t3), "13:47 +01:00") self.assertEqual(repr(t1), "timetz(7, 47, tzinfo=est)") self.assertEqual(repr(t2), "timetz(12, 47, tzinfo=utc)") --- 42,48 ---- self.assertEqual(t1, t3) self.assertEqual(t2, t3) ! self.assertEqual(str(t1), "07:47:00.000000-05:00") ! self.assertEqual(str(t2), "12:47:00.000000+00:00") ! self.assertEqual(str(t3), "13:47:00.000000+01:00") self.assertEqual(repr(t1), "timetz(7, 47, tzinfo=est)") self.assertEqual(repr(t2), "timetz(12, 47, tzinfo=utc)") *************** *** 266,274 **** def test_suite(): - s3 = unittest.makeSuite(TestTime, 'test') s4 = unittest.makeSuite(TestTimeTZ, 'test') s5 = unittest.makeSuite(TestDateTime, 'test') s6 = unittest.makeSuite(TestDateTimeTZ, 'test') ! return unittest.TestSuite([s3, s4, s5, s6]) def test_main(): --- 154,161 ---- def test_suite(): s4 = unittest.makeSuite(TestTimeTZ, 'test') s5 = unittest.makeSuite(TestDateTime, 'test') s6 = unittest.makeSuite(TestDateTimeTZ, 'test') ! return unittest.TestSuite([s4, s5, s6]) def test_main(): From tim_one@users.sourceforge.net Sat Dec 7 18:58:27 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sat, 07 Dec 2002 10:58:27 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime doc.txt,1.24,1.25 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv30522 Modified Files: doc.txt Log Message: Typo repair. Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.24 retrieving revision 1.25 diff -C2 -d -r1.24 -r1.25 *** doc.txt 7 Dec 2002 18:34:39 -0000 1.24 --- doc.txt 7 Dec 2002 18:58:25 -0000 1.25 *************** *** 504,508 **** ========== A time object represents an idealized time of day, independent of day ! and timezone. Constructor: --- 504,508 ---- ========== A time object represents an idealized time of day, independent of day ! and timezone. Constructor: *************** *** 510,514 **** time(hour=0, minute=0, second=0, microsecond=0) ! All arguments are optional. The may be ints or longs, in the following ranges: --- 510,514 ---- time(hour=0, minute=0, second=0, microsecond=0) ! All arguments are optional. They may be ints or longs, in the following ranges: *************** *** 527,534 **** .min ! The earliest representable time, time(0, 0, 0). .max ! The latest representable time, time(23, 59, 59). .resolution --- 527,534 ---- .min ! The earliest representable time, time(0, 0, 0, 0). .max ! The latest representable time, time(23, 59, 59, 999999). .resolution From tim_one@users.sourceforge.net Sat Dec 7 19:03:17 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sat, 07 Dec 2002 11:03:17 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_date.c,1.37,1.38 obj_datetime.c,1.32,1.33 obj_delta.c,1.23,1.24 obj_time.c,1.2,1.3 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv31784 Modified Files: obj_date.c obj_datetime.c obj_delta.c obj_time.c Log Message: Reviewed uses of Py_BuildValue and ensured that the right typecodes were getting used (bugs waiting to happen on 64-bit boxes). Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.37 retrieving revision 1.38 diff -C2 -d -r1.37 -r1.38 *** obj_date.c 7 Dec 2002 18:34:39 -0000 1.37 --- obj_date.c 7 Dec 2002 19:03:14 -0000 1.38 *************** *** 388,393 **** { if (self->hashcode == -1) { ! PyObject *temp = Py_BuildValue("lll", GET_YEAR(self), ! GET_MONTH(self), GET_DAY(self)); if (temp != NULL) { self->hashcode = PyObject_Hash(temp); --- 388,395 ---- { if (self->hashcode == -1) { ! PyObject *temp = Py_BuildValue("iii", ! GET_YEAR(self), ! GET_MONTH(self), ! GET_DAY(self)); if (temp != NULL) { self->hashcode = PyObject_Hash(temp); Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.32 retrieving revision 1.33 diff -C2 -d -r1.32 -r1.33 *** obj_datetime.c 7 Dec 2002 18:34:39 -0000 1.32 --- obj_datetime.c 7 Dec 2002 19:03:15 -0000 1.33 *************** *** 455,463 **** if (self->hashcode == -1) { PyObject *temp; ! temp = Py_BuildValue("lllllll", GET_YEAR(self), ! GET_MONTH(self), GET_DAY(self), ! DATE_GET_HOUR(self), DATE_GET_MINUTE(self), ! DATE_GET_SECOND(self), ! DATE_GET_MICROSECOND(self)); if (temp != NULL) { self->hashcode = PyObject_Hash(temp); --- 455,466 ---- if (self->hashcode == -1) { PyObject *temp; ! temp = Py_BuildValue("iiiiiii", ! GET_YEAR(self), ! GET_MONTH(self), ! GET_DAY(self), ! DATE_GET_HOUR(self), ! DATE_GET_MINUTE(self), ! DATE_GET_SECOND(self), ! DATE_GET_MICROSECOND(self)); if (temp != NULL) { self->hashcode = PyObject_Hash(temp); Index: obj_delta.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_delta.c,v retrieving revision 1.23 retrieving revision 1.24 diff -C2 -d -r1.23 -r1.24 *** obj_delta.c 7 Dec 2002 02:23:08 -0000 1.23 --- obj_delta.c 7 Dec 2002 19:03:15 -0000 1.24 *************** *** 276,283 **** { if (self->hashcode == -1) { ! PyObject *temp = Py_BuildValue("lll", ! self->days, ! self->seconds, ! self->microseconds); if (temp != NULL) { self->hashcode = PyObject_Hash(temp); --- 276,283 ---- { if (self->hashcode == -1) { ! PyObject *temp = Py_BuildValue("iii", ! (int)self->days, ! (int)self->seconds, ! (int)self->microseconds); if (temp != NULL) { self->hashcode = PyObject_Hash(temp); *************** *** 578,584 **** delta_getstate(PyDateTime_Delta *self) { ! return Py_BuildValue("lll", GET_TD_DAYS(self), ! GET_TD_SECONDS(self), ! GET_TD_MICROSECONDS(self)); } --- 578,584 ---- delta_getstate(PyDateTime_Delta *self) { ! return Py_BuildValue("iii", (int)GET_TD_DAYS(self), ! (int)GET_TD_SECONDS(self), ! (int)GET_TD_MICROSECONDS(self)); } Index: obj_time.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_time.c,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** obj_time.c 7 Dec 2002 18:34:39 -0000 1.2 --- obj_time.c 7 Dec 2002 19:03:15 -0000 1.3 *************** *** 166,170 **** if (self->hashcode == -1) { PyObject *temp; ! temp = Py_BuildValue("llll", TIME_GET_HOUR(self), TIME_GET_MINUTE(self), --- 166,170 ---- if (self->hashcode == -1) { PyObject *temp; ! temp = Py_BuildValue("iiii", TIME_GET_HOUR(self), TIME_GET_MINUTE(self), From tim_one@users.sourceforge.net Sat Dec 7 19:17:38 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sat, 07 Dec 2002 11:17:38 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.py,1.79,1.80 test_both.py,1.49,1.50 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv2914 Modified Files: datetime.py test_both.py Log Message: Beefed up some weak time tests. Added a time pickle test. Implemented pickling in the Python time implementation. Index: datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.py,v retrieving revision 1.79 retrieving revision 1.80 diff -C2 -d -r1.79 -r1.80 *** datetime.py 7 Dec 2002 18:34:39 -0000 1.79 --- datetime.py 7 Dec 2002 19:17:34 -0000 1.80 *************** *** 731,735 **** """ ! def __init__(self, hour, minute, second=0, microsecond=0): """Constructor. --- 731,735 ---- """ ! def __init__(self, hour=0, minute=0, second=0, microsecond=0): """Constructor. *************** *** 827,830 **** --- 827,844 ---- self.__second, 0, 0, -1)) + + # Pickle support. + + def __getstate__(self): + us2, us3 = divmod(self.__microsecond, 256) + us1, us2 = divmod(us2, 256) + return ("%c" * 6) % (self.__hour, self.__minute, self.__second, + us1, us2, us3) + + def __setstate__(self, string): + assert len(string) == 6 + self.__hour, self.__minute, self.__second, us1, us2, us3 = \ + map(ord, string) + self.__microsecond = (((us1 << 8) | us2) << 8) | us3 time.min = time(0, 0, 0) Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.49 retrieving revision 1.50 diff -C2 -d -r1.49 -r1.50 *** test_both.py 7 Dec 2002 18:34:39 -0000 1.49 --- test_both.py 7 Dec 2002 19:17:34 -0000 1.50 *************** *** 1141,1161 **** def test_roundtrip(self): ! for t in (self.theclass(1, 2, 3, 4),): ! # Verify t -> string -> time identity. ! s = repr(t) ! t2 = eval(s) ! self.assertEqual(t, t2) ! # Verify identity via reconstructing from pieces. ! t2 = self.theclass(t.hour, t.minute, t.second, ! t.microsecond) ! self.assertEqual(t, t2) def test_comparing(self): ! t1 = self.theclass(9, 0, 0) ! t2 = self.theclass(10, 0, 0) ! t3 = self.theclass(9, 0, 0) ! self.assertEqual(t1, t3) ! self.assert_(t2 > t3) def test_bad_constructor_arguments(self): --- 1141,1202 ---- def test_roundtrip(self): ! t = self.theclass(1, 2, 3, 4) ! # Verify t -> string -> time identity. ! s = repr(t) ! t2 = eval(s) ! self.assertEqual(t, t2) ! ! # Verify identity via reconstructing from pieces. ! t2 = self.theclass(t.hour, t.minute, t.second, ! t.microsecond) ! self.assertEqual(t, t2) def test_comparing(self): ! args = [1, 2, 3, 4] ! t1 = self.theclass(*args) ! t2 = self.theclass(*args) ! self.failUnless(t1 == t2) ! self.failUnless(t1 <= t2) ! self.failUnless(t1 >= t2) ! self.failUnless(not t1 != t2) ! self.failUnless(not t1 < t2) ! self.failUnless(not t1 > t2) ! self.assertEqual(cmp(t1, t2), 0) ! self.assertEqual(cmp(t2, t1), 0) ! ! for i in range(len(args)): ! newargs = args[:] ! newargs[i] = args[i] + 1 ! t2 = self.theclass(*newargs) # this is larger than t1 ! self.failUnless(t1 < t2) ! self.failUnless(t2 > t1) ! self.failUnless(t1 <= t2) ! self.failUnless(t2 >= t1) ! self.failUnless(t1 != t2) ! self.failUnless(t2 != t1) ! self.failUnless(not t1 == t2) ! self.failUnless(not t2 == t1) ! self.failUnless(not t1 > t2) ! self.failUnless(not t2 < t1) ! self.failUnless(not t1 >= t2) ! self.failUnless(not t2 <= t1) ! self.assertEqual(cmp(t1, t2), -1) ! self.assertEqual(cmp(t2, t1), 1) ! ! for badarg in (10, 10L, 34.5, "abc", {}, [], (), date(1, 1, 1), ! datetime.datetime(1, 1, 1, 1, 1), timedelta(9)): ! self.assertRaises(TypeError, lambda: t1 == badarg) ! self.assertRaises(TypeError, lambda: t1 != badarg) ! self.assertRaises(TypeError, lambda: t1 <= badarg) ! self.assertRaises(TypeError, lambda: t1 < badarg) ! self.assertRaises(TypeError, lambda: t1 > badarg) ! self.assertRaises(TypeError, lambda: t1 >= badarg) ! self.assertRaises(TypeError, lambda: badarg == t1) ! self.assertRaises(TypeError, lambda: badarg != t1) ! self.assertRaises(TypeError, lambda: badarg <= t1) ! self.assertRaises(TypeError, lambda: badarg < t1) ! self.assertRaises(TypeError, lambda: badarg > t1) ! self.assertRaises(TypeError, lambda: badarg >= t1) def test_bad_constructor_arguments(self): *************** *** 1240,1243 **** --- 1281,1299 ---- self.assert_(isinstance(self.theclass.resolution, timedelta)) self.assert_(self.theclass.max > self.theclass.min) + + def test_pickling(self): + import pickle, cPickle + args = 20, 59, 16, 64**2 + orig = self.theclass(*args) + state = orig.__getstate__() + self.assertEqual(state, '\x14\x3b\x10\x00\x10\x00') + derived = self.theclass() + derived.__setstate__(state) + self.assertEqual(orig, derived) + for pickler in pickle, cPickle: + for binary in 0, 1: + green = pickler.dumps(orig, binary) + derived = pickler.loads(green) + self.assertEqual(orig, derived) def test_suite(): From tim_one@users.sourceforge.net Sat Dec 7 19:51:21 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sat, 07 Dec 2002 11:51:21 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.py,1.80,1.81 doc.txt,1.25,1.26 obj_date.c,1.38,1.39 obj_datetime.c,1.33,1.34 test_both.py,1.50,1.51 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv14891 Modified Files: datetime.py doc.txt obj_date.c obj_datetime.c test_both.py Log Message: The behavior of these objects in Boolean contexts wasn't documented or tested, and differed between the Python and C implementations. Repaired all that. I'm not sure it's of real value that timdelta(0) and time(0) are considered false, and am especially dubious of the latter. Index: datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.py,v retrieving revision 1.80 retrieving revision 1.81 diff -C2 -d -r1.80 -r1.81 *** datetime.py 7 Dec 2002 19:17:34 -0000 1.80 --- datetime.py 7 Dec 2002 19:51:18 -0000 1.81 *************** *** 464,467 **** --- 464,472 ---- return hash((self.__days, self.__seconds, self.__microseconds)) + def __nonzero__(self): + return (self.__days != 0 or + self.__seconds != 0 or + self.__microseconds != 0) + def __getstate__(self): return (self.__days, self.__seconds, self.__microseconds) *************** *** 827,830 **** --- 832,841 ---- self.__second, 0, 0, -1)) + + def __nonzero__(self): + return (self.__hour != 0 or + self.__minute != 0 or + self.__second != 0 or + self.__microsecond != 0) # Pickle support. Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.25 retrieving revision 1.26 diff -C2 -d -r1.25 -r1.26 *** doc.txt 7 Dec 2002 18:58:25 -0000 1.25 --- doc.txt 7 Dec 2002 19:51:18 -0000 1.26 *************** *** 148,156 **** t.days < 0. This is exact, and cannot overflow. ! - comparison of timedelta to timedelta - hash, use as dict key ! - pickling --- 148,160 ---- t.days < 0. This is exact, and cannot overflow. ! - comparison of timedelta to timedelta; the timedelta representing ! the smaller duration is considered to be the smaller timedelta - hash, use as dict key ! - efficient pickling ! ! - in Boolean contexts, a timedelta object is consdired to be true ! if and only if it isn't equal to timedelta(0) *************** *** 247,251 **** - hash, use as dict key ! - pickling Instance methods: --- 251,257 ---- - hash, use as dict key ! - efficient pickling ! ! - in Boolean contexts, all date objects are considered to be true Instance methods: *************** *** 440,444 **** - hash, use as dict key ! - pickling Instance methods: --- 446,452 ---- - hash, use as dict key ! - efficient pickling ! ! - in Boolean contexts, all datetime objects are considered to be true Instance methods: *************** *** 550,554 **** - hash, use as dict key ! - pickling Instance methods: --- 558,565 ---- - hash, use as dict key ! - efficient pickling ! ! - in Boolean contexts, a time object is consdired to be true ! if and only if it isn't equal to time(0) Instance methods: Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.38 retrieving revision 1.39 diff -C2 -d -r1.38 -r1.39 *** obj_date.c 7 Dec 2002 19:03:14 -0000 1.38 --- obj_date.c 7 Dec 2002 19:51:18 -0000 1.39 *************** *** 400,410 **** } - static int - date_nonzero(PyDateTime_Date *self) - { - assert(GET_YEAR(self) >= 1); - return 1; - } - static PyObject * date_toordinal(PyDateTime_Date *self) --- 400,403 ---- *************** *** 562,566 **** 0, /* nb_positive */ 0, /* nb_absolute */ ! (inquiry)date_nonzero, /* nb_nonzero */ }; --- 555,559 ---- 0, /* nb_positive */ 0, /* nb_absolute */ ! 0, /* nb_nonzero */ }; Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.33 retrieving revision 1.34 diff -C2 -d -r1.33 -r1.34 *** obj_datetime.c 7 Dec 2002 19:03:15 -0000 1.33 --- obj_datetime.c 7 Dec 2002 19:51:18 -0000 1.34 *************** *** 628,632 **** 0, /* nb_positive */ 0, /* nb_absolute */ ! (inquiry)date_nonzero, /* nb_nonzero */ }; --- 628,632 ---- 0, /* nb_positive */ 0, /* nb_absolute */ ! 0, /* nb_nonzero */ }; Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.50 retrieving revision 1.51 diff -C2 -d -r1.50 -r1.51 *** test_both.py 7 Dec 2002 19:17:34 -0000 1.50 --- test_both.py 7 Dec 2002 19:51:18 -0000 1.51 *************** *** 328,331 **** --- 328,338 ---- (-1, 24*3600-1, 999999)) + def test_bool(self): + self.failUnless(timedelta(1)) + self.failUnless(timedelta(0, 1)) + self.failUnless(timedelta(0, 0, 1)) + self.failUnless(timedelta(microseconds=1)) + self.failUnless(not timedelta(0)) + ############################################################################# # date tests *************** *** 778,781 **** --- 785,793 ---- self.assertRaises(TypeError, lambda: badarg >= t1) + def test_bool(self): + # All dates are considered true. + self.failUnless(self.theclass.min) + self.failUnless(self.theclass.max) + ############################################################################# # datetime tests *************** *** 1296,1299 **** --- 1308,1320 ---- derived = pickler.loads(green) self.assertEqual(orig, derived) + + def test_bool(self): + cls = self.theclass + self.failUnless(cls(1)) + self.failUnless(cls(0, 1)) + self.failUnless(cls(0, 0, 1)) + self.failUnless(cls(0, 0, 0, 1)) + self.failUnless(not cls(0)) + self.failUnless(not cls()) def test_suite(): From tim_one@users.sourceforge.net Sat Dec 7 19:57:23 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sat, 07 Dec 2002 11:57:23 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime doc.txt,1.26,1.27 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv17653 Modified Files: doc.txt Log Message: Spelling repair. Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.26 retrieving revision 1.27 diff -C2 -d -r1.26 -r1.27 *** doc.txt 7 Dec 2002 19:51:18 -0000 1.26 --- doc.txt 7 Dec 2002 19:57:21 -0000 1.27 *************** *** 155,159 **** - efficient pickling ! - in Boolean contexts, a timedelta object is consdired to be true if and only if it isn't equal to timedelta(0) --- 155,159 ---- - efficient pickling ! - in Boolean contexts, a timedelta object is considred to be true if and only if it isn't equal to timedelta(0) *************** *** 560,564 **** - efficient pickling ! - in Boolean contexts, a time object is consdired to be true if and only if it isn't equal to time(0) --- 560,564 ---- - efficient pickling ! - in Boolean contexts, a time object is considered to be true if and only if it isn't equal to time(0) From tim_one@users.sourceforge.net Sat Dec 7 20:19:04 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sat, 07 Dec 2002 12:19:04 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime test_both.py,1.51,1.52 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv24722 Modified Files: test_both.py Log Message: Used True/False instead of 1/0, for clarity. Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.51 retrieving revision 1.52 diff -C2 -d -r1.51 -r1.52 *** test_both.py 7 Dec 2002 19:51:18 -0000 1.51 --- test_both.py 7 Dec 2002 20:19:02 -0000 1.52 *************** *** 431,435 **** # Test every day in a leap-year and a non-leap year. dim = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] ! for year, isleap in (2000, 1), (2002, 0): n = self.theclass(year, 1, 1).toordinal() for month, maxday in zip(range(1, 13), dim): --- 431,435 ---- # Test every day in a leap-year and a non-leap year. dim = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] ! for year, isleap in (2000, True), (2002, False): n = self.theclass(year, 1, 1).toordinal() for month, maxday in zip(range(1, 13), dim): From tim_one@users.sourceforge.net Sat Dec 7 20:24:48 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sat, 07 Dec 2002 12:24:48 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime doc.txt,1.27,1.28 obj_datetime.c,1.34,1.35 test_both.py,1.52,1.53 test_datetime.py,1.56,1.57 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv25917 Modified Files: doc.txt obj_datetime.c test_both.py test_datetime.py Log Message: Implemented the datetime.datetime.time() extractor. Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.27 retrieving revision 1.28 diff -C2 -d -r1.27 -r1.28 *** doc.txt 7 Dec 2002 19:57:21 -0000 1.27 --- doc.txt 7 Dec 2002 20:24:46 -0000 1.28 *************** *** 455,458 **** --- 455,461 ---- Return new date object with same year, month and day. + - time() + Return time object with same hour, minute, second and microsecond. + - timetuple() Return a 9-element tuple of the form returned by time.localtime(). Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.34 retrieving revision 1.35 diff -C2 -d -r1.34 -r1.35 *** obj_datetime.c 7 Dec 2002 19:51:18 -0000 1.34 --- obj_datetime.c 7 Dec 2002 20:24:46 -0000 1.35 *************** *** 491,497 **** datetime_getdate(PyDateTime_DateTime *self) { ! return new_date((int)GET_YEAR(self), ! (int)GET_MONTH(self), ! (int)GET_DAY(self)); } --- 491,506 ---- datetime_getdate(PyDateTime_DateTime *self) { ! return new_date(GET_YEAR(self), ! GET_MONTH(self), ! GET_DAY(self)); ! } ! ! static PyObject * ! datetime_gettime(PyDateTime_DateTime *self) ! { ! return new_time(DATE_GET_HOUR(self), ! DATE_GET_MINUTE(self), ! DATE_GET_SECOND(self), ! DATE_GET_MICROSECOND(self)); } *************** *** 597,600 **** --- 606,612 ---- {"date", (PyCFunction)datetime_getdate, METH_NOARGS, "Return date object with same year, month and day."}, + + {"time", (PyCFunction)datetime_gettime, METH_NOARGS, + "Return time object with same hour, minute, second and microsecond."}, {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS, Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.52 retrieving revision 1.53 diff -C2 -d -r1.52 -r1.53 *** test_both.py 7 Dec 2002 20:19:02 -0000 1.52 --- test_both.py 7 Dec 2002 20:24:46 -0000 1.53 *************** *** 1129,1134 **** dt = self.theclass(2002, 3, 4, 18, 45, 3, 1234) self.assertEqual(dt.date(), date(2002, 3, 4)) ! # Next line is in test_datetime now. ! # self.assertEqual(dt.time(), time(18, 45, 3, 1234)) class TestTime(unittest.TestCase): --- 1129,1133 ---- dt = self.theclass(2002, 3, 4, 18, 45, 3, 1234) self.assertEqual(dt.date(), date(2002, 3, 4)) ! self.assertEqual(dt.time(), time(18, 45, 3, 1234)) class TestTime(unittest.TestCase): Index: test_datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_datetime.py,v retrieving revision 1.56 retrieving revision 1.57 diff -C2 -d -r1.56 -r1.57 *** test_datetime.py 7 Dec 2002 18:34:39 -0000 1.56 --- test_datetime.py 7 Dec 2002 20:24:46 -0000 1.57 *************** *** 80,89 **** self.assertEqual(dt, datetime(2002, 3, 4, 18, 45, 3, 1234)) - def test_extract(self): - dt = self.theclass(2002, 3, 4, 18, 45, 3, 1234) - # Next line is in test_both now. - # self.assertEqual(dt.date(), date(2002, 3, 4)) - self.assertEqual(dt.time(), time(18, 45, 3, 1234)) - class FixedOffset(object): --- 80,83 ---- From tim_one@users.sourceforge.net Sat Dec 7 21:06:41 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sat, 07 Dec 2002 13:06:41 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.py,1.81,1.82 doc.txt,1.28,1.29 obj_datetime.c,1.35,1.36 test_both.py,1.53,1.54 test_datetime.py,1.57,1.58 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv5404 Modified Files: datetime.py doc.txt obj_datetime.c test_both.py test_datetime.py Log Message: Implemented the datetime.datetime.combine() constructor. Added type checking to the Python implementation of this. Moved the test case to test_both.py. Added error cases to the test. YUCK: The METH_CLASS bug makes the combination of a class method with METH_KEYWORDS excruciating. Index: datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.py,v retrieving revision 1.81 retrieving revision 1.82 diff -C2 -d -r1.81 -r1.82 *** datetime.py 7 Dec 2002 19:51:18 -0000 1.81 --- datetime.py 7 Dec 2002 21:06:38 -0000 1.82 *************** *** 1133,1136 **** --- 1133,1141 ---- def combine(cls, date, time): "Construct a datetime from a given date and a given time." + import datetime + if not isinstance(date, datetime.date): + raise TypeError("combine's first argument must be a date") + if not isinstance(time, datetime.time): + raise TypeError("combine's second argument must be a time") return cls(date.year, date.month, date.day, time.hour, time.minute, time.second, time.microsecond) Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.28 retrieving revision 1.29 diff -C2 -d -r1.28 -r1.29 *** doc.txt 7 Dec 2002 20:24:46 -0000 1.28 --- doc.txt 7 Dec 2002 21:06:38 -0000 1.29 *************** *** 396,399 **** --- 396,405 ---- second and microsecond of the result are all 0. + - combine(date, time) + + Return a new datetime object whose date components are equal to the + given date object's, and whose time components are equal to the given + time object's. + Class attributes: Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.35 retrieving revision 1.36 diff -C2 -d -r1.35 -r1.36 *** obj_datetime.c 7 Dec 2002 20:24:46 -0000 1.35 --- obj_datetime.c 7 Dec 2002 21:06:38 -0000 1.36 *************** *** 198,201 **** --- 198,231 ---- } + /* Return new datetime from date and time arguments. */ + static PyObject * + datetime_combine(PyObject *self, PyObject *args, PyObject *kw) + { + /* XXX Ack! The METH_CLASS bug (see below) makes us pass a + * XXX keyword name for the class argument. Rather than try to + * XXX work around it, we pass an "impossible" class name. This + * XXX function will need some reworking when the bug is fixed. + */ + static char *keywords[] = {" cls ", "date", "time", NULL}; + PyObject *cls; + PyObject *date; + PyObject *time; + PyObject *result = NULL; + + if (PyArg_ParseTupleAndKeywords(args, kw, "OO!O!:combine", keywords, + &cls, + &PyDateTime_DateType, &date, + &PyDateTime_TimeType, &time)) + result = PyObject_CallFunction(cls, "iiiiiii", + GET_YEAR(date), + GET_MONTH(date), + GET_DAY(date), + TIME_GET_HOUR(time), + TIME_GET_MINUTE(time), + TIME_GET_SECOND(time), + TIME_GET_MICROSECOND(time)); + return result; + } + static PyObject * datetime_utcnow(PyObject *self, PyObject *cls) *************** *** 294,298 **** (DATE_GET_MINUTE(left) - DATE_GET_MINUTE(right)) * 60 + DATE_GET_SECOND(left) - DATE_GET_SECOND(right); ! long delta_us = DATE_GET_MICROSECOND(left) - DATE_GET_MICROSECOND(right); --- 324,328 ---- (DATE_GET_MINUTE(left) - DATE_GET_MINUTE(right)) * 60 + DATE_GET_SECOND(left) - DATE_GET_SECOND(right); ! long delta_us = DATE_GET_MICROSECOND(left) - DATE_GET_MICROSECOND(right); *************** *** 365,369 **** GET_YEAR(self), GET_MONTH(self), GET_DAY(self), DATE_GET_HOUR(self), DATE_GET_MINUTE(self), ! DATE_GET_SECOND(self), DATE_GET_MICROSECOND(self)); } --- 395,399 ---- GET_YEAR(self), GET_MONTH(self), GET_DAY(self), DATE_GET_HOUR(self), DATE_GET_MINUTE(self), ! DATE_GET_SECOND(self), DATE_GET_MICROSECOND(self)); } *************** *** 461,465 **** DATE_GET_HOUR(self), DATE_GET_MINUTE(self), ! DATE_GET_SECOND(self), DATE_GET_MICROSECOND(self)); if (temp != NULL) { --- 491,495 ---- DATE_GET_HOUR(self), DATE_GET_MINUTE(self), ! DATE_GET_SECOND(self), DATE_GET_MICROSECOND(self)); if (temp != NULL) { *************** *** 599,602 **** --- 629,636 ---- "timestamp -> UTC datetime from a POSIX timestamp " "(like time.time())."}, + + {"combine", (PyCFunction)datetime_combine, + METH_KEYWORDS | METH_CLASS, + "date, time -> datetime with same date and time fields"}, /* Instance methods: */ Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.53 retrieving revision 1.54 diff -C2 -d -r1.53 -r1.54 *** test_both.py 7 Dec 2002 20:24:46 -0000 1.53 --- test_both.py 7 Dec 2002 21:06:38 -0000 1.54 *************** *** 1131,1134 **** --- 1131,1150 ---- self.assertEqual(dt.time(), time(18, 45, 3, 1234)) + def test_combine(self): + d = date(2002, 3, 4) + t = time(18, 45, 3, 1234) + expected = self.theclass(2002, 3, 4, 18, 45, 3, 1234) + combine = self.theclass.combine + dt = combine(d, t) + self.assertEqual(dt, expected) + dt = combine(time=t, date=d) + self.assertEqual(dt, expected) + + self.assertRaises(TypeError, combine) # need an arg + self.assertRaises(TypeError, combine, d) # need two args + self.assertRaises(TypeError, combine, t, d) # args reversed + self.assertRaises(TypeError, combine, d, t, 1) # too many args + self.assertRaises(TypeError, combine, "date", "time") # wrong types + class TestTime(unittest.TestCase): Index: test_datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_datetime.py,v retrieving revision 1.57 retrieving revision 1.58 diff -C2 -d -r1.57 -r1.58 *** test_datetime.py 7 Dec 2002 20:24:46 -0000 1.57 --- test_datetime.py 7 Dec 2002 21:06:39 -0000 1.58 *************** *** 74,84 **** self.assertEqual(timestamp, tm.time()) - def test_combine(self): - d = date(2002, 3, 4) - t = time(18, 45, 3, 1234) - dt = datetime.combine(d, t) - self.assertEqual(dt, datetime(2002, 3, 4, 18, 45, 3, 1234)) - - class FixedOffset(object): def __init__(self, offset, name): --- 74,77 ---- From tim_one@users.sourceforge.net Sat Dec 7 21:18:40 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sat, 07 Dec 2002 13:18:40 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_datetime.c,1.36,1.37 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv9948 Modified Files: obj_datetime.c Log Message: More typecode fiddling. BTW, the Python implementation shows leaks again! 11 references per test cycle. The C implementation does not show leaks. Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.36 retrieving revision 1.37 diff -C2 -d -r1.36 -r1.37 *** obj_datetime.c 7 Dec 2002 21:06:38 -0000 1.36 --- obj_datetime.c 7 Dec 2002 21:18:38 -0000 1.37 *************** *** 114,118 **** tm = f(&timet); if (tm) ! result = PyObject_CallFunction(cls, "lllllll", tm->tm_year + 1900, tm->tm_mon + 1, --- 114,118 ---- tm = f(&timet); if (tm) ! result = PyObject_CallFunction(cls, "iiiiiil", tm->tm_year + 1900, tm->tm_mon + 1, *************** *** 191,195 **** tm = localtime(&timet); ! return PyObject_CallFunction(cls, "llllll", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, --- 191,195 ---- tm = localtime(&timet); ! return PyObject_CallFunction(cls, "iiiiii", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, *************** *** 240,244 **** tm = gmtime(&timet); ! return PyObject_CallFunction(cls, "llllll", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, --- 240,244 ---- tm = gmtime(&timet); ! return PyObject_CallFunction(cls, "iiiiii", tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, From tim_one@users.sourceforge.net Sat Dec 7 21:39:19 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sat, 07 Dec 2002 13:39:19 -0800 Subject: [Python-checkins] python/dist/src/Objects typeobject.c,2.195,2.196 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv14618/python/Objects Modified Files: typeobject.c Log Message: slot_nb_nonzero(): Another leak uncovered by the sandbox datetime tests. I found the logic too confusing to follow here, so rewrote more than was likely absolutely necessary. Bugfix candidate. Index: typeobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/typeobject.c,v retrieving revision 2.195 retrieving revision 2.196 diff -C2 -d -r2.195 -r2.196 *** typeobject.c 6 Dec 2002 23:38:02 -0000 2.195 --- typeobject.c 7 Dec 2002 21:39:16 -0000 2.196 *************** *** 44,48 **** if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) { etype* et = (etype*)type; ! Py_INCREF(et->name); return et->name; --- 44,48 ---- if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) { etype* et = (etype*)type; ! Py_INCREF(et->name); return et->name; *************** *** 79,83 **** return -1; } ! if (strlen(PyString_AS_STRING(value)) != (size_t)PyString_GET_SIZE(value)) { PyErr_Format(PyExc_ValueError, --- 79,83 ---- return -1; } ! if (strlen(PyString_AS_STRING(value)) != (size_t)PyString_GET_SIZE(value)) { PyErr_Format(PyExc_ValueError, *************** *** 311,318 **** type->tp_base = old_base; type->tp_mro = old_mro; ! Py_DECREF(value); Py_DECREF(new_base); ! return -1; } --- 311,318 ---- type->tp_base = old_base; type->tp_mro = old_mro; ! Py_DECREF(value); Py_DECREF(new_base); ! return -1; } *************** *** 885,903 **** } ! /* Method resolution order algorithm C3 described in "A Monotonic Superclass Linearization for Dylan", by Kim Barrett, Bob Cassel, Paul Haahr, ! David A. Moon, Keith Playford, and P. Tucker Withington. (OOPSLA 1996) Some notes about the rules implied by C3: ! No duplicate bases. It isn't legal to repeat a class in a list of base classes. The next three properties are the 3 constraints in "C3". ! Local precendece order. If A precedes B in C's MRO, then A will precede B in the MRO of all subclasses of C. --- 885,903 ---- } ! /* Method resolution order algorithm C3 described in "A Monotonic Superclass Linearization for Dylan", by Kim Barrett, Bob Cassel, Paul Haahr, ! David A. Moon, Keith Playford, and P. Tucker Withington. (OOPSLA 1996) Some notes about the rules implied by C3: ! No duplicate bases. It isn't legal to repeat a class in a list of base classes. The next three properties are the 3 constraints in "C3". ! Local precendece order. If A precedes B in C's MRO, then A will precede B in the MRO of all subclasses of C. *************** *** 913,917 **** */ ! static int tail_contains(PyObject *list, int whence, PyObject *o) { int j, size; --- 913,917 ---- */ ! static int tail_contains(PyObject *list, int whence, PyObject *o) { int j, size; *************** *** 1011,1020 **** } ! static int pmerge(PyObject *acc, PyObject* to_merge) { int i, j, to_merge_size; int *remain; int ok, empty_cnt; ! to_merge_size = PyList_GET_SIZE(to_merge); --- 1011,1020 ---- } ! static int pmerge(PyObject *acc, PyObject* to_merge) { int i, j, to_merge_size; int *remain; int ok, empty_cnt; ! to_merge_size = PyList_GET_SIZE(to_merge); *************** *** 1033,1037 **** for (i = 0; i < to_merge_size; i++) { PyObject *candidate; ! PyObject *cur_list = PyList_GET_ITEM(to_merge, i); --- 1033,1037 ---- for (i = 0; i < to_merge_size; i++) { PyObject *candidate; ! PyObject *cur_list = PyList_GET_ITEM(to_merge, i); *************** *** 1093,1097 **** /* Find a superclass linearization that honors the constraints of the explicit lists of bases and the constraints implied by ! each base class. to_merge is a list of lists, where each list is a superclass --- 1093,1097 ---- /* Find a superclass linearization that honors the constraints of the explicit lists of bases and the constraints implied by ! each base class. to_merge is a list of lists, where each list is a superclass *************** *** 2289,2293 **** return 0; } ! return 1; } --- 2289,2293 ---- return 0; } ! return 1; } *************** *** 2356,2360 **** static PyMethodDef object_methods[] = { ! {"__reduce__", object_reduce, METH_NOARGS, PyDoc_STR("helper for pickle")}, {0} --- 2356,2360 ---- static PyMethodDef object_methods[] = { ! {"__reduce__", object_reduce, METH_NOARGS, PyDoc_STR("helper for pickle")}, {0} *************** *** 3735,3740 **** slot_nb_nonzero(PyObject *self) { ! PyObject *func, *res, *args; static PyObject *nonzero_str, *len_str; func = lookup_maybe(self, "__nonzero__", &nonzero_str); --- 3735,3741 ---- slot_nb_nonzero(PyObject *self) { ! PyObject *func, *args; static PyObject *nonzero_str, *len_str; + int result = -1; func = lookup_maybe(self, "__nonzero__", &nonzero_str); *************** *** 3743,3762 **** return -1; func = lookup_maybe(self, "__len__", &len_str); ! if (func == NULL) { ! if (PyErr_Occurred()) ! return -1; ! else ! return 1; ! } ! } ! args = res = PyTuple_New(0); if (args != NULL) { ! res = PyObject_Call(func, args, NULL); Py_DECREF(args); } Py_DECREF(func); ! if (res == NULL) ! return -1; ! return PyObject_IsTrue(res); } --- 3744,3761 ---- return -1; func = lookup_maybe(self, "__len__", &len_str); ! if (func == NULL) ! return PyErr_Occurred() ? -1 : 1; ! } ! args = PyTuple_New(0); if (args != NULL) { ! PyObject *temp = PyObject_Call(func, args, NULL); Py_DECREF(args); + if (temp != NULL) { + result = PyObject_IsTrue(temp); + Py_DECREF(temp); + } } Py_DECREF(func); ! return result; } From tim.one@comcast.net Sat Dec 7 21:46:59 2002 From: tim.one@comcast.net (Tim Peters) Date: Sat, 07 Dec 2002 16:46:59 -0500 Subject: [Python-checkins] python/dist/src/Objects typeobject.c,2.195,2.196 In-Reply-To: Message-ID: > slot_nb_nonzero(): Another leak uncovered by the sandbox datetime > tests. I found the logic too confusing to follow here, so rewrote more > than was likely absolutely necessary. Damn! I didn't mean to check in trim-trailing-whitespace changes too. This is the only part of the patch that mattered: *************** *** 3735,3740 **** slot_nb_nonzero(PyObject *self) { ! PyObject *func, *res, *args; static PyObject *nonzero_str, *len_str; func = lookup_maybe(self, "__nonzero__", &nonzero_str); --- 3735,3741 ---- slot_nb_nonzero(PyObject *self) { ! PyObject *func, *args; static PyObject *nonzero_str, *len_str; + int result = -1; func = lookup_maybe(self, "__nonzero__", &nonzero_str); *************** *** 3743,3762 **** return -1; func = lookup_maybe(self, "__len__", &len_str); ! if (func == NULL) { ! if (PyErr_Occurred()) ! return -1; ! else ! return 1; ! } ! } ! args = res = PyTuple_New(0); if (args != NULL) { ! res = PyObject_Call(func, args, NULL); Py_DECREF(args); } Py_DECREF(func); ! if (res == NULL) ! return -1; ! return PyObject_IsTrue(res); } --- 3744,3761 ---- return -1; func = lookup_maybe(self, "__len__", &len_str); ! if (func == NULL) ! return PyErr_Occurred() ? -1 : 1; ! } ! args = PyTuple_New(0); if (args != NULL) { ! PyObject *temp = PyObject_Call(func, args, NULL); Py_DECREF(args); + if (temp != NULL) { + result = PyObject_IsTrue(temp); + Py_DECREF(temp); + } } Py_DECREF(func); ! return result; } From tim_one@users.sourceforge.net Sat Dec 7 22:29:48 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sat, 07 Dec 2002 14:29:48 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_date.c,1.39,1.40 obj_datetime.c,1.37,1.38 obj_delta.c,1.24,1.25 obj_time.c,1.3,1.4 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv30004 Modified Files: obj_date.c obj_datetime.c obj_delta.c obj_time.c Log Message: Added PyDoc_STR() macros. Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.39 retrieving revision 1.40 diff -C2 -d -r1.39 -r1.40 *** obj_date.c 7 Dec 2002 19:51:18 -0000 1.39 --- obj_date.c 7 Dec 2002 22:29:45 -0000 1.40 *************** *** 492,540 **** {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS | METH_CLASS, ! "timestamp -> local date from a POSIX timestamp (like time.time())."}, {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS | METH_CLASS, ! "int -> date corresponding to a proleptic Gregorian ordinal."}, {"today", (PyCFunction)date_today, METH_O | METH_CLASS, ! "Current date or datetime: same as " ! "self.__class__.fromtimestamp(time.time())."}, /* Instance methods: */ {"ctime", (PyCFunction)date_ctime, METH_NOARGS, ! "Return ctime() style string."}, {"strftime", (PyCFunction)date_strftime, METH_O, ! "format -> strftime() style string."}, {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS, ! "Return time tuple, compatible with time.localtime()."}, {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS, ! "Return a 3-tuple containing ISO year, week number, and weekday.\n\n" ! "The first ISO week of the year is the (Mon-Sun) week containing the\n" ! "year's first Thursday; everything else derives from that."}, {"isoformat", (PyCFunction)date_str, METH_NOARGS, ! "Return string in ISO 8601 format, YYYY-MM-DD."}, {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS, ! "Return the day of the week represented by the date.\n" ! "Monday == 1 ... Sunday == 7"}, {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS, ! "Return proleptic Gregorian ordinal. January 1 of year 1 is day 1."}, {"weekday", (PyCFunction)date_weekday, METH_NOARGS, ! "Return the day of the week represented by the date.\n" ! "Monday == 0 ... Sunday == 6"}, {"__setstate__", (PyCFunction)date_setstate, METH_O, ! PyDoc_STR("__setstate__(state)")}, {"__getstate__", (PyCFunction)date_getstate, METH_NOARGS, ! PyDoc_STR("__getstate__() -> state")}, {NULL, NULL} --- 492,542 ---- {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS | METH_CLASS, ! PyDoc_STR("timestamp -> local date from a POSIX timestamp (like " ! "time.time()).")}, {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS | METH_CLASS, ! PyDoc_STR("int -> date corresponding to a proleptic Gregorian " ! "ordinal.")}, {"today", (PyCFunction)date_today, METH_O | METH_CLASS, ! PyDoc_STR("Current date or datetime: same as " ! "self.__class__.fromtimestamp(time.time()).")}, /* Instance methods: */ {"ctime", (PyCFunction)date_ctime, METH_NOARGS, ! PyDoc_STR("Return ctime() style string.")}, {"strftime", (PyCFunction)date_strftime, METH_O, ! PyDoc_STR("format -> strftime() style string.")}, {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS, ! PyDoc_STR("Return time tuple, compatible with time.localtime().")}, {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS, ! PyDoc_STR("Return a 3-tuple containing ISO year, week number, and " ! "weekday.")}, {"isoformat", (PyCFunction)date_str, METH_NOARGS, ! PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")}, {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS, ! PyDoc_STR("Return the day of the week represented by the date.\n" ! "Monday == 1 ... Sunday == 7")}, {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS, ! PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year " ! "1 is day 1.")}, {"weekday", (PyCFunction)date_weekday, METH_NOARGS, ! PyDoc_STR("Return the day of the week represented by the date.\n" ! "Monday == 0 ... Sunday == 6")}, {"__setstate__", (PyCFunction)date_setstate, METH_O, ! PyDoc_STR("__setstate__(state)")}, {"__getstate__", (PyCFunction)date_getstate, METH_NOARGS, ! PyDoc_STR("__getstate__() -> state")}, {NULL, NULL} *************** *** 542,546 **** static char date_doc[] = ! "Basic date type."; static PyNumberMethods date_as_number = { --- 544,548 ---- static char date_doc[] = ! PyDoc_STR("Basic date type."); static PyNumberMethods date_as_number = { Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.37 retrieving revision 1.38 diff -C2 -d -r1.37 -r1.38 *** obj_datetime.c 7 Dec 2002 21:18:38 -0000 1.37 --- obj_datetime.c 7 Dec 2002 22:29:45 -0000 1.38 *************** *** 614,665 **** {"now", (PyCFunction)datetime_now, METH_O | METH_CLASS, ! "Return a new datetime representing local day and time."}, {"utcnow", (PyCFunction)datetime_utcnow, METH_O | METH_CLASS, ! "Return a new datetime representing UTC day and time."}, {"fromtimestamp", (PyCFunction)datetime_fromtimestamp, METH_VARARGS | METH_CLASS, ! "timestamp -> local datetime from a POSIX timestamp " ! "(like time.time())."}, {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp, METH_VARARGS | METH_CLASS, ! "timestamp -> UTC datetime from a POSIX timestamp " ! "(like time.time())."}, {"combine", (PyCFunction)datetime_combine, METH_KEYWORDS | METH_CLASS, ! "date, time -> datetime with same date and time fields"}, /* Instance methods: */ {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS, ! "Return time tuple, compatible with time.localtime()."}, {"date", (PyCFunction)datetime_getdate, METH_NOARGS, ! "Return date object with same year, month and day."}, {"time", (PyCFunction)datetime_gettime, METH_NOARGS, ! "Return time object with same hour, minute, second and microsecond."}, {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS, ! "Return ctime() style string."}, {"isoformat", (PyCFunction)datetime_isoformat, METH_KEYWORDS, ! "[sep] -> string in ISO 8601 format, YYYY-MM-DDTHH:MM:SS.mmmmmm.\n\n" ! "sep is used to separate the year from the time, and defaults\n" ! "to 'T'."}, {"__setstate__", (PyCFunction)datetime_setstate, METH_O, ! PyDoc_STR("__setstate__(state)")}, {"__getstate__", (PyCFunction)datetime_getstate, METH_NOARGS, ! PyDoc_STR("__getstate__() -> state")}, {NULL, NULL} }; static char datetime_doc[] = ! "Basic date/time type."; static PyNumberMethods datetime_as_number = { --- 614,668 ---- {"now", (PyCFunction)datetime_now, METH_O | METH_CLASS, ! PyDoc_STR("Return a new datetime representing local day and time.")}, {"utcnow", (PyCFunction)datetime_utcnow, METH_O | METH_CLASS, ! PyDoc_STR("Return a new datetime representing UTC day and time.")}, {"fromtimestamp", (PyCFunction)datetime_fromtimestamp, METH_VARARGS | METH_CLASS, ! PyDoc_STR("timestamp -> local datetime from a POSIX timestamp " ! "(like time.time()).")}, {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp, METH_VARARGS | METH_CLASS, ! PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp " ! "(like time.time()).")}, {"combine", (PyCFunction)datetime_combine, METH_KEYWORDS | METH_CLASS, ! PyDoc_STR("date, time -> datetime with same date and time fields")}, /* Instance methods: */ {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS, ! PyDoc_STR("Return time tuple, compatible with time.localtime().")}, {"date", (PyCFunction)datetime_getdate, METH_NOARGS, ! PyDoc_STR("Return date object with same year, month and day.")}, {"time", (PyCFunction)datetime_gettime, METH_NOARGS, ! PyDoc_STR("Return time object with same hour, minute, second and " ! "microsecond.")}, {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS, ! PyDoc_STR("Return ctime() style string.")}, {"isoformat", (PyCFunction)datetime_isoformat, METH_KEYWORDS, ! PyDoc_STR("[sep] -> string in ISO 8601 format, " ! "YYYY-MM-DDTHH:MM:SS.mmmmmm.\n\n" ! "sep is used to separate the year from the time, and " ! "defaults\n" ! "to 'T'.")}, {"__setstate__", (PyCFunction)datetime_setstate, METH_O, ! PyDoc_STR("__setstate__(state)")}, {"__getstate__", (PyCFunction)datetime_getstate, METH_NOARGS, ! PyDoc_STR("__getstate__() -> state")}, {NULL, NULL} }; static char datetime_doc[] = ! PyDoc_STR("Basic date/time type."); static PyNumberMethods datetime_as_number = { Index: obj_delta.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_delta.c,v retrieving revision 1.24 retrieving revision 1.25 diff -C2 -d -r1.24 -r1.25 *** obj_delta.c 7 Dec 2002 19:03:15 -0000 1.24 --- obj_delta.c 7 Dec 2002 22:29:45 -0000 1.25 *************** *** 623,628 **** --- 623,630 ---- {"days", T_LONG, OFFSET(days), READONLY, PyDoc_STR("Number of days.")}, + {"seconds", T_LONG, OFFSET(seconds), READONLY, PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")}, + {"microseconds", T_LONG, OFFSET(microseconds), READONLY, PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")}, *************** *** 632,645 **** static PyMethodDef delta_methods[] = { {"__setstate__", (PyCFunction)delta_setstate, METH_O, ! PyDoc_STR("__setstate__(state)")}, {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS, ! NULL}, {"__getstate__", (PyCFunction)delta_getstate, METH_NOARGS, ! PyDoc_STR("__getstate__() -> state")}, {NULL, NULL}, }; static char delta_doc[] = ! "Difference between two datetime values."; static PyNumberMethods delta_as_number = { --- 634,649 ---- static PyMethodDef delta_methods[] = { {"__setstate__", (PyCFunction)delta_setstate, METH_O, ! PyDoc_STR("__setstate__(state)")}, ! {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS, ! PyDoc_STR("__setstate__(state)")}, ! {"__getstate__", (PyCFunction)delta_getstate, METH_NOARGS, ! PyDoc_STR("__getstate__() -> state")}, {NULL, NULL}, }; static char delta_doc[] = ! PyDoc_STR("Difference between two datetime values."); static PyNumberMethods delta_as_number = { Index: obj_time.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_time.c,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** obj_time.c 7 Dec 2002 19:03:15 -0000 1.3 --- obj_time.c 7 Dec 2002 22:29:45 -0000 1.4 *************** *** 260,278 **** static PyMethodDef time_methods[] = { {"isoformat", (PyCFunction)time_isoformat, METH_KEYWORDS, ! "Return string in ISO 8601 format, HH:MM:SS.mmmmmm."}, {"strftime", (PyCFunction)time_strftime, METH_O, ! "format -> strftime() style string."}, {"__setstate__", (PyCFunction)time_setstate, METH_O, ! PyDoc_STR("__setstate__(state)")}, {"__getstate__", (PyCFunction)time_getstate, METH_NOARGS, ! PyDoc_STR("__getstate__() -> state")}, {NULL, NULL} }; static char time_doc[] = ! "Basic time type."; static PyNumberMethods time_as_number = { --- 260,278 ---- static PyMethodDef time_methods[] = { {"isoformat", (PyCFunction)time_isoformat, METH_KEYWORDS, ! PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS.mmmmmm.")}, {"strftime", (PyCFunction)time_strftime, METH_O, ! PyDoc_STR("format -> strftime() style string.")}, {"__setstate__", (PyCFunction)time_setstate, METH_O, ! PyDoc_STR("__setstate__(state)")}, {"__getstate__", (PyCFunction)time_getstate, METH_NOARGS, ! PyDoc_STR("__getstate__() -> state")}, {NULL, NULL} }; static char time_doc[] = ! PyDoc_STR("Basic time type."); static PyNumberMethods time_as_number = { From theller@python.net Sat Dec 7 23:23:12 2002 From: theller@python.net (Thomas Heller) Date: 08 Dec 2002 00:23:12 +0100 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.py,1.81,1.82 doc.txt,1.28,1.29 obj_datetime.c,1.35,1.36 test_both.py,1.53,1.54 test_datetime.py,1.57,1.58 In-Reply-To: References: Message-ID: tim_one@users.sourceforge.net writes: > YUCK: The METH_CLASS bug makes the combination of a class method with > METH_KEYWORDS excruciating. Have you tried or looked at the patch? Thomas From tim@zope.com Sun Dec 8 06:17:49 2002 From: tim@zope.com (Tim Peters) Date: Sun, 8 Dec 2002 01:17:49 -0500 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.py,1.81,1.82 doc.txt,1.28,1.29 obj_datetime.c,1.35,1.36 test_both.py,1.53,1.54 test_datetime.py,1.57,1.58 In-Reply-To: Message-ID: [Thomas Heller] > Have you tried or looked at the patch? Sorry, I'm buried. What patch? From montanaro@users.sourceforge.net Sun Dec 8 18:36:26 2002 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Sun, 08 Dec 2002 10:36:26 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libshelve.tex,1.15,1.16 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv2668/Doc/lib Modified Files: libshelve.tex Log Message: Add support for binary pickles to the shelve module. In some situations this can result in significantly smaller files. All classes as well as the open function now accept an optional binary parameter, which defaults to False for backward compatibility. Added a small test suite, updated the libref documentation (including documenting the exported classes and fixing a few other nits) and added a note about the change to Misc/NEWS. Index: libshelve.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libshelve.tex,v retrieving revision 1.15 retrieving revision 1.16 diff -C2 -d -r1.15 -r1.16 *** libshelve.tex 15 Nov 2002 06:46:13 -0000 1.15 --- libshelve.tex 8 Dec 2002 18:36:23 -0000 1.16 *************** *** 20,24 **** import shelve ! d = shelve.open(filename) # open, with (g)dbm filename -- no suffix d[key] = data # store data at key (overwrites old data if --- 20,25 ---- import shelve ! d = shelve.open(filename) # open -- file may get suffix added by low-level ! # library d[key] = data # store data at key (overwrites old data if *************** *** 55,60 **** \item ! Dependent on the implementation, closing a persistent dictionary may ! or may not be necessary to flush changes to disk. \item --- 56,63 ---- \item ! Depending on the implementation, closing a persistent dictionary may ! or may not be necessary to flush changes to disk. The \method{__del__} ! method of the \class{Shelf} class calls the \method{close} method, so the ! programmer generally need not do this explicitly. \item *************** *** 68,75 **** \end{itemize} \begin{seealso} \seemodule{anydbm}{Generic interface to \code{dbm}-style databases.} ! \seemodule{dbhash}{BSD \code{db} database interface.} \seemodule{dbm}{Standard \UNIX{} database interface.} \seemodule{dumbdbm}{Portable implementation of the \code{dbm} interface.} --- 71,105 ---- \end{itemize} + \begin{classdesc}{Shelf}{dict\optional{, binary=False}} + A subclass of \class{UserDict.DictMixin} which stores pickled values in the + \var{dict} object. If the \var{binary} parameter is \constant{True}, binary + pickles will be used. This can provide much more compact storage than plain + text pickles, depending on the nature of the objects stored in the databse. + \end{classdesc} + + \begin{classdesc}{BsdDbShelf}{dict\optional{, binary=False}} + A subclass of \class{Shelf} which exposes \method{first}, \method{next}, + {}\method{previous}, \method{last} and \method{set_location} which are + available in the \module{bsddb} module but not in other database modules. + The \var{dict} object passed to the constructor must support those methods. + This is generally accomplished by calling one of \function{bsddb.hashopen}, + \function{bsddb.btopen} or \function{bsddb.rnopen}. The optional + \var{binary} parameter has the same interpretation as for the \class{Shelf} + class. + \end{classdesc} + + \begin{classdesc}{DbfilenameShelf}{dict\optional{, flag='c'}\optional{, binary=False}} + A subclass of \class{Shelf} which accepts a filename instead of a dict-like + object. The underlying file will be opened using \function{anydbm.open}. + By default, the file will be created and opened for both read and write. + The optional \var{binary} parameter has the same interpretation as for the + \class{Shelf} class. + \end{classdesc} \begin{seealso} \seemodule{anydbm}{Generic interface to \code{dbm}-style databases.} ! \seemodule{bsddb}{BSD \code{db} database interface.} ! \seemodule{dbhash}{Thin layer around the \module{bsddb} which provides an ! \function{open} function like the other database modules.} \seemodule{dbm}{Standard \UNIX{} database interface.} \seemodule{dumbdbm}{Portable implementation of the \code{dbm} interface.} From montanaro@users.sourceforge.net Sun Dec 8 18:36:26 2002 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Sun, 08 Dec 2002 10:36:26 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_shelve.py,NONE,1.1 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv2668/Lib/test Added Files: test_shelve.py Log Message: Add support for binary pickles to the shelve module. In some situations this can result in significantly smaller files. All classes as well as the open function now accept an optional binary parameter, which defaults to False for backward compatibility. Added a small test suite, updated the libref documentation (including documenting the exported classes and fixing a few other nits) and added a note about the change to Misc/NEWS. --- NEW FILE: test_shelve.py --- import os import unittest import shelve import glob from test import test_support class TestCase(unittest.TestCase): fn = "shelftemp.db" def test_ascii_file_shelf(self): try: s = shelve.open(self.fn, binary=False) s['key1'] = (1,2,3,4) self.assertEqual(s['key1'], (1,2,3,4)) s.close() finally: for f in glob.glob(self.fn+"*"): os.unlink(f) def test_binary_file_shelf(self): try: s = shelve.open(self.fn, binary=True) s['key1'] = (1,2,3,4) self.assertEqual(s['key1'], (1,2,3,4)) s.close() finally: for f in glob.glob(self.fn+"*"): os.unlink(f) def test_in_memory_shelf(self): d1 = {} s = shelve.Shelf(d1, binary=False) s['key1'] = (1,2,3,4) self.assertEqual(s['key1'], (1,2,3,4)) s.close() d2 = {} s = shelve.Shelf(d2, binary=True) s['key1'] = (1,2,3,4) self.assertEqual(s['key1'], (1,2,3,4)) s.close() self.assertEqual(len(d1), 1) self.assertNotEqual(d1, d2) def test_main(): test_support.run_unittest(TestCase) if __name__ == "__main__": test_main() From montanaro@users.sourceforge.net Sun Dec 8 18:36:26 2002 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Sun, 08 Dec 2002 10:36:26 -0800 Subject: [Python-checkins] python/dist/src/Lib shelve.py,1.17,1.18 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv2668/Lib Modified Files: shelve.py Log Message: Add support for binary pickles to the shelve module. In some situations this can result in significantly smaller files. All classes as well as the open function now accept an optional binary parameter, which defaults to False for backward compatibility. Added a small test suite, updated the libref documentation (including documenting the exported classes and fixing a few other nits) and added a note about the change to Misc/NEWS. Index: shelve.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/shelve.py,v retrieving revision 1.17 retrieving revision 1.18 diff -C2 -d -r1.17 -r1.18 *** shelve.py 15 Nov 2002 06:46:14 -0000 1.17 --- shelve.py 8 Dec 2002 18:36:24 -0000 1.18 *************** *** 52,57 **** """ ! def __init__(self, dict): self.dict = dict def keys(self): --- 52,58 ---- """ ! def __init__(self, dict, binary=False): self.dict = dict + self.binary = binary def keys(self): *************** *** 78,82 **** def __setitem__(self, key, value): f = StringIO() ! p = Pickler(f) p.dump(value) self.dict[key] = f.getvalue() --- 79,83 ---- def __setitem__(self, key, value): f = StringIO() ! p = Pickler(f, self.binary) p.dump(value) self.dict[key] = f.getvalue() *************** *** 113,118 **** """ ! def __init__(self, dict): ! Shelf.__init__(self, dict) def set_location(self, key): --- 114,119 ---- """ ! def __init__(self, dict, binary=False): ! Shelf.__init__(self, dict, binary) def set_location(self, key): *************** *** 149,158 **** """ ! def __init__(self, filename, flag='c'): import anydbm ! Shelf.__init__(self, anydbm.open(filename, flag)) ! def open(filename, flag='c'): """Open a persistent dictionary for reading and writing. --- 150,159 ---- """ ! def __init__(self, filename, flag='c', binary=False): import anydbm ! Shelf.__init__(self, anydbm.open(filename, flag), binary) ! def open(filename, flag='c', binary=False): """Open a persistent dictionary for reading and writing. *************** *** 161,163 **** """ ! return DbfilenameShelf(filename, flag) --- 162,164 ---- """ ! return DbfilenameShelf(filename, flag, binary) From montanaro@users.sourceforge.net Sun Dec 8 18:36:27 2002 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Sun, 08 Dec 2002 10:36:27 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.553,1.554 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv2668/Misc Modified Files: NEWS Log Message: Add support for binary pickles to the shelve module. In some situations this can result in significantly smaller files. All classes as well as the open function now accept an optional binary parameter, which defaults to False for backward compatibility. Added a small test suite, updated the libref documentation (including documenting the exported classes and fixing a few other nits) and added a note about the change to Misc/NEWS. Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.553 retrieving revision 1.554 diff -C2 -d -r1.553 -r1.554 *** NEWS 6 Dec 2002 12:48:47 -0000 1.553 --- NEWS 8 Dec 2002 18:36:24 -0000 1.554 *************** *** 441,444 **** --- 441,448 ---- storage for scripts originally written with dictionaries in mind. + - shelve.open and the various classes in shelve.py now accept an optional + binary flag, which defaults to False. If True, the values stored in the + shelf are binary pickles. + - A new package, logging, implements the logging API defined by PEP 282. The code is written by Vinay Sajip. From tim_one@users.sourceforge.net Sun Dec 8 19:02:33 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sun, 08 Dec 2002 11:02:33 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.py,1.82,1.83 doc.txt,1.29,1.30 obj_datetime.c,1.38,1.39 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv10604 Modified Files: datetime.py doc.txt obj_datetime.c Log Message: Use gettimeofday() for datetime.now() and datetime.utcnow(), on platforms that have it. NEEDS TESTING! Windows doesn't have this function, so I haven't even compiled the new code. Somebody please try this on Linux. Index: datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.py,v retrieving revision 1.82 retrieving revision 1.83 diff -C2 -d -r1.82 -r1.83 *** datetime.py 7 Dec 2002 21:06:38 -0000 1.82 --- datetime.py 8 Dec 2002 19:02:29 -0000 1.83 *************** *** 1112,1115 **** --- 1112,1120 ---- fromtimestamp = classmethod(fromtimestamp) + # XXX This is supposed to do better than we *can* do by using time.time(), + # XXX if the platform supports a more accurate way. The C implementation + # XXX uses gettimeofday on platforms that have it, but that isn't + # XXX available from Python. So now() may return different results + # XXX across the implementations. def now(cls): "Construct a datetime from time.time()." Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.29 retrieving revision 1.30 diff -C2 -d -r1.29 -r1.30 *** doc.txt 7 Dec 2002 21:06:38 -0000 1.29 --- doc.txt 8 Dec 2002 19:02:30 -0000 1.30 *************** *** 362,367 **** Return the current local datetime. This is like today(), but, if possible, supplies more precision than can be gotten from going ! through a time.time() timestamp. ! XXX It currently doesn't. To the contrary, it's currently worse. See also today(), utcnow(). --- 362,367 ---- Return the current local datetime. This is like today(), but, if possible, supplies more precision than can be gotten from going ! through a time.time() timestamp (for example, this may be possible ! on platforms that supply the C gettimeofday() function). See also today(), utcnow(). Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.38 retrieving revision 1.39 diff -C2 -d -r1.38 -r1.39 *** obj_datetime.c 7 Dec 2002 22:29:45 -0000 1.38 --- obj_datetime.c 8 Dec 2002 19:02:31 -0000 1.39 *************** *** 104,113 **** typedef struct tm *(*TM_FUNC)(const time_t *timer); static PyObject * ! datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp) { struct tm *tm; - time_t timet = (time_t)timestamp; - long us = (long)((timestamp - (double)timet) * 1e6); PyObject *result = NULL; --- 104,115 ---- typedef struct tm *(*TM_FUNC)(const time_t *timer); + /* Internal helper. + * Build datetime from a time_t and a distinct count of microseconds. + * Pass localtime or gmtime for f, to control the interpretation of timet. + */ static PyObject * ! datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, long us) { struct tm *tm; PyObject *result = NULL; *************** *** 129,132 **** --- 131,195 ---- } + /* Internal helper. + * Build datetime from a Python timestamp. Pass localtime or gmtime for f, + * to control the interpretation of the timestamp. Since a double doesn't + * have enough bits to cover a datetime's full range of precision, it's + * better to call datetime_from_timet_and_us provided you have a way + * to get that much precision (e.g., C time() isn't good enough). + */ + static PyObject * + datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp) + { + time_t timet = (time_t)timestamp; + long us = (long)((timestamp - (double)timet) * 1e6); + + return datetime_from_timet_and_us(cls, f, timet, us); + } + + /* Internal helper. + * Build most accurate possible datetime for current time. Pass localtime or + * gmtime for f as appropriate. + */ + static PyObject * + datetime_best_possible(PyObject *cls, TM_FUNC f) + { + #ifdef HAVE_GETTIMEOFDAY + struct timeval t; + + #ifdef GETTIMEOFDAY_NO_TZ + gettimeofday(&t); + #else + gettimeofday(&t, (struct timezone *)NULL); + #endif + return datetime_from_timet_and_us(cls, f, t.tv_sec, t.tv_usec); + + #else /* ! HAVE_GETTIMEOFDAY */ + /* No flavor of gettimeofday exists on this platform. Python's + * time.time() does a lot of other platform tricks to get the + * best time it can on the platform, and we're not going to do + * better than that (if we could, the better code would belong + * in time.time()!) We're limited by the precision of a double, + * though. + */ + PyObject *time_time; /* time.time() */ + double dtime; + PyObject *time = PyImport_ImportModule("time"); + + if (time == NULL) + return NULL; + + time_time = PyObject_CallMethod(time, "time", "()"); + Py_DECREF(time); + if (time_time == NULL) + return NULL; + + dtime = PyFloat_AsDouble(time_time); + Py_DECREF(time_time); + if (dtime == -1.0 && PyErr_Occurred()) + return NULL; + return datetime_from_timestamp(cls, f, dtime); + #endif /* ! HAVE_GETTIMEOFDAY */ + } + /* Return new local datetime from timestamp (Python timestamp -- a double). */ static PyObject * *************** *** 155,199 **** } static PyObject * datetime_now(PyObject *self, PyObject *cls) { ! /* XXX MAJOR: This needs to get some notion of current time ! * XXX to better than 1-second resolution. Doing this in a x- ! * XXX platform way is mondo painful. Maybe floattime() from ! * XXX timemodule.c is good enough? We're running out of bits ! * XXX in a typical time_t, though, and gettimeofday() should do ! * XXX better than floattime() -- but gettimeofday isn't portable. ! */ ! #if 0 ! /* XXX need to create the instance by calling cls(y,mon,d,h,min,s,u) */ ! struct timeval t; ! struct tm *tm; ! time_t timet; ! ! #ifdef GETTIMEOFDAY_NO_TZ ! gettimeofday(&t); ! #else /* !GETTIMEOFDAY_NO_TZ */ ! gettimeofday(&t, (struct timezone *)NULL); ! #endif /* !GETTIMEOFDAY_NO_TZ */ ! timet = t.tv_sec; ! tm = localtime(&timet); ! ! return PyObject_CallFunction(cls, "iiiiiil", ! tm->tm_year + 1900, tm->tm_mon + 1, ! tm->tm_mday, tm->tm_hour, tm->tm_min, ! tm->tm_sec, t.tv_usec); ! #else ! /* XXX need to create the instance by calling cls(y,mon,d,h,min,s,u) */ ! struct tm *tm; ! time_t timet; ! ! time(&timet); ! tm = localtime(&timet); ! return PyObject_CallFunction(cls, "iiiiii", ! tm->tm_year + 1900, tm->tm_mon + 1, ! tm->tm_mday, tm->tm_hour, tm->tm_min, ! tm->tm_sec); ! #endif } --- 218,237 ---- } + /* Return best possible local time -- this isn't constrained by the + * precision of a timestamp. + */ static PyObject * datetime_now(PyObject *self, PyObject *cls) { ! return datetime_best_possible(cls, localtime); ! } ! /* Return best possible UTC time -- this isn't constrained by the ! * precision of a timestamp. ! */ ! static PyObject * ! datetime_utcnow(PyObject *self, PyObject *cls) ! { ! return datetime_best_possible(cls, gmtime); } *************** *** 226,247 **** TIME_GET_MICROSECOND(time)); return result; - } - - static PyObject * - datetime_utcnow(PyObject *self, PyObject *cls) - { - /* XXX Like datetime_now, this would like to do better than - * XXX 1-second resolution. - */ - struct tm *tm; - time_t timet; - - time(&timet); - tm = gmtime(&timet); - - return PyObject_CallFunction(cls, "iiiiii", - tm->tm_year + 1900, tm->tm_mon + 1, - tm->tm_mday, tm->tm_hour, tm->tm_min, - tm->tm_sec); } --- 264,267 ---- From tim_one@users.sourceforge.net Sun Dec 8 19:21:34 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sun, 08 Dec 2002 11:21:34 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime doc.txt,1.30,1.31 test_both.py,1.54,1.55 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv16211 Modified Files: doc.txt test_both.py Log Message: Noted the obvious invariant among datetime.combine(), d.date() and d.time(), and added some test lines to verify it. Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.30 retrieving revision 1.31 diff -C2 -d -r1.30 -r1.31 *** doc.txt 8 Dec 2002 19:02:30 -0000 1.30 --- doc.txt 8 Dec 2002 19:21:32 -0000 1.31 *************** *** 400,404 **** Return a new datetime object whose date components are equal to the given date object's, and whose time components are equal to the given ! time object's. Class attributes: --- 400,405 ---- Return a new datetime object whose date components are equal to the given date object's, and whose time components are equal to the given ! time object's. For any datetime object d, ! d == datetime.combine(d.date(), d.time()). Class attributes: Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.54 retrieving revision 1.55 diff -C2 -d -r1.54 -r1.55 *** test_both.py 7 Dec 2002 21:06:38 -0000 1.54 --- test_both.py 8 Dec 2002 19:21:32 -0000 1.55 *************** *** 1138,1143 **** --- 1138,1148 ---- dt = combine(d, t) self.assertEqual(dt, expected) + dt = combine(time=t, date=d) self.assertEqual(dt, expected) + + self.assertEqual(d, dt.date()) + self.assertEqual(t, dt.time()) + self.assertEqual(dt, combine(dt.date(), dt.time())) self.assertRaises(TypeError, combine) # need an arg From gvanrossum@users.sourceforge.net Sun Dec 8 20:00:48 2002 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Sun, 08 Dec 2002 12:00:48 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.c,1.47,1.48 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv28296 Modified Files: datetime.c Log Message: Shut up GCC warning about possibly unused variable. Index: datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.c,v retrieving revision 1.47 retrieving revision 1.48 diff -C2 -d -r1.47 -r1.48 *** datetime.c 7 Dec 2002 18:34:39 -0000 1.47 --- datetime.c 8 Dec 2002 20:00:45 -0000 1.48 *************** *** 612,615 **** --- 612,616 ---- default: assert(! "op unknown"); + istrue = 0; /* To shut up compiler */ } result = istrue ? Py_True : Py_False; From gvanrossum@users.sourceforge.net Sun Dec 8 20:01:15 2002 From: gvanrossum@users.sourceforge.net (gvanrossum@users.sourceforge.net) Date: Sun, 08 Dec 2002 12:01:15 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime Makefile,1.6,1.7 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv28449 Modified Files: Makefile Log Message: Standard targets: default doesn't test, check->test, clean. Index: Makefile =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/Makefile,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** Makefile 20 Aug 2002 19:02:40 -0000 1.6 --- Makefile 8 Dec 2002 20:01:13 -0000 1.7 *************** *** 1,14 **** PYTHON=python2.3 - #PYTHON=../../../trunk/debug/python ! default: check ! all: _datetime.so ! _datetime.so: datetime.c datetime.h $(PYTHON) setup.py build_ext -i ! check: _datetime.so ! $(PYTHON) test_datetime.py ! $(PYTHON) test_cdatetime.py ! test: check --- 1,14 ---- PYTHON=python2.3 ! DTSO= _datetime.so ! all: $(DTSO) ! ! $(DTSO): datetime.c datetime.h $(PYTHON) setup.py build_ext -i ! test: $(DTSO) ! $(PYTHON) test_both.py ! clean: ! rm -rf $(DTSO) build *.pyc *.pyo *~ From montanaro@users.sourceforge.net Sun Dec 8 21:25:02 2002 From: montanaro@users.sourceforge.net (montanaro@users.sourceforge.net) Date: Sun, 08 Dec 2002 13:25:02 -0800 Subject: [Python-checkins] python/dist/src/Lib shelve.py,1.18,1.19 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv21497 Modified Files: shelve.py Log Message: self.binary -> self._binary to remove it from the public interface - suggestion by Raymond Hettinger. Index: shelve.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/shelve.py,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** shelve.py 8 Dec 2002 18:36:24 -0000 1.18 --- shelve.py 8 Dec 2002 21:25:00 -0000 1.19 *************** *** 54,58 **** def __init__(self, dict, binary=False): self.dict = dict ! self.binary = binary def keys(self): --- 54,58 ---- def __init__(self, dict, binary=False): self.dict = dict ! self._binary = binary def keys(self): *************** *** 79,83 **** def __setitem__(self, key, value): f = StringIO() ! p = Pickler(f, self.binary) p.dump(value) self.dict[key] = f.getvalue() --- 79,83 ---- def __setitem__(self, key, value): f = StringIO() ! p = Pickler(f, self._binary) p.dump(value) self.dict[key] = f.getvalue() From tim_one@users.sourceforge.net Mon Dec 9 01:35:49 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sun, 08 Dec 2002 17:35:49 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime doc.txt,1.31,1.32 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv27451 Modified Files: doc.txt Log Message: Added TODO/OPEN and C API sections. Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.31 retrieving revision 1.32 diff -C2 -d -r1.31 -r1.32 *** doc.txt 8 Dec 2002 19:21:32 -0000 1.31 --- doc.txt 9 Dec 2002 01:35:47 -0000 1.32 *************** *** 1,2 **** --- 1,44 ---- + TODO/OPEN + ========= + - datetimetz needs a C implementation. + + - timetz needs a C implementation. + + - Behavior in Boolean contexts. Currently time(0) and timedelta(0) act + as false, everything else acts true. Is this desired? timedelta(0) + seems reasonable since it's very number-like, but time(0) acting false + bothers me (midnight isn't especially more zero-like than noon). + + - What should str() do? It generally acts like a synonym for isoformat() + now. But + + >>> print time(2) + 02:00:00.000000 + >>> + + is arguably better as '2:00:00' or even '2:00'. The Python + implementation has (overridden) "pretty __str__" according to one + person's idea of "pretty", for a couple types. Rat hole. + + - The METH_CLASS bug affects about a dozen functions here. They'll need + to be recoded in minor ways when the bug gets fixed. The bug needs to + be fixed. + + - pickles still "feel too big". + + - Subclass relationships. Currently datetime is a subclass of date. + I like this in practice, and think it's theoretically sound too. + Should this be blessed? I expect the same questions to pop up for + timetz wrt time, and datetimetz wrt datetime. + + - The type objects aren't exposed, due to headaches with DLL/.so. + + - LaTeXize the docs. + + - Move from sandbox to mainline. + + + Docs + ==== The datetime module supplies a number of classes for manipulating dates and times, in both simple and complex ways. *************** *** 589,590 **** --- 631,664 ---- class timetz ============ + + + C API + ===== + Struct typedefs: + + PyDateTime_Date + PyDateTime_DateTime + PyDateTime_Time + PyDateTime_Delta + + Accessor macros: + + All objects are immutable, so accessors are read-only. All macros + return ints: + + For date instances: + PyDateTime_GET_YEAR(o) + PyDateTime_GET_MONTH(o) + PyDateTime_GET_DAY(o) + + Ror datetime and date instances: + PyDateTime_DATE_GET_HOUR(o) + PyDateTime_DATE_GET_MINUTE(o) + PyDateTime_DATE_GET_SECOND(o) + PyDateTime_DATE_GET_MICROSECOND(o) + + For time instances: + PyDateTime_TIME_GET_HOUR(o) + PyDateTime_TIME_GET_MINUTE(o) + PyDateTime_TIME_GET_SECOND(o) + PyDateTime_TIME_GET_MICROSECOND(o) From tim_one@users.sourceforge.net Mon Dec 9 01:40:13 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sun, 08 Dec 2002 17:40:13 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime doc.txt,1.32,1.33 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv28674 Modified Files: doc.txt Log Message: Added timestamp issue. Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.32 retrieving revision 1.33 diff -C2 -d -r1.32 -r1.33 *** doc.txt 9 Dec 2002 01:35:47 -0000 1.32 --- doc.txt 9 Dec 2002 01:40:11 -0000 1.33 *************** *** 38,41 **** --- 38,46 ---- - Move from sandbox to mainline. + - Every function involving a timestamp inherits platform C limitations + on year range, on resolution, and on precision. If we were to invent + our own timestamp format, an IEEE double doesn't have enough bits to + cover 9999 years to microsecond resolution. + Docs From neal@metaslash.com Mon Dec 9 01:47:54 2002 From: neal@metaslash.com (Neal Norwitz) Date: Sun, 8 Dec 2002 20:47:54 -0500 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.py,1.81,1.82 doc.txt,1.28,1.29 obj_datetime.c,1.35,1.36 test_both.py,1.53,1.54 test_datetime.py,1.57,1.58 In-Reply-To: References: Message-ID: <20021209014754.GK16807@epoch.metaslash.com> On Sun, Dec 08, 2002 at 01:17:49AM -0500, Tim Peters wrote: > [Thomas Heller] > > Have you tried or looked at the patch? > > Sorry, I'm buried. What patch? I think Thomas means the one attached to the bug report: http://python.org/sf/548651 From tim_one@users.sourceforge.net Mon Dec 9 01:51:14 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sun, 08 Dec 2002 17:51:14 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.c,1.48,1.49 obj_date.c,1.40,1.41 obj_datetime.c,1.39,1.40 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv31711 Modified Files: datetime.c obj_date.c obj_datetime.c Log Message: Squash code duplication: introduced time_time() helper, to call the Python time.time(). Index: datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.c,v retrieving revision 1.48 retrieving revision 1.49 diff -C2 -d -r1.48 -r1.49 *** datetime.c 8 Dec 2002 20:00:45 -0000 1.48 --- datetime.c 9 Dec 2002 01:51:10 -0000 1.49 *************** *** 142,145 **** --- 142,159 ---- }; + /* Call time.time() and return its result (a Python float). */ + static PyObject * + time_time() + { + PyObject *result = NULL; + PyObject *time = PyImport_ImportModule("time"); + + if (time != NULL) { + result = PyObject_CallMethod(time, "time", "()"); + Py_DECREF(time); + } + return result; + } + /* year -> 1 if leap year, else 0. */ static int Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.40 retrieving revision 1.41 diff -C2 -d -r1.40 -r1.41 *** obj_date.c 7 Dec 2002 22:29:45 -0000 1.40 --- obj_date.c 9 Dec 2002 01:51:11 -0000 1.41 *************** *** 93,109 **** date_today(PyObject *self, PyObject *cls) { ! PyObject *time; /* the time module */ ! PyObject *time_time; /* time.time() */ PyObject *result; ! time = PyImport_ImportModule("time"); if (time == NULL) return NULL; - time_time = PyObject_CallMethod(time, "time", "()"); - Py_DECREF(time); - if (time_time == NULL) - return NULL; - /* Note well: today() is a class method, so this may not call * date.fromtimestamp. For example, it may call --- 93,103 ---- date_today(PyObject *self, PyObject *cls) { ! PyObject *time; PyObject *result; ! time = time_time(); if (time == NULL) return NULL; /* Note well: today() is a class method, so this may not call * date.fromtimestamp. For example, it may call *************** *** 112,117 **** * date.today() could get away with plain C time(). */ ! result = PyObject_CallMethod(cls, "fromtimestamp", "O", time_time); ! Py_DECREF(time_time); return result; } --- 106,111 ---- * date.today() could get away with plain C time(). */ ! result = PyObject_CallMethod(cls, "fromtimestamp", "O", time); ! Py_DECREF(time); return result; } Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.39 retrieving revision 1.40 diff -C2 -d -r1.39 -r1.40 *** obj_datetime.c 8 Dec 2002 19:02:31 -0000 1.39 --- obj_datetime.c 9 Dec 2002 01:51:11 -0000 1.40 *************** *** 172,189 **** * though. */ ! PyObject *time_time; /* time.time() */ double dtime; - PyObject *time = PyImport_ImportModule("time"); - - if (time == NULL) - return NULL; ! time_time = PyObject_CallMethod(time, "time", "()"); ! Py_DECREF(time); ! if (time_time == NULL) return NULL; ! ! dtime = PyFloat_AsDouble(time_time); ! Py_DECREF(time_time); if (dtime == -1.0 && PyErr_Occurred()) return NULL; --- 172,183 ---- * though. */ ! PyObject *time; double dtime; ! time = time_time(); ! if (time == NULL) return NULL; ! dtime = PyFloat_AsDouble(time); ! Py_DECREF(time); if (dtime == -1.0 && PyErr_Occurred()) return NULL; From tim_one@users.sourceforge.net Mon Dec 9 02:20:36 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Sun, 08 Dec 2002 18:20:36 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.py,1.83,1.84 obj_date.c,1.41,1.42 obj_datetime.c,1.40,1.41 obj_delta.c,1.25,1.26 obj_time.c,1.4,1.5 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv5324 Modified Files: datetime.py obj_date.c obj_datetime.c obj_delta.c obj_time.c Log Message: Reworked hashing to use __getstate__ instead of building tuples all the time. This should be much faster for the C implementation, since __getstate__ there just does a memcpy of the guts (for date, time, and datetime objects). Index: datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.py,v retrieving revision 1.83 retrieving revision 1.84 diff -C2 -d -r1.83 -r1.84 *** datetime.py 8 Dec 2002 19:02:29 -0000 1.83 --- datetime.py 9 Dec 2002 02:20:34 -0000 1.84 *************** *** 462,466 **** def __hash__(self): ! return hash((self.__days, self.__seconds, self.__microseconds)) def __nonzero__(self): --- 462,466 ---- def __hash__(self): ! return hash(self.__getstate__()) def __nonzero__(self): *************** *** 602,606 **** def __hash__(self): "Hash." ! return hash((self.__year, self.__month, self.__day)) # Formatting methods --- 602,606 ---- def __hash__(self): "Hash." ! return hash(self.__getstate__()) # Formatting methods *************** *** 778,783 **** def __hash__(self): """Hash.""" ! return hash((self.__hour, self.__minute, self.__second, ! self.__microsecond)) # Conversions to string --- 778,782 ---- def __hash__(self): """Hash.""" ! return hash(self.__getstate__()) # Conversions to string *************** *** 934,938 **** """Hash.""" tz = self.__tzinfo ! if tz == None: return super(timetz, self).__hash__() tzoff = tz.utcoffset(self) --- 933,937 ---- """Hash.""" tz = self.__tzinfo ! if tz is None: return super(timetz, self).__hash__() tzoff = tz.utcoffset(self) *************** *** 942,947 **** # Unfortunately it is not possible to construct a new timetz object # and use super().__hash__(), since hour may exceed the range of ! # allowed values ! return hash((h, m, self.second, self.microsecond)) # Conversion to string --- 941,949 ---- # Unfortunately it is not possible to construct a new timetz object # and use super().__hash__(), since hour may exceed the range of ! # allowed values. ! if 0 <= h < 24: ! return hash(timetz(h, m, self.second, self.microsecond)) ! else: ! return hash((h, m, self.second, self.microsecond)) # Conversion to string *************** *** 1200,1206 **** def __hash__(self): "Hash." ! return hash((self.__year, self.__month, self.__day, ! self.__hour, self.__minute, self.__second, ! self.__microsecond)) # Formatting methods --- 1202,1206 ---- def __hash__(self): "Hash." ! return hash(self.__getstate__()) # Formatting methods Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.41 retrieving revision 1.42 diff -C2 -d -r1.41 -r1.42 *** obj_date.c 9 Dec 2002 01:51:11 -0000 1.41 --- obj_date.c 9 Dec 2002 02:20:34 -0000 1.42 *************** *** 378,389 **** } static long date_hash(PyDateTime_Date *self) { if (self->hashcode == -1) { ! PyObject *temp = Py_BuildValue("iii", ! GET_YEAR(self), ! GET_MONTH(self), ! GET_DAY(self)); if (temp != NULL) { self->hashcode = PyObject_Hash(temp); --- 378,388 ---- } + static PyObject *date_getstate(PyDateTime_Date *self); + static long date_hash(PyDateTime_Date *self) { if (self->hashcode == -1) { ! PyObject *temp = date_getstate(self); if (temp != NULL) { self->hashcode = PyObject_Hash(temp); Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.40 retrieving revision 1.41 diff -C2 -d -r1.40 -r1.41 *** obj_datetime.c 9 Dec 2002 01:51:11 -0000 1.40 --- obj_datetime.c 9 Dec 2002 02:20:34 -0000 1.41 *************** *** 494,510 **** } static long datetime_hash(PyDateTime_DateTime *self) { if (self->hashcode == -1) { ! PyObject *temp; ! temp = Py_BuildValue("iiiiiii", ! GET_YEAR(self), ! GET_MONTH(self), ! GET_DAY(self), ! DATE_GET_HOUR(self), ! DATE_GET_MINUTE(self), ! DATE_GET_SECOND(self), ! DATE_GET_MICROSECOND(self)); if (temp != NULL) { self->hashcode = PyObject_Hash(temp); --- 494,504 ---- } + static PyObject *datetime_getstate(PyDateTime_DateTime *self); + static long datetime_hash(PyDateTime_DateTime *self) { if (self->hashcode == -1) { ! PyObject *temp = datetime_getstate(self); if (temp != NULL) { self->hashcode = PyObject_Hash(temp); Index: obj_delta.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_delta.c,v retrieving revision 1.25 retrieving revision 1.26 diff -C2 -d -r1.25 -r1.26 *** obj_delta.c 7 Dec 2002 22:29:45 -0000 1.25 --- obj_delta.c 9 Dec 2002 02:20:34 -0000 1.26 *************** *** 272,283 **** } static long delta_hash(PyDateTime_Delta *self) { if (self->hashcode == -1) { ! PyObject *temp = Py_BuildValue("iii", ! (int)self->days, ! (int)self->seconds, ! (int)self->microseconds); if (temp != NULL) { self->hashcode = PyObject_Hash(temp); --- 272,282 ---- } + static PyObject *delta_getstate(PyDateTime_Delta *self); + static long delta_hash(PyDateTime_Delta *self) { if (self->hashcode == -1) { ! PyObject *temp = delta_getstate(self); if (temp != NULL) { self->hashcode = PyObject_Hash(temp); Index: obj_time.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_time.c,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** obj_time.c 7 Dec 2002 22:29:45 -0000 1.4 --- obj_time.c 9 Dec 2002 02:20:34 -0000 1.5 *************** *** 161,174 **** } static long time_hash(PyDateTime_Time *self) { if (self->hashcode == -1) { ! PyObject *temp; ! temp = Py_BuildValue("iiii", ! TIME_GET_HOUR(self), ! TIME_GET_MINUTE(self), ! TIME_GET_SECOND(self), ! TIME_GET_MICROSECOND(self)); if (temp != NULL) { self->hashcode = PyObject_Hash(temp); --- 161,171 ---- } + static PyObject *time_getstate(PyDateTime_Time *self); + static long time_hash(PyDateTime_Time *self) { if (self->hashcode == -1) { ! PyObject *temp = time_getstate(self); if (temp != NULL) { self->hashcode = PyObject_Hash(temp); From rhettinger@users.sourceforge.net Mon Dec 9 08:56:09 2002 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Mon, 09 Dec 2002 00:56:09 -0800 Subject: [Python-checkins] python/dist/src/Misc NEWS,1.554,1.555 Message-ID: Update of /cvsroot/python/python/dist/src/Misc In directory sc8-pr-cvs1:/tmp/cvs-serv1570 Modified Files: NEWS Log Message: Docs were added about a month ago Index: NEWS =================================================================== RCS file: /cvsroot/python/python/dist/src/Misc/NEWS,v retrieving revision 1.554 retrieving revision 1.555 diff -C2 -d -r1.554 -r1.555 *** NEWS 8 Dec 2002 18:36:24 -0000 1.554 --- NEWS 9 Dec 2002 08:56:06 -0000 1.555 *************** *** 499,504 **** also a class ImmutableSet which is useful when you need sets of sets or when you need to use sets as dict keys, and a class BaseSet which ! is the base class of the two. (This is not documented yet, but ! help(sets) gives a wealth of information.) - Added operator.pow(a,b) which is equivalent to a**b. --- 499,503 ---- also a class ImmutableSet which is useful when you need sets of sets or when you need to use sets as dict keys, and a class BaseSet which ! is the base class of the two. - Added operator.pow(a,b) which is equivalent to a**b. From tim_one@users.sourceforge.net Mon Dec 9 15:42:44 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 09 Dec 2002 07:42:44 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime doc.txt,1.33,1.34 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv23587 Modified Files: doc.txt Log Message: Added issue about timetuple() return type. Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.33 retrieving revision 1.34 diff -C2 -d -r1.33 -r1.34 *** doc.txt 9 Dec 2002 01:40:11 -0000 1.33 --- doc.txt 9 Dec 2002 15:42:41 -0000 1.34 *************** *** 34,37 **** --- 34,40 ---- - The type objects aren't exposed, due to headaches with DLL/.so. + - timetuple() should probably return a struct_time tuple+struct combo, + like time.localtime() returns. Is the type exposed from C? + - LaTeXize the docs. From gward@users.sourceforge.net Mon Dec 9 16:23:11 2002 From: gward@users.sourceforge.net (gward@users.sourceforge.net) Date: Mon, 09 Dec 2002 08:23:11 -0800 Subject: [Python-checkins] python/dist/src/Lib textwrap.py,1.18,1.19 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv26875 Modified Files: textwrap.py Log Message: Fix SF bug #622831 (I think): add unicode_whitespace_trans class attribute, and modify _munge_whitespace() to recognize Unicode strings and use unicode_whitespace_trans to munge them. Still need to add a test to make sure I've really fixed the bug. Index: textwrap.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/textwrap.py,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** textwrap.py 22 Oct 2002 18:31:50 -0000 1.18 --- textwrap.py 9 Dec 2002 16:23:08 -0000 1.19 *************** *** 52,55 **** --- 52,59 ---- ' ' * len(string.whitespace)) + unicode_whitespace_trans = {} + for c in string.whitespace: + unicode_whitespace_trans[ord(unicode(c))] = ord(u' ') + # This funky little regex is just the trick for splitting # text up into word-wrappable chunks. E.g. *************** *** 100,104 **** text = text.expandtabs() if self.replace_whitespace: ! text = text.translate(self.whitespace_trans) return text --- 104,111 ---- text = text.expandtabs() if self.replace_whitespace: ! if isinstance(text, str): ! text = text.translate(self.whitespace_trans) ! elif isinstance(text, unicode): ! text = text.translate(self.unicode_whitespace_trans) return text From gward@users.sourceforge.net Mon Dec 9 16:26:08 2002 From: gward@users.sourceforge.net (gward@users.sourceforge.net) Date: Mon, 09 Dec 2002 08:26:08 -0800 Subject: [Python-checkins] python/dist/src/Lib textwrap.py,1.19,1.20 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv28838 Modified Files: textwrap.py Log Message: Fix SF bug #622849: in _wrap_chunks(), ensure that leading whitespace in the input string is always preserved. Index: textwrap.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/textwrap.py,v retrieving revision 1.19 retrieving revision 1.20 diff -C2 -d -r1.19 -r1.20 *** textwrap.py 9 Dec 2002 16:23:08 -0000 1.19 --- textwrap.py 9 Dec 2002 16:26:05 -0000 1.20 *************** *** 203,208 **** width = self.width - len(indent) ! # First chunk on line is whitespace -- drop it. ! if chunks[0].strip() == '': del chunks[0] --- 203,209 ---- width = self.width - len(indent) ! # First chunk on line is whitespace -- drop it, unless this ! # is the very beginning of the text (ie. no lines started yet). ! if chunks[0].strip() == '' and lines: del chunks[0] From gward@users.sourceforge.net Mon Dec 9 16:27:18 2002 From: gward@users.sourceforge.net (gward@users.sourceforge.net) Date: Mon, 09 Dec 2002 08:27:18 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_textwrap.py,1.16,1.17 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv30201 Modified Files: test_textwrap.py Log Message: Added test_initial_whitespace() to ensure that SF bug #622849 is fixed. Change LongWordTestCase.setUp() -- remove leading whitespace from text string. Comment fix. Index: test_textwrap.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_textwrap.py,v retrieving revision 1.16 retrieving revision 1.17 diff -C2 -d -r1.16 -r1.17 *** test_textwrap.py 31 Oct 2002 16:11:18 -0000 1.16 --- test_textwrap.py 9 Dec 2002 16:27:15 -0000 1.17 *************** *** 225,233 **** self.check_split("--text--.", ["--text--."]) ! # I think David got this wrong in the bug report, but it can't ! # hurt to make sure it stays right! self.check_split("--option", ["--option"]) self.check_split("--option-opt", ["--option-", "opt"]) def test_split(self): # Ensure that the standard _split() method works as advertised --- 225,243 ---- self.check_split("--text--.", ["--text--."]) ! # My initial mis-interpretation of part of the bug report -- ! # These were always handled correctly, but it can't hurt to make ! # sure that they *stay* correct! self.check_split("--option", ["--option"]) self.check_split("--option-opt", ["--option-", "opt"]) + def test_initial_whitespace(self): + # SF bug #622849 reported inconsistent handling of leading + # whitespace; let's test that a bit, shall we? + text = " This is a sentence with leading whitespace." + self.check_wrap(text, 50, + [" This is a sentence with leading whitespace."]) + self.check_wrap(text, 30, + [" This is a sentence with", "leading whitespace."]) + def test_split(self): # Ensure that the standard _split() method works as advertised *************** *** 245,249 **** def setUp(self): self.wrapper = TextWrapper() ! self.text = ''' Did you say "supercalifragilisticexpialidocious?" How *do* you spell that odd word, anyways? --- 255,259 ---- def setUp(self): self.wrapper = TextWrapper() ! self.text = '''\ Did you say "supercalifragilisticexpialidocious?" How *do* you spell that odd word, anyways? From gward@users.sourceforge.net Mon Dec 9 16:32:44 2002 From: gward@users.sourceforge.net (gward@users.sourceforge.net) Date: Mon, 09 Dec 2002 08:32:44 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_textwrap.py,1.17,1.18 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv2200 Modified Files: test_textwrap.py Log Message: Add test_unicode() to ensure that 1) textwrap doesn't crash on unicode input, and 2) unicode input means unicode output. This closes SF bug #622831. Index: test_textwrap.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_textwrap.py,v retrieving revision 1.17 retrieving revision 1.18 diff -C2 -d -r1.17 -r1.18 *** test_textwrap.py 9 Dec 2002 16:27:15 -0000 1.17 --- test_textwrap.py 9 Dec 2002 16:32:41 -0000 1.18 *************** *** 240,243 **** --- 240,255 ---- [" This is a sentence with", "leading whitespace."]) + def test_unicode(self): + # *Very* simple test of wrapping Unicode strings. I'm sure + # there's more to it than this, but let's at least make + # sure textwrap doesn't crash on Unicode input! + text = u"Hello there, how are you today?" + self.check_wrap(text, 50, [u"Hello there, how are you today?"]) + self.check_wrap(text, 20, [u"Hello there, how are", "you today?"]) + olines = self.wrapper.wrap(text) + assert isinstance(olines, list) and isinstance(olines[0], unicode) + otext = self.wrapper.fill(text) + assert isinstance(otext, unicode) + def test_split(self): # Ensure that the standard _split() method works as advertised From tim_one@users.sourceforge.net Mon Dec 9 16:37:21 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 09 Dec 2002 08:37:21 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.c,1.49,1.50 datetime.py,1.84,1.85 doc.txt,1.34,1.35 obj_date.c,1.42,1.43 obj_datetime.c,1.41,1.42 test_both.py,1.55,1.56 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv6208 Modified Files: datetime.c datetime.py doc.txt obj_date.c obj_datetime.c test_both.py Log Message: Closed open issue: timetuple() methods now return a time.struct_time instead of a 9-tuple. Index: datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.c,v retrieving revision 1.49 retrieving revision 1.50 diff -C2 -d -r1.49 -r1.50 *** datetime.c 9 Dec 2002 01:51:10 -0000 1.49 --- datetime.c 9 Dec 2002 16:37:15 -0000 1.50 *************** *** 142,159 **** }; - /* Call time.time() and return its result (a Python float). */ - static PyObject * - time_time() - { - PyObject *result = NULL; - PyObject *time = PyImport_ImportModule("time"); - - if (time != NULL) { - result = PyObject_CallMethod(time, "time", "()"); - Py_DECREF(time); - } - return result; - } - /* year -> 1 if leap year, else 0. */ static int --- 142,145 ---- *************** *** 362,367 **** PyObject *result; - assert(PyTuple_Size(tuple) == 9); - time = PyImport_ImportModule("time"); if (time == NULL) --- 348,351 ---- *************** *** 508,511 **** --- 492,534 ---- assert(*m > 0); assert(*d > 0); + } + + /* Wrap functions from the time module. These aren't directly available + * from C. Perhaps they should be. + */ + + /* Call time.time() and return its result (a Python float). */ + static PyObject * + time_time() + { + PyObject *result = NULL; + PyObject *time = PyImport_ImportModule("time"); + + if (time != NULL) { + result = PyObject_CallMethod(time, "time", "()"); + Py_DECREF(time); + } + return result; + } + + /* Build a time.struct_time. The DST flag is always -1. */ + static PyObject * + build_struct_time(int y, int m, int d, int hh, int mm, int ss) + { + PyObject *time; + PyObject *result = NULL; + + time = PyImport_ImportModule("time"); + if (time != NULL) { + result = PyObject_CallMethod(time, "struct_time", + "((iiiiiiiii))", + y, m, d, + hh, mm, ss, + weekday(y, m, d), + days_before_month(y, m) + d, + -1); + Py_DECREF(time); + } + return result; } Index: datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.py,v retrieving revision 1.84 retrieving revision 1.85 diff -C2 -d -r1.84 -r1.85 *** datetime.py 9 Dec 2002 02:20:34 -0000 1.84 --- datetime.py 9 Dec 2002 16:37:16 -0000 1.85 *************** *** 150,153 **** --- 150,157 ---- _DAYNAMES = [None, "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] + + def _build_struct_time(y, m, d, hh, mm, ss, wday, dnum, dstflag): + return _time.struct_time((y, m, d, hh, mm, ss, wday, dnum, dstflag)) + # This is a start at a struct tm workalike. Goals: # *************** *** 579,584 **** def timetuple(self): "Return local time tuple compatible with time.localtime()." ! return (self.__year, self.__month, self.__day, ! 0, 0, 0, self.weekday(), self._yday(), -1) def toordinal(self): --- 583,589 ---- def timetuple(self): "Return local time tuple compatible with time.localtime()." ! return _build_struct_time(self.__year, self.__month, self.__day, ! 0, 0, 0, ! self.weekday(), self._yday(), -1) def toordinal(self): *************** *** 1175,1181 **** def timetuple(self): "Return local time tuple compatible with time.localtime()." ! return (self.__year, self.__month, self.__day, ! self.__hour, self.__minute, self.__second, ! self.weekday(), self._yday(), -1) def date(self): --- 1180,1186 ---- def timetuple(self): "Return local time tuple compatible with time.localtime()." ! return _build_struct_time(self.__year, self.__month, self.__day, ! self.__hour, self.__minute, self.__second, ! self.weekday(), self._yday(), -1) def date(self): Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.34 retrieving revision 1.35 diff -C2 -d -r1.34 -r1.35 *** doc.txt 9 Dec 2002 15:42:41 -0000 1.34 --- doc.txt 9 Dec 2002 16:37:17 -0000 1.35 *************** *** 34,40 **** - The type objects aren't exposed, due to headaches with DLL/.so. - - timetuple() should probably return a struct_time tuple+struct combo, - like time.localtime() returns. Is the type exposed from C? - - LaTeXize the docs. --- 34,37 ---- Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.42 retrieving revision 1.43 diff -C2 -d -r1.42 -r1.43 *** obj_date.c 9 Dec 2002 02:20:34 -0000 1.42 --- obj_date.c 9 Dec 2002 16:37:17 -0000 1.43 *************** *** 303,307 **** if (tuple == NULL) return NULL; - assert(PyTuple_Size(tuple) == 9); result = format_strftime(format, tuple); Py_DECREF(tuple); --- 303,306 ---- *************** *** 366,379 **** date_timetuple(PyDateTime_Date *self) { ! const int year = GET_YEAR(self); ! const int month = GET_MONTH(self); ! const int day = GET_DAY(self); ! ! return Py_BuildValue("iiiiiiiii", ! year, month, day, ! 0, 0, 0, ! weekday(year, month, day), ! days_before_month(year, month) + day, ! -1); } --- 365,372 ---- date_timetuple(PyDateTime_Date *self) { ! return build_struct_time(GET_YEAR(self), ! GET_MONTH(self), ! GET_DAY(self), ! 0, 0, 0); } Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.41 retrieving revision 1.42 diff -C2 -d -r1.41 -r1.42 *** obj_datetime.c 9 Dec 2002 02:20:34 -0000 1.41 --- obj_datetime.c 9 Dec 2002 16:37:17 -0000 1.42 *************** *** 512,527 **** datetime_timetuple(PyDateTime_DateTime *self) { ! const int year = GET_YEAR(self); ! const int month = GET_MONTH(self); ! const int day = GET_DAY(self); ! ! return Py_BuildValue("iiiiiiiii", ! year, month, day, ! DATE_GET_HOUR(self), ! DATE_GET_MINUTE(self), ! DATE_GET_SECOND(self), ! weekday(year, month, day), ! days_before_month(year, month) + day, ! -1); } --- 512,521 ---- datetime_timetuple(PyDateTime_DateTime *self) { ! return build_struct_time(GET_YEAR(self), ! GET_MONTH(self), ! GET_DAY(self), ! DATE_GET_HOUR(self), ! DATE_GET_MINUTE(self), ! DATE_GET_SECOND(self)); } Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.55 retrieving revision 1.56 diff -C2 -d -r1.55 -r1.56 *** test_both.py 8 Dec 2002 19:21:32 -0000 1.55 --- test_both.py 9 Dec 2002 16:37:18 -0000 1.56 *************** *** 726,729 **** --- 726,738 ---- t = d.timetuple() self.assertEqual(t, (1956, 3, 1+i, 0, 0, 0, (3+i)%7, 61+i, -1)) + self.assertEqual(t.tm_year, 1956) + self.assertEqual(t.tm_mon, 3) + self.assertEqual(t.tm_mday, 1+i) + self.assertEqual(t.tm_hour, 0) + self.assertEqual(t.tm_min, 0) + self.assertEqual(t.tm_sec, 0) + self.assertEqual(t.tm_wday, (3+i)%7) + self.assertEqual(t.tm_yday, 61+i) + self.assertEqual(t.tm_isdst, -1) def test_pickling(self): *************** *** 1119,1122 **** --- 1128,1142 ---- t.toordinal() - date(t.year, 1, 1).toordinal() + 1, -1)) + tt = t.timetuple() + self.assertEqual(tt.tm_year, t.year) + self.assertEqual(tt.tm_mon, t.month) + self.assertEqual(tt.tm_mday, t.day) + self.assertEqual(tt.tm_hour, t.hour) + self.assertEqual(tt.tm_min, t.minute) + self.assertEqual(tt.tm_sec, t.second) + self.assertEqual(tt.tm_wday, t.weekday()) + self.assertEqual(tt.tm_yday, t.toordinal() - + date(t.year, 1, 1).toordinal() + 1) + self.assertEqual(tt.tm_isdst, -1) def test_more_strftime(self): From tim_one@users.sourceforge.net Mon Dec 9 17:42:04 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 09 Dec 2002 09:42:04 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime doc.txt,1.35,1.36 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv18364 Modified Files: doc.txt Log Message: Updated OPEN/TODO list after triage review w/ Guido, and moved some to a new CLOSED list (there were closed w/o action). Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.35 retrieving revision 1.36 diff -C2 -d -r1.35 -r1.36 *** doc.txt 9 Dec 2002 16:37:17 -0000 1.35 --- doc.txt 9 Dec 2002 17:42:02 -0000 1.36 *************** *** 5,13 **** - timetz needs a C implementation. - - Behavior in Boolean contexts. Currently time(0) and timedelta(0) act - as false, everything else acts true. Is this desired? timedelta(0) - seems reasonable since it's very number-like, but time(0) acting false - bothers me (midnight isn't especially more zero-like than noon). - - What should str() do? It generally acts like a synonym for isoformat() now. But --- 5,8 ---- *************** *** 20,23 **** --- 15,21 ---- implementation has (overridden) "pretty __str__" according to one person's idea of "pretty", for a couple types. Rat hole. + Guido sez: chop ".000000" when microseconds are 0, and that's it. + Tim sez: and having a fixed-size string when they are will make + life easier for people implementing their own ideas of "pretty". - The METH_CLASS bug affects about a dozen functions here. They'll need *************** *** 25,36 **** be fixed. - - pickles still "feel too big". - - Subclass relationships. Currently datetime is a subclass of date. I like this in practice, and think it's theoretically sound too. Should this be blessed? I expect the same questions to pop up for timetz wrt time, and datetimetz wrt datetime. ! ! - The type objects aren't exposed, due to headaches with DLL/.so. - LaTeXize the docs. --- 23,32 ---- be fixed. - Subclass relationships. Currently datetime is a subclass of date. I like this in practice, and think it's theoretically sound too. Should this be blessed? I expect the same questions to pop up for timetz wrt time, and datetimetz wrt datetime. ! Guido sez subclassing is fine. Add docs about the subclass ! relationships. - LaTeXize the docs. *************** *** 38,45 **** - Move from sandbox to mainline. - Every function involving a timestamp inherits platform C limitations on year range, on resolution, and on precision. If we were to invent our own timestamp format, an IEEE double doesn't have enough bits to ! cover 9999 years to microsecond resolution. --- 34,56 ---- - Move from sandbox to mainline. + + CLOSED + ====== + - pickles still "feel too big". But this is a general issue w/ new-style + classes. + + - The type objects aren't exposed at the C level, due to headaches with + DLL/.so. We're going to ignore this; if you need to construct, e.g., + a datetime object from C, the constructors can still be gotten via + importing the datetime module and calling the appropriate method. + - Every function involving a timestamp inherits platform C limitations on year range, on resolution, and on precision. If we were to invent our own timestamp format, an IEEE double doesn't have enough bits to ! cover 9999 years to microsecond resolution. Tough. The only methods ! in this module that *produce* timestamps (as opposed to consuming them) ! are in datetimetz, and people will have to live with that limitation. ! Other methods are timestamp consumers, and suffer platform limitations ! no matter what we do here. *************** *** 657,661 **** PyDateTime_GET_DAY(o) ! Ror datetime and date instances: PyDateTime_DATE_GET_HOUR(o) PyDateTime_DATE_GET_MINUTE(o) --- 668,672 ---- PyDateTime_GET_DAY(o) ! For datetime and date instances: PyDateTime_DATE_GET_HOUR(o) PyDateTime_DATE_GET_MINUTE(o) From tim_one@users.sourceforge.net Mon Dec 9 18:56:12 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 09 Dec 2002 10:56:12 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.py,1.85,1.86 doc.txt,1.36,1.37 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv26243 Modified Files: datetime.py doc.txt Log Message: str issue: record that isoformat() should also skip 0 microseconds. Index: datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.py,v retrieving revision 1.85 retrieving revision 1.86 diff -C2 -d -r1.85 -r1.86 *** datetime.py 9 Dec 2002 16:37:16 -0000 1.85 --- datetime.py 9 Dec 2002 18:56:10 -0000 1.86 *************** *** 566,570 **** def __str__(self): ! "Convert to pretty string, for str()." return self.isoformat() --- 566,570 ---- def __str__(self): ! "Convert to string, for str()." return self.isoformat() Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.36 retrieving revision 1.37 diff -C2 -d -r1.36 -r1.37 *** doc.txt 9 Dec 2002 17:42:02 -0000 1.36 --- doc.txt 9 Dec 2002 18:56:10 -0000 1.37 *************** *** 18,21 **** --- 18,23 ---- Tim sez: and having a fixed-size string when they are will make life easier for people implementing their own ideas of "pretty". + Later: isoformat() should also elide trailing microsecond when it's + 0. - The METH_CLASS bug affects about a dozen functions here. They'll need From tim_one@users.sourceforge.net Mon Dec 9 19:01:36 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 09 Dec 2002 11:01:36 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.py,1.86,1.87 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv31370 Modified Files: datetime.py Log Message: Make str() a synonym for isoformat() (except for datetime, where it's like isoformat(' ')). The isoformat()s will be changed next to elide trailing microseconds when they're all zeroes. Index: datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.py,v retrieving revision 1.86 retrieving revision 1.87 diff -C2 -d -r1.86 -r1.87 *** datetime.py 9 Dec 2002 18:56:10 -0000 1.86 --- datetime.py 9 Dec 2002 19:01:33 -0000 1.87 *************** *** 564,571 **** self.__month, self.__day) ! def __str__(self): ! "Convert to string, for str()." ! return self.isoformat() # Read-only field accessors --- 564,592 ---- self.__month, self.__day) + # XXX These shouldn't depend on time.localtime(), because that + # clips the usable dates to [1970 .. 2038). At least ctime() is + # easily done without using strftime() -- that's better too because + # strftime("%c", ...) is locale specific. ! def ctime(self): ! "Format a la ctime()." ! return tmxxx(self.__year, self.__month, self.__day).ctime() ! ! def strftime(self, fmt): ! "Format using strftime()." ! return _time.strftime(fmt, self.timetuple()) ! ! def isoformat(self): ! """Return the date formatted according to ISO. ! ! This is 'YYYY-MM-DD'. ! ! References: ! - http://www.w3.org/TR/NOTE-datetime ! - http://www.cl.cam.ac.uk/~mgk25/iso-time.html ! """ ! return "%04d-%02d-%02d" % (self.__year, self.__month, self.__day) ! ! __str__ = isoformat # Read-only field accessors *************** *** 609,627 **** return hash(self.__getstate__()) - # Formatting methods - - # XXX These shouldn't depend on time.localtime(), because that - # clips the usable dates to [1970 .. 2038). At least ctime() is - # easily done without using strftime() -- that's better too because - # strftime("%c", ...) is locale specific. - - def ctime(self): - "Format a la ctime()." - return tmxxx(self.__year, self.__month, self.__day).ctime() - - def strftime(self, fmt): - "Format using strftime()." - return _time.strftime(fmt, self.timetuple()) - # Computations --- 630,633 ---- *************** *** 693,707 **** return year, week+1, day+1 - def isoformat(self): - """Return the date formatted according to ISO. - - This is 'YYYY-MM-DD'. - - References: - - http://www.w3.org/TR/NOTE-datetime - - http://www.cl.cam.ac.uk/~mgk25/iso-time.html - """ - return "%04d-%02d-%02d" % (self.__year, self.__month, self.__day) - # Pickle support. --- 699,702 ---- *************** *** 807,830 **** self.__microsecond) - # XXX All other types in this module that define isoformat make __str__ - # XXX a synonym, so for now I'm overriding this "pretty string" oddball - # XXX to do likewise. The last thing I need right now is to spend days - # XXX arguing about what "pretty" means in 6 distinct types <0.5 wink>. - def __str__(self): - """Convert to pretty string, for str().""" - pretty = "%d:%02d:%02d.%06d" % ( - self.__hour, self.__minute, self.__second, - self.__microsecond) - # trim microseconds: hh:mm:ss.xxx000 -> hh:mm:ss.xxx - while pretty.endswith('0'): - pretty = pretty[:-1] - # trim microseconds: hh:mm:ss.000000 -> hh:mm:ss - if pretty.endswith('.'): - pretty = pretty[:-1] - # trim seconds: hh:mm:00 -> hh:mm - if pretty.endswith(':00'): - pretty = pretty[:-3] - return pretty - __str__ = isoformat --- 802,805 ---- *************** *** 985,996 **** return s - # XXX As for time, I'm making __str__ a synonym for isoformat for now. - def __str__(self): - """Convert to pretty string, for str().""" - s = super(timetz, self).__str__() - tz = self._tzstr() - if tz: s = "%s %s" % (s, tz) - return s - __str__ = isoformat --- 960,963 ---- *************** *** 1166,1170 **** def __str__(self): ! "Convert to pretty string, for str()." return self.isoformat(sep=' ') --- 1133,1137 ---- def __str__(self): ! "Convert to string, for str()." return self.isoformat(sep=' ') From tim_one@users.sourceforge.net Mon Dec 9 19:50:37 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 09 Dec 2002 11:50:37 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.c,1.50,1.51 datetime.py,1.87,1.88 doc.txt,1.37,1.38 obj_date.c,1.43,1.44 obj_datetime.c,1.42,1.43 obj_time.c,1.5,1.6 test_both.py,1.56,1.57 test_datetime.py,1.58,1.59 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv19070 Modified Files: datetime.c datetime.py doc.txt obj_date.c obj_datetime.c obj_time.c test_both.py test_datetime.py Log Message: All isoformat() and __str__() methods for types with a time field: leave off the trailing .000000 if self.microsecond is 0. Make thing.__str__() generally equivalent to thing.isoformat(), except forcing a blank separator for types with both date and time parts. datetimetz.isoformat (Python implementation) set the default separator to ' '; changed it to 'T' for consistency with datetime.isoformat. Index: datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.c,v retrieving revision 1.50 retrieving revision 1.51 diff -C2 -d -r1.50 -r1.51 *** datetime.c 9 Dec 2002 16:37:15 -0000 1.50 --- datetime.c 9 Dec 2002 19:50:33 -0000 1.51 *************** *** 370,379 **** isoformat_time(PyDateTime_DateTime *dt, char buffer[], int bufflen) { PyOS_snprintf(buffer, bufflen, ! "%02d:%02d:%02d.%06d", DATE_GET_HOUR(dt), DATE_GET_MINUTE(dt), ! DATE_GET_SECOND(dt), ! DATE_GET_MICROSECOND(dt)); } --- 370,383 ---- isoformat_time(PyDateTime_DateTime *dt, char buffer[], int bufflen) { + int us = DATE_GET_MICROSECOND(dt); + PyOS_snprintf(buffer, bufflen, ! "%02d:%02d:%02d", DATE_GET_HOUR(dt), DATE_GET_MINUTE(dt), ! DATE_GET_SECOND(dt)); ! if (us) ! PyOS_snprintf(buffer + 8, bufflen - 8, ! ".%06d", DATE_GET_MICROSECOND(dt)); } Index: datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.py,v retrieving revision 1.87 retrieving revision 1.88 diff -C2 -d -r1.87 -r1.88 *** datetime.py 9 Dec 2002 19:01:33 -0000 1.87 --- datetime.py 9 Dec 2002 19:50:33 -0000 1.88 *************** *** 154,157 **** --- 154,164 ---- return _time.struct_time((y, m, d, hh, mm, ss, wday, dnum, dstflag)) + def _format_time(hh, mm, ss, us): + # Skip traling microseconds when us==0. + result = "%02d:%02d:%02d" % (hh, mm, ss) + if us: + result += ".%06d" % us + return result + # This is a start at a struct tm workalike. Goals: # *************** *** 796,804 **** """Return the time formatted according to ISO. ! This is 'HH:MM:SS.mmmmmm'. """ ! return "%02d:%02d:%02d.%06d" % ( ! self.__hour, self.__minute, self.__second, ! self.__microsecond) __str__ = isoformat --- 803,810 ---- """Return the time formatted according to ISO. ! This is 'HH:MM:SS.mmmmmm', or 'HH:MM:SS' if self.microsecond == 0. """ ! return _format_time(self.__hour, self.__minute, self.__second, ! self.__microsecond) __str__ = isoformat *************** *** 953,957 **** """Return the time formatted according to ISO. ! This is 'HH:MM:SS.mmmmmm+zz:zz'. """ s = super(timetz, self).isoformat() --- 959,964 ---- """Return the time formatted according to ISO. ! This is 'HH:MM:SS.mmmmmm+zz:zz', or 'HH:MM:SS+zz:zz' if ! self.microsecond == 0. """ s = super(timetz, self).isoformat() *************** *** 1121,1125 **** combine = classmethod(combine) ! # Conversions to string def __repr__(self): --- 1128,1132 ---- combine = classmethod(combine) ! # Conversions to string. def __repr__(self): *************** *** 1239,1252 **** """Return the time formatted according to ISO. ! This is 'YYYY-MM-DD HH:MM:SS.mmmmmm'. Optional argument sep specifies the separator between date and time, default 'T'. """ ! return "%04d-%02d-%02d%c%02d:%02d:%02d.%06d" % ( ! self.__year, self.__month, self.__day, ! sep, ! self.__hour, self.__minute, self.__second, ! self.__microsecond) # Pickle support. --- 1246,1259 ---- """Return the time formatted according to ISO. ! This is 'YYYY-MM-DD HH:MM:SS.mmmmmm', or 'YYYY-MM-DD HH:MM:SS' if ! self.microsecond == 0. Optional argument sep specifies the separator between date and time, default 'T'. """ ! return ("%04d-%02d-%02d%c" % (self.__year, self.__month, self.__day, ! sep) + ! _format_time(self.__hour, self.__minute, self.__second, ! self.__microsecond)) # Pickle support. *************** *** 1329,1333 **** self.__tzinfo) ! def isoformat(self, sep=' '): s = super(datetimetz, self).isoformat(sep) if self.__tzinfo is not None: --- 1336,1340 ---- self.__tzinfo) ! def isoformat(self, sep='T'): s = super(datetimetz, self).isoformat(sep) if self.__tzinfo is not None: Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.37 retrieving revision 1.38 diff -C2 -d -r1.37 -r1.38 *** doc.txt 9 Dec 2002 18:56:10 -0000 1.37 --- doc.txt 9 Dec 2002 19:50:33 -0000 1.38 *************** *** 5,24 **** - timetz needs a C implementation. - - What should str() do? It generally acts like a synonym for isoformat() - now. But - - >>> print time(2) - 02:00:00.000000 - >>> - - is arguably better as '2:00:00' or even '2:00'. The Python - implementation has (overridden) "pretty __str__" according to one - person's idea of "pretty", for a couple types. Rat hole. - Guido sez: chop ".000000" when microseconds are 0, and that's it. - Tim sez: and having a fixed-size string when they are will make - life easier for people implementing their own ideas of "pretty". - Later: isoformat() should also elide trailing microsecond when it's - 0. - - The METH_CLASS bug affects about a dozen functions here. They'll need to be recoded in minor ways when the bug gets fixed. The bug needs to --- 5,8 ---- *************** *** 39,42 **** --- 23,43 ---- CLOSED ====== + - What should str() do? It generally acts like a synonym for isoformat() + now. But + + >>> print time(2) + 02:00:00.000000 + >>> + + is arguably better as '2:00:00' or even '2:00'. The Python + implementation has (overridden) "pretty __str__" according to one + person's idea of "pretty", for a couple types. Rat hole. + Guido sez: chop ".000000" when microseconds are 0, and that's it. + Tim sez: and having a fixed-size string when they are will make + life easier for people implementing their own ideas of "pretty". + Later: isoformat() should also elide trailing microsecond when it's + 0. + Done. + - pickles still "feel too big". But this is a general issue w/ new-style classes. *************** *** 368,372 **** 'YYYY-MM-DD'. For example, date(2002, 12, 4).isoformat() == '2002-12-04'. ! str(d) is equivalent to d.isoformat(). - ctime() --- 369,375 ---- 'YYYY-MM-DD'. For example, date(2002, 12, 4).isoformat() == '2002-12-04'. ! ! - __str__() ! For a date d, str(d) is equivalent to d.isoformat(). - ctime() *************** *** 555,563 **** Return a string representing the date and time in ISO 8601 format, YYYY-MM-DDTHH:MM:SS.mmmmmm Optional argument sep (default 'T') is a one-character separator, placed between the date and time portions of the result. For example, datetime(2002, 12, 4, 1, 2, 3, 4).isoformat(' ') == '2002-12-04 01:02:03.000004' ! str(d) is equivalent to d.isoformat(' '). - ctime() --- 558,570 ---- Return a string representing the date and time in ISO 8601 format, YYYY-MM-DDTHH:MM:SS.mmmmmm + or, if self.microsecond is 0, + YYYY-MM-DDTHH:MM:SS Optional argument sep (default 'T') is a one-character separator, placed between the date and time portions of the result. For example, datetime(2002, 12, 4, 1, 2, 3, 4).isoformat(' ') == '2002-12-04 01:02:03.000004' ! ! - __str__() ! For a datetime d, str(d) is equivalent to d.isoformat(' '). - ctime() *************** *** 638,642 **** Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm ! str(t) is equivalent to t.isoformat(). - strftime(format) --- 645,653 ---- Return a string representing the time in ISO 8601 format, HH:MM:SS.mmmmmm ! or, if self.microsecond is 0 ! HH:MM:SS ! ! - __str__() ! For a time t, str(t) is equivalent to t.isoformat(). - strftime(format) Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.43 retrieving revision 1.44 diff -C2 -d -r1.43 -r1.44 *** obj_date.c 9 Dec 2002 16:37:17 -0000 1.43 --- obj_date.c 9 Dec 2002 19:50:33 -0000 1.44 *************** *** 276,288 **** static PyObject * ! date_str(PyDateTime_Date *self) { char buffer[128]; isoformat_date(self, buffer, sizeof(buffer)); - return PyString_FromString(buffer); } static PyObject * date_ctime(PyDateTime_Date *self) --- 276,295 ---- static PyObject * ! date_isoformat(PyDateTime_Date *self) { char buffer[128]; isoformat_date(self, buffer, sizeof(buffer)); return PyString_FromString(buffer); } + /* str() calls the appropriate isofomat() method. */ + static PyObject * + date_str(PyDateTime_Date *self) + { + return PyObject_CallMethod((PyObject *)self, "isoformat", "()"); + } + + static PyObject * date_ctime(PyDateTime_Date *self) *************** *** 505,509 **** "weekday.")}, ! {"isoformat", (PyCFunction)date_str, METH_NOARGS, PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")}, --- 512,516 ---- "weekday.")}, ! {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS, PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")}, Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.42 retrieving revision 1.43 diff -C2 -d -r1.42 -r1.43 *** obj_datetime.c 9 Dec 2002 16:37:17 -0000 1.42 --- obj_datetime.c 9 Dec 2002 19:50:33 -0000 1.43 *************** *** 431,451 **** static PyObject * - datetime_isoformat_helper(PyDateTime_DateTime *self, char sep) - { - char buffer[100]; - char *cp; - - cp = isoformat_date((PyDateTime_Date *)self, buffer, sizeof(buffer)); - assert(cp != NULL); - *cp++ = sep; - isoformat_time(self, cp, sizeof(buffer) - (cp - buffer)); - - return PyString_FromString(buffer); - } - - static PyObject * datetime_str(PyDateTime_DateTime *self) { ! return datetime_isoformat_helper(self, ' '); } --- 431,437 ---- static PyObject * datetime_str(PyDateTime_DateTime *self) { ! return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " "); } *************** *** 456,464 **** char sep = 'T'; static char *keywords[] = {"sep", NULL}; if (!PyArg_ParseTupleAndKeywords(args, kw, "|c:isoformat", keywords, &sep)) return NULL; ! return datetime_isoformat_helper(self, sep); } --- 442,456 ---- char sep = 'T'; static char *keywords[] = {"sep", NULL}; + char buffer[100]; + char *cp; if (!PyArg_ParseTupleAndKeywords(args, kw, "|c:isoformat", keywords, &sep)) return NULL; ! cp = isoformat_date((PyDateTime_Date *)self, buffer, sizeof(buffer)); ! assert(cp != NULL); ! *cp++ = sep; ! isoformat_time(self, cp, sizeof(buffer) - (cp - buffer)); ! return PyString_FromString(buffer); } *************** *** 652,656 **** {"isoformat", (PyCFunction)datetime_isoformat, METH_KEYWORDS, PyDoc_STR("[sep] -> string in ISO 8601 format, " ! "YYYY-MM-DDTHH:MM:SS.mmmmmm.\n\n" "sep is used to separate the year from the time, and " "defaults\n" --- 644,648 ---- {"isoformat", (PyCFunction)datetime_isoformat, METH_KEYWORDS, PyDoc_STR("[sep] -> string in ISO 8601 format, " ! "YYYY-MM-DDTHH:MM:SS[.mmmmmm].\n\n" "sep is used to separate the year from the time, and " "defaults\n" Index: obj_time.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_time.c,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** obj_time.c 9 Dec 2002 02:20:34 -0000 1.5 --- obj_time.c 9 Dec 2002 19:50:33 -0000 1.6 *************** *** 103,107 **** } ! /* time_isoformat is also tp_str */ static PyObject * time_isoformat(PyDateTime_Time *self) --- 103,112 ---- } ! static PyObject * ! time_str(PyDateTime_Time *self) ! { ! return PyObject_CallMethod((PyObject *)self, "isoformat", "()"); ! } ! static PyObject * time_isoformat(PyDateTime_Time *self) *************** *** 257,261 **** static PyMethodDef time_methods[] = { {"isoformat", (PyCFunction)time_isoformat, METH_KEYWORDS, ! PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS.mmmmmm.")}, {"strftime", (PyCFunction)time_strftime, METH_O, --- 262,266 ---- static PyMethodDef time_methods[] = { {"isoformat", (PyCFunction)time_isoformat, METH_KEYWORDS, ! PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm].")}, {"strftime", (PyCFunction)time_strftime, METH_O, *************** *** 305,309 **** (hashfunc)time_hash, /* tp_hash */ 0, /* tp_call */ ! (reprfunc)time_isoformat, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ --- 310,314 ---- (hashfunc)time_hash, /* tp_hash */ 0, /* tp_call */ ! (reprfunc)time_str, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.56 retrieving revision 1.57 diff -C2 -d -r1.56 -r1.57 *** test_both.py 9 Dec 2002 16:37:18 -0000 1.56 --- test_both.py 9 Dec 2002 19:50:33 -0000 1.57 *************** *** 858,861 **** --- 858,868 ---- self.assertEqual(str(t), "0002-03-02 04:05:01.000123") + t = self.theclass(2, 3, 2) + self.assertEqual(t.isoformat(), "0002-03-02T00:00:00") + self.assertEqual(t.isoformat('T'), "0002-03-02T00:00:00") + self.assertEqual(t.isoformat(' '), "0002-03-02 00:00:00") + # str is ISO format with the separator forced to a blank. + self.assertEqual(str(t), "0002-03-02 00:00:00") + def test_more_ctime(self): # Test fields that TestDate doesn't touch. *************** *** 1300,1303 **** --- 1307,1339 ---- t = self.theclass(4, 5, 1, 123) self.assertEqual(t.isoformat(), "04:05:01.000123") + self.assertEqual(t.isoformat(), str(t)) + + t = self.theclass() + self.assertEqual(t.isoformat(), "00:00:00") + self.assertEqual(t.isoformat(), str(t)) + + t = self.theclass(microsecond=1) + self.assertEqual(t.isoformat(), "00:00:00.000001") + self.assertEqual(t.isoformat(), str(t)) + + t = self.theclass(microsecond=10) + self.assertEqual(t.isoformat(), "00:00:00.000010") + self.assertEqual(t.isoformat(), str(t)) + + t = self.theclass(microsecond=100) + self.assertEqual(t.isoformat(), "00:00:00.000100") + self.assertEqual(t.isoformat(), str(t)) + + t = self.theclass(microsecond=1000) + self.assertEqual(t.isoformat(), "00:00:00.001000") + self.assertEqual(t.isoformat(), str(t)) + + t = self.theclass(microsecond=10000) + self.assertEqual(t.isoformat(), "00:00:00.010000") + self.assertEqual(t.isoformat(), str(t)) + + t = self.theclass(microsecond=100000) + self.assertEqual(t.isoformat(), "00:00:00.100000") + self.assertEqual(t.isoformat(), str(t)) def test_strftime(self): *************** *** 1309,1314 **** self.assertEqual(str(self.theclass(10, 2, 3, 4000)), "10:02:03.004000") self.assertEqual(str(self.theclass(0, 2, 3, 400000)), "00:02:03.400000") ! self.assertEqual(str(self.theclass(12, 2, 3, 0)), "12:02:03.000000") ! self.assertEqual(str(self.theclass(23, 15, 0, 0)), "23:15:00.000000") def test_repr(self): --- 1345,1350 ---- self.assertEqual(str(self.theclass(10, 2, 3, 4000)), "10:02:03.004000") self.assertEqual(str(self.theclass(0, 2, 3, 400000)), "00:02:03.400000") ! self.assertEqual(str(self.theclass(12, 2, 3, 0)), "12:02:03") ! self.assertEqual(str(self.theclass(23, 15, 0, 0)), "23:15:00") def test_repr(self): Index: test_datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_datetime.py,v retrieving revision 1.58 retrieving revision 1.59 diff -C2 -d -r1.58 -r1.59 *** test_datetime.py 7 Dec 2002 21:06:39 -0000 1.58 --- test_datetime.py 9 Dec 2002 19:50:34 -0000 1.59 *************** *** 42,54 **** self.assertEqual(t1, t3) self.assertEqual(t2, t3) ! self.assertEqual(str(t1), "07:47:00.000000-05:00") ! self.assertEqual(str(t2), "12:47:00.000000+00:00") ! self.assertEqual(str(t3), "13:47:00.000000+01:00") self.assertEqual(repr(t1), "timetz(7, 47, tzinfo=est)") self.assertEqual(repr(t2), "timetz(12, 47, tzinfo=utc)") self.assertEqual(repr(t3), "timetz(13, 47, tzinfo=met)") ! self.assertEqual(t1.isoformat(), "07:47:00.000000-05:00") ! self.assertEqual(t2.isoformat(), "12:47:00.000000+00:00") ! self.assertEqual(t3.isoformat(), "13:47:00.000000+01:00") self.assertEqual(t1.strftime("%H:%M:%S %Z %z"), "07:47:00 EST -0500") self.assertEqual(t2.strftime("%H:%M:%S %Z %z"), "12:47:00 UTC +0000") --- 42,54 ---- self.assertEqual(t1, t3) self.assertEqual(t2, t3) ! self.assertEqual(str(t1), "07:47:00-05:00") ! self.assertEqual(str(t2), "12:47:00+00:00") ! self.assertEqual(str(t3), "13:47:00+01:00") self.assertEqual(repr(t1), "timetz(7, 47, tzinfo=est)") self.assertEqual(repr(t2), "timetz(12, 47, tzinfo=utc)") self.assertEqual(repr(t3), "timetz(13, 47, tzinfo=met)") ! self.assertEqual(t1.isoformat(), "07:47:00-05:00") ! self.assertEqual(t2.isoformat(), "12:47:00+00:00") ! self.assertEqual(t3.isoformat(), "13:47:00+01:00") self.assertEqual(t1.strftime("%H:%M:%S %Z %z"), "07:47:00 EST -0500") self.assertEqual(t2.strftime("%H:%M:%S %Z %z"), "12:47:00 UTC +0000") *************** *** 114,120 **** self.assertEqual(t1, t3) self.assertEqual(t2, t3) ! self.assertEqual(str(t1), "2002-03-19 07:47:00.000000-05:00") ! self.assertEqual(str(t2), "2002-03-19 12:47:00.000000+00:00") ! self.assertEqual(str(t3), "2002-03-19 13:47:00.000000+01:00") self.assertEqual(repr(t1), "datetimetz(2002, 3, 19, 7, 47, tzinfo=est)") --- 114,120 ---- self.assertEqual(t1, t3) self.assertEqual(t2, t3) ! self.assertEqual(str(t1), "2002-03-19 07:47:00-05:00") ! self.assertEqual(str(t2), "2002-03-19 12:47:00+00:00") ! self.assertEqual(str(t3), "2002-03-19 13:47:00+01:00") self.assertEqual(repr(t1), "datetimetz(2002, 3, 19, 7, 47, tzinfo=est)") From tim_one@users.sourceforge.net Mon Dec 9 21:37:40 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 09 Dec 2002 13:37:40 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.c,1.51,1.52 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv21208 Modified Files: datetime.c Log Message: isoformat_time(): Simplified some silly new code. Index: datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.c,v retrieving revision 1.51 retrieving revision 1.52 diff -C2 -d -r1.51 -r1.52 *** datetime.c 9 Dec 2002 19:50:33 -0000 1.51 --- datetime.c 9 Dec 2002 21:37:37 -0000 1.52 *************** *** 373,383 **** PyOS_snprintf(buffer, bufflen, ! "%02d:%02d:%02d", DATE_GET_HOUR(dt), DATE_GET_MINUTE(dt), DATE_GET_SECOND(dt)); if (us) ! PyOS_snprintf(buffer + 8, bufflen - 8, ! ".%06d", DATE_GET_MICROSECOND(dt)); } --- 373,382 ---- PyOS_snprintf(buffer, bufflen, ! "%02d:%02d:%02d", /* 8 characters */ DATE_GET_HOUR(dt), DATE_GET_MINUTE(dt), DATE_GET_SECOND(dt)); if (us) ! PyOS_snprintf(buffer + 8, bufflen - 8, ".%06d", us); } From tim_one@users.sourceforge.net Mon Dec 9 22:05:39 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 09 Dec 2002 14:05:39 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.py,1.88,1.89 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv16749 Modified Files: datetime.py Log Message: Fixed typo in comment. Index: datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.py,v retrieving revision 1.88 retrieving revision 1.89 diff -C2 -d -r1.88 -r1.89 *** datetime.py 9 Dec 2002 19:50:33 -0000 1.88 --- datetime.py 9 Dec 2002 22:05:36 -0000 1.89 *************** *** 155,159 **** def _format_time(hh, mm, ss, us): ! # Skip traling microseconds when us==0. result = "%02d:%02d:%02d" % (hh, mm, ss) if us: --- 155,159 ---- def _format_time(hh, mm, ss, us): ! # Skip trailng microseconds when us==0. result = "%02d:%02d:%02d" % (hh, mm, ss) if us: From tim_one@users.sourceforge.net Mon Dec 9 22:10:56 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 09 Dec 2002 14:10:56 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.py,1.89,1.90 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv22685 Modified Files: datetime.py Log Message: Another try at spelling "trailig" correctly. Index: datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.py,v retrieving revision 1.89 retrieving revision 1.90 diff -C2 -d -r1.89 -r1.90 *** datetime.py 9 Dec 2002 22:05:36 -0000 1.89 --- datetime.py 9 Dec 2002 22:10:53 -0000 1.90 *************** *** 155,159 **** def _format_time(hh, mm, ss, us): ! # Skip trailng microseconds when us==0. result = "%02d:%02d:%02d" % (hh, mm, ss) if us: --- 155,159 ---- def _format_time(hh, mm, ss, us): ! # Skip trailing microseconds when us==0. result = "%02d:%02d:%02d" % (hh, mm, ss) if us: From tim_one@users.sourceforge.net Mon Dec 9 22:56:15 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 09 Dec 2002 14:56:15 -0800 Subject: [Python-checkins] python/dist/src/Include descrobject.h,2.11,2.12 Message-ID: Update of /cvsroot/python/python/dist/src/Include In directory sc8-pr-cvs1:/tmp/cvs-serv10366/python/Include Modified Files: descrobject.h Log Message: SF 548651: Fix the METH_CLASS implementation. Most of these patches are from Thomas Heller, with long lines folded by Tim. The change to test_descr.py is from Guido. See the bug report. Not a bugfix candidate -- METH_CLASS is new in 2.3. Index: descrobject.h =================================================================== RCS file: /cvsroot/python/python/dist/src/Include/descrobject.h,v retrieving revision 2.11 retrieving revision 2.12 diff -C2 -d -r2.11 -r2.12 *** descrobject.h 19 Aug 2002 18:45:37 -0000 2.11 --- descrobject.h 9 Dec 2002 22:56:12 -0000 2.12 *************** *** 71,74 **** --- 71,75 ---- PyAPI_FUNC(PyObject *) PyDescr_NewMethod(PyTypeObject *, PyMethodDef *); + PyAPI_FUNC(PyObject *) PyDescr_NewClassMethod(PyTypeObject *, PyMethodDef *); PyAPI_FUNC(PyObject *) PyDescr_NewMember(PyTypeObject *, struct PyMemberDef *); From tim_one@users.sourceforge.net Mon Dec 9 22:56:15 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 09 Dec 2002 14:56:15 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_descr.py,1.168,1.169 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv10366/python/Lib/test Modified Files: test_descr.py Log Message: SF 548651: Fix the METH_CLASS implementation. Most of these patches are from Thomas Heller, with long lines folded by Tim. The change to test_descr.py is from Guido. See the bug report. Not a bugfix candidate -- METH_CLASS is new in 2.3. Index: test_descr.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_descr.py,v retrieving revision 1.168 retrieving revision 1.169 diff -C2 -d -r1.168 -r1.169 *** test_descr.py 27 Nov 2002 16:29:26 -0000 1.168 --- test_descr.py 9 Dec 2002 22:56:13 -0000 1.169 *************** *** 1465,1474 **** d = {'abc': 123} x, a1, d1 = spam.spamlist.classmeth(*a, **d) ! veris(x, None) ! vereq((spam.spamlist,) + a, a1) vereq(d, d1) x, a1, d1 = spam.spamlist().classmeth(*a, **d) ! veris(x, None) ! vereq((spam.spamlist,) + a, a1) vereq(d, d1) --- 1465,1474 ---- d = {'abc': 123} x, a1, d1 = spam.spamlist.classmeth(*a, **d) ! veris(x, spam.spamlist) ! vereq(a, a1) vereq(d, d1) x, a1, d1 = spam.spamlist().classmeth(*a, **d) ! veris(x, spam.spamlist) ! vereq(a, a1) vereq(d, d1) From tim_one@users.sourceforge.net Mon Dec 9 22:56:15 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 09 Dec 2002 14:56:15 -0800 Subject: [Python-checkins] python/dist/src/Objects descrobject.c,2.31,2.32 dictobject.c,2.135,2.136 typeobject.c,2.196,2.197 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv10366/python/Objects Modified Files: descrobject.c dictobject.c typeobject.c Log Message: SF 548651: Fix the METH_CLASS implementation. Most of these patches are from Thomas Heller, with long lines folded by Tim. The change to test_descr.py is from Guido. See the bug report. Not a bugfix candidate -- METH_CLASS is new in 2.3. Index: descrobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/descrobject.c,v retrieving revision 2.31 retrieving revision 2.32 diff -C2 -d -r2.31 -r2.32 *** descrobject.c 31 Aug 2002 15:51:04 -0000 2.31 --- descrobject.c 9 Dec 2002 22:56:13 -0000 2.32 *************** *** 80,83 **** --- 80,90 ---- static PyObject * + classmethod_get(PyMethodDescrObject *descr, PyObject *obj, + PyTypeObject *type) + { + return PyCFunction_New(descr->d_method, (PyObject *)type); + } + + static PyObject * method_get(PyMethodDescrObject *descr, PyObject *obj, PyTypeObject *type) { *************** *** 214,217 **** --- 221,239 ---- static PyObject * + classmethoddescr_call(PyMethodDescrObject *descr, PyObject *args, + PyObject *kwds) + { + PyObject *func, *result; + + func = PyCFunction_New(descr->d_method, (PyObject *)descr->d_type); + if (func == NULL) + return NULL; + + result = PyEval_CallObjectWithKeywords(func, args, kwds); + Py_DECREF(func); + return result; + } + + static PyObject * wrapperdescr_call(PyWrapperDescrObject *descr, PyObject *args, PyObject *kwds) { *************** *** 374,377 **** --- 396,437 ---- }; + static PyTypeObject PyClassMethodDescr_Type = { + PyObject_HEAD_INIT(&PyType_Type) + 0, + "special_method_descriptor", + sizeof(PyMethodDescrObject), + 0, + (destructor)descr_dealloc, /* tp_dealloc */ + 0, /* tp_print */ + 0, /* tp_getattr */ + 0, /* tp_setattr */ + 0, /* tp_compare */ + (reprfunc)method_repr, /* tp_repr */ + 0, /* tp_as_number */ + 0, /* tp_as_sequence */ + 0, /* tp_as_mapping */ + 0, /* tp_hash */ + (ternaryfunc)classmethoddescr_call, /* 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 */ + descr_traverse, /* tp_traverse */ + 0, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + 0, /* tp_methods */ + descr_members, /* tp_members */ + method_getset, /* tp_getset */ + 0, /* tp_base */ + 0, /* tp_dict */ + (descrgetfunc)classmethod_get, /* tp_descr_get */ + 0, /* tp_descr_set */ + }; + static PyTypeObject PyMemberDescr_Type = { PyObject_HEAD_INIT(&PyType_Type) *************** *** 512,515 **** --- 572,587 ---- descr = (PyMethodDescrObject *)descr_new(&PyMethodDescr_Type, + type, method->ml_name); + if (descr != NULL) + descr->d_method = method; + return (PyObject *)descr; + } + + PyObject * + PyDescr_NewClassMethod(PyTypeObject *type, PyMethodDef *method) + { + PyMethodDescrObject *descr; + + descr = (PyMethodDescrObject *)descr_new(&PyClassMethodDescr_Type, type, method->ml_name); if (descr != NULL) Index: dictobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/dictobject.c,v retrieving revision 2.135 retrieving revision 2.136 diff -C2 -d -r2.135 -r2.136 *** dictobject.c 7 Dec 2002 08:10:51 -0000 2.135 --- dictobject.c 9 Dec 2002 22:56:13 -0000 2.136 *************** *** 964,968 **** static PyObject * ! dict_fromkeys(PyObject *mp, PyObject *args) { PyObject *seq; --- 964,968 ---- static PyObject * ! dict_fromkeys(PyObject *cls, PyObject *args) { PyObject *seq; *************** *** 971,978 **** PyObject *key; PyObject *d; - PyObject *cls; int status; ! if (!PyArg_ParseTuple(args, "OO|O:fromkeys", &cls, &seq, &value)) return NULL; --- 971,977 ---- PyObject *key; PyObject *d; int status; ! if (!PyArg_ParseTuple(args, "O|O:fromkeys", &seq, &value)) return NULL; Index: typeobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/typeobject.c,v retrieving revision 2.196 retrieving revision 2.197 diff -C2 -d -r2.196 -r2.197 *** typeobject.c 7 Dec 2002 21:39:16 -0000 2.196 --- typeobject.c 9 Dec 2002 22:56:13 -0000 2.197 *************** *** 2436,2440 **** return -1; } ! descr = create_specialmethod(meth, PyClassMethod_New); } else if (meth->ml_flags & METH_STATIC) { --- 2436,2440 ---- return -1; } ! descr = PyDescr_NewClassMethod(type, meth); } else if (meth->ml_flags & METH_STATIC) { From tim_one@users.sourceforge.net Mon Dec 9 23:16:41 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 09 Dec 2002 15:16:41 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime doc.txt,1.38,1.39 obj_date.c,1.44,1.45 obj_datetime.c,1.43,1.44 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv17929 Modified Files: doc.txt obj_date.c obj_datetime.c Log Message: The METH_CLASS bug has been fixed in Python CVS (thanks to Thomas Heller and Guido!, so fiddled the code here to work again. It's an improvement this way. Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.38 retrieving revision 1.39 diff -C2 -d -r1.38 -r1.39 *** doc.txt 9 Dec 2002 19:50:33 -0000 1.38 --- doc.txt 9 Dec 2002 23:16:38 -0000 1.39 *************** *** 5,12 **** - timetz needs a C implementation. - - The METH_CLASS bug affects about a dozen functions here. They'll need - to be recoded in minor ways when the bug gets fixed. The bug needs to - be fixed. - - Subclass relationships. Currently datetime is a subclass of date. I like this in practice, and think it's theoretically sound too. --- 5,8 ---- *************** *** 23,26 **** --- 19,27 ---- CLOSED ====== + - The METH_CLASS bug affects about a dozen functions here. They'll need + to be recoded in minor ways when the bug gets fixed. The bug needs to + be fixed. + Done. + - What should str() do? It generally acts like a synonym for isoformat() now. But Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.44 retrieving revision 1.45 diff -C2 -d -r1.44 -r1.45 *** obj_date.c 9 Dec 2002 19:50:33 -0000 1.44 --- obj_date.c 9 Dec 2002 23:16:39 -0000 1.45 *************** *** 91,95 **** */ static PyObject * ! date_today(PyObject *self, PyObject *cls) { PyObject *time; --- 91,95 ---- */ static PyObject * ! date_today(PyObject *cls, PyObject *dummy) { PyObject *time; *************** *** 113,123 **** /* Return new date from given timestamp (Python timestamp -- a double). */ static PyObject * ! date_fromtimestamp(PyObject *self, PyObject *args) { - PyObject *cls; double timestamp; PyObject *result = NULL; ! if (PyArg_ParseTuple(args, "Od:fromtimestamp", &cls, ×tamp)) result = date_local_from_time_t(cls, (time_t)timestamp); return result; --- 113,122 ---- /* Return new date from given timestamp (Python timestamp -- a double). */ static PyObject * ! date_fromtimestamp(PyObject *cls, PyObject *args) { double timestamp; PyObject *result = NULL; ! if (PyArg_ParseTuple(args, "d:fromtimestamp", ×tamp)) result = date_local_from_time_t(cls, (time_t)timestamp); return result; *************** *** 128,139 **** */ static PyObject * ! date_fromordinal(PyObject *self, PyObject *args) { PyObject *result = NULL; - PyObject *cls; long ordinal; ! if (PyArg_ParseTuple(args, "Ol:formordinal", &cls, &ordinal)) { long year; long month; --- 127,137 ---- */ static PyObject * ! date_fromordinal(PyObject *cls, PyObject *args) { PyObject *result = NULL; long ordinal; ! if (PyArg_ParseTuple(args, "l:formordinal", &ordinal)) { long year; long month; *************** *** 478,486 **** static PyMethodDef date_methods[] = { /* Class methods: */ - /* XXX METH_CLASS is implemented incorrectly: - * XXX http://www.python.org/sf/548651 - * XXX The signatures of these methods will need to change (for - * XXX the better) when that's fixed. - */ {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS | METH_CLASS, --- 476,479 ---- *************** *** 493,497 **** "ordinal.")}, ! {"today", (PyCFunction)date_today, METH_O | METH_CLASS, PyDoc_STR("Current date or datetime: same as " "self.__class__.fromtimestamp(time.time()).")}, --- 486,490 ---- "ordinal.")}, ! {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS, PyDoc_STR("Current date or datetime: same as " "self.__class__.fromtimestamp(time.time()).")}, Index: obj_datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_datetime.c,v retrieving revision 1.43 retrieving revision 1.44 diff -C2 -d -r1.43 -r1.44 *** obj_datetime.c 9 Dec 2002 19:50:33 -0000 1.43 --- obj_datetime.c 9 Dec 2002 23:16:39 -0000 1.44 *************** *** 188,198 **** /* Return new local datetime from timestamp (Python timestamp -- a double). */ static PyObject * ! datetime_fromtimestamp(PyObject *self, PyObject *args) { - PyObject *cls; double timestamp; PyObject *result = NULL; ! if (PyArg_ParseTuple(args, "Od:fromtimestamp", &cls, ×tamp)) result = datetime_from_timestamp(cls, localtime, timestamp); return result; --- 188,197 ---- /* Return new local datetime from timestamp (Python timestamp -- a double). */ static PyObject * ! datetime_fromtimestamp(PyObject *cls, PyObject *args) { double timestamp; PyObject *result = NULL; ! if (PyArg_ParseTuple(args, "d:fromtimestamp", ×tamp)) result = datetime_from_timestamp(cls, localtime, timestamp); return result; *************** *** 201,211 **** /* Return new UTC datetime from timestamp (Python timestamp -- a double). */ static PyObject * ! datetime_utcfromtimestamp(PyObject *self, PyObject *args) { - PyObject *cls; double timestamp; PyObject *result = NULL; ! if (PyArg_ParseTuple(args, "Od:utcfromtimestamp", &cls, ×tamp)) result = datetime_from_timestamp(cls, gmtime, timestamp); return result; --- 200,209 ---- /* Return new UTC datetime from timestamp (Python timestamp -- a double). */ static PyObject * ! datetime_utcfromtimestamp(PyObject *cls, PyObject *args) { double timestamp; PyObject *result = NULL; ! if (PyArg_ParseTuple(args, "d:utcfromtimestamp", ×tamp)) result = datetime_from_timestamp(cls, gmtime, timestamp); return result; *************** *** 216,220 **** */ static PyObject * ! datetime_now(PyObject *self, PyObject *cls) { return datetime_best_possible(cls, localtime); --- 214,218 ---- */ static PyObject * ! datetime_now(PyObject *cls, PyObject *dummy) { return datetime_best_possible(cls, localtime); *************** *** 225,229 **** */ static PyObject * ! datetime_utcnow(PyObject *self, PyObject *cls) { return datetime_best_possible(cls, gmtime); --- 223,227 ---- */ static PyObject * ! datetime_utcnow(PyObject *cls, PyObject *dummy) { return datetime_best_possible(cls, gmtime); *************** *** 232,250 **** /* Return new datetime from date and time arguments. */ static PyObject * ! datetime_combine(PyObject *self, PyObject *args, PyObject *kw) { ! /* XXX Ack! The METH_CLASS bug (see below) makes us pass a ! * XXX keyword name for the class argument. Rather than try to ! * XXX work around it, we pass an "impossible" class name. This ! * XXX function will need some reworking when the bug is fixed. ! */ ! static char *keywords[] = {" cls ", "date", "time", NULL}; ! PyObject *cls; PyObject *date; PyObject *time; PyObject *result = NULL; ! if (PyArg_ParseTupleAndKeywords(args, kw, "OO!O!:combine", keywords, ! &cls, &PyDateTime_DateType, &date, &PyDateTime_TimeType, &time)) --- 230,241 ---- /* Return new datetime from date and time arguments. */ static PyObject * ! datetime_combine(PyObject *cls, PyObject *args, PyObject *kw) { ! static char *keywords[] = {"date", "time", NULL}; PyObject *date; PyObject *time; PyObject *result = NULL; ! if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords, &PyDateTime_DateType, &date, &PyDateTime_TimeType, &time)) *************** *** 601,615 **** static PyMethodDef datetime_methods[] = { /* Class methods: */ - /* XXX METH_CLASS is implemented incorrectly: - * XXX http://www.python.org/sf/548651 - * XXX The signatures of these methods will need to change (for - * XXX the better) when that's fixed. - */ {"now", (PyCFunction)datetime_now, ! METH_O | METH_CLASS, PyDoc_STR("Return a new datetime representing local day and time.")}, {"utcnow", (PyCFunction)datetime_utcnow, ! METH_O | METH_CLASS, PyDoc_STR("Return a new datetime representing UTC day and time.")}, --- 592,601 ---- static PyMethodDef datetime_methods[] = { /* Class methods: */ {"now", (PyCFunction)datetime_now, ! METH_NOARGS | METH_CLASS, PyDoc_STR("Return a new datetime representing local day and time.")}, {"utcnow", (PyCFunction)datetime_utcnow, ! METH_NOARGS | METH_CLASS, PyDoc_STR("Return a new datetime representing UTC day and time.")}, *************** *** 625,629 **** {"combine", (PyCFunction)datetime_combine, ! METH_KEYWORDS | METH_CLASS, PyDoc_STR("date, time -> datetime with same date and time fields")}, --- 611,615 ---- {"combine", (PyCFunction)datetime_combine, ! METH_VARARGS | METH_KEYWORDS | METH_CLASS, PyDoc_STR("date, time -> datetime with same date and time fields")}, From tim_one@users.sourceforge.net Tue Dec 10 00:13:37 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 09 Dec 2002 16:13:37 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_date.c,1.45,1.46 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv6373 Modified Files: obj_date.c Log Message: Our good friend Super-Dynamite Time Bomb pointed out a typo, herewith repaired. Index: obj_date.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_date.c,v retrieving revision 1.45 retrieving revision 1.46 diff -C2 -d -r1.45 -r1.46 *** obj_date.c 9 Dec 2002 23:16:39 -0000 1.45 --- obj_date.c 10 Dec 2002 00:13:35 -0000 1.46 *************** *** 132,137 **** long ordinal; ! ! if (PyArg_ParseTuple(args, "l:formordinal", &ordinal)) { long year; long month; --- 132,136 ---- long ordinal; ! if (PyArg_ParseTuple(args, "l:fromordinal", &ordinal)) { long year; long month; From tim_one@users.sourceforge.net Tue Dec 10 02:04:29 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Mon, 09 Dec 2002 18:04:29 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_timetz.c,NONE,1.1 datetime.c,1.52,1.53 datetime.h,1.12,1.13 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv5008 Modified Files: datetime.c datetime.h Added Files: obj_timetz.c Log Message: Added wholly non-functional code for the timetz -- this is just a copy, paste, and mindless edit of the time code. --- NEW FILE: obj_timetz.c --- /* * PyDateTime_TimeTZ implementation. */ /* Accessor properties. */ static PyObject * timetz_hour(PyDateTime_TimeTZ *self, void *unused) { return PyInt_FromLong(TIME_GET_HOUR(self)); } static PyObject * timetz_minute(PyDateTime_TimeTZ *self, void *unused) { return PyInt_FromLong(TIME_GET_MINUTE(self)); } static PyObject * timetz_second(PyDateTime_TimeTZ *self, void *unused) { return PyInt_FromLong(TIME_GET_SECOND(self)); } static PyObject * timetz_microsecond(PyDateTime_TimeTZ *self, void *unused) { return PyInt_FromLong(TIME_GET_MICROSECOND(self)); } static PyGetSetDef timetz_getset[] = { {"hour", (getter)timetz_hour}, {"minute", (getter)timetz_minute}, {"second", (getter)timetz_second}, {"microsecond", (getter)timetz_microsecond}, {NULL} }; /* Constructors. */ static PyObject * timetz_new(PyTypeObject *type, PyObject *args, PyObject *kw) { PyObject *self = NULL; long hour = 0; long minute = 0; long second = 0; long usecond = 0; static char *keywords[] = { "hour", "minute", "second", "microsecond", NULL }; if (PyArg_ParseTupleAndKeywords(args, kw, "|llll", keywords, &hour, &minute, &second, &usecond)) { if (hour < 0 || hour > 23) { PyErr_SetString(PyExc_ValueError, "hour must be in 0..23"); return NULL; } if (minute < 0 || minute > 59) { PyErr_SetString(PyExc_ValueError, "minute must be in 0..59"); return NULL; } if (second < 0 || second > 59) { PyErr_SetString(PyExc_ValueError, "second must be in 0..59"); return NULL; } if (usecond < 0 || usecond > 999999) { PyErr_SetString(PyExc_ValueError, "microsecond must be in 0..999999"); return NULL; } self = new_time(hour, minute, second, usecond); } return self; } /* Various ways to turn a time into a string. */ static PyObject * timetz_repr(PyDateTime_TimeTZ *self) { char buffer[100]; char *typename = self->ob_type->tp_name; int h = TIME_GET_HOUR(self); int m = TIME_GET_MINUTE(self); int s = TIME_GET_SECOND(self); int us = TIME_GET_MICROSECOND(self); if (us) PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d, %d, %d)", typename, h, m, s, us); else if (s) PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d, %d)", typename, h, m, s); else PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d)", typename, h, m); return PyString_FromString(buffer); } static PyObject * timetz_str(PyDateTime_TimeTZ *self) { return PyObject_CallMethod((PyObject *)self, "isoformat", "()"); } static PyObject * timetz_isoformat(PyDateTime_TimeTZ *self) { char buffer[100]; /* Reuse the time format code from the datetime type. */ PyDateTime_DateTime datetime; PyDateTime_DateTime *pdatetime = &datetime; /* Copy over just the time bytes. */ memcpy(pdatetime->data + _PyDateTime_DATE_DATASIZE, self->data, _PyDateTime_TIME_DATASIZE); isoformat_time(pdatetime, buffer, sizeof(buffer)); return PyString_FromString(buffer); } static PyObject * timetz_strftime(PyDateTime_TimeTZ *self, PyObject *format) { PyObject *result; PyObject *tuple = Py_BuildValue("iiiiiiiii", 0, 0, 0, /* year, month, day */ TIME_GET_HOUR(self), TIME_GET_MINUTE(self), TIME_GET_SECOND(self), 0, 0, -1); /* weekday, daynum, dst */ if (tuple == NULL) return NULL; assert(PyTuple_Size(tuple) == 9); result = format_strftime(format, tuple); Py_DECREF(tuple); return result; } /* 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 * timetz_richcompare(PyDateTime_TimeTZ *self, PyObject *other, int op) { long diff; if (!PyType_IsSubtype(other->ob_type, &PyDateTime_TimeType)) { PyErr_Format(PyExc_TypeError, "can't compare time to %s instance", other->ob_type->tp_name); return NULL; } diff = memcmp(self->data, ((PyDateTime_TimeTZ *)other)->data, _PyDateTime_TIME_DATASIZE); return diff_to_bool(diff, op); } static PyObject *timetz_getstate(PyDateTime_TimeTZ *self); static long timetz_hash(PyDateTime_TimeTZ *self) { if (self->hashcode == -1) { PyObject *temp = timetz_getstate(self); if (temp != NULL) { self->hashcode = PyObject_Hash(temp); Py_DECREF(temp); } } return self->hashcode; } static int timetz_nonzero(PyDateTime_TimeTZ *self) { return TIME_GET_HOUR(self) || TIME_GET_MINUTE(self) || TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self); } /* Pickle support. Quite a maze! */ static PyObject * timetz_getstate(PyDateTime_TimeTZ *self) { return PyString_FromStringAndSize(self->data, _PyDateTime_TIME_DATASIZE); } static PyObject * timetz_setstate(PyDateTime_TimeTZ *self, PyObject *state) { const int len = PyString_Size(state); unsigned char *pdata = (unsigned char*)PyString_AsString(state); if (! PyString_Check(state) || len != _PyDateTime_TIME_DATASIZE) { PyErr_SetString(PyExc_TypeError, "bad argument to time.__setstate__"); return NULL; } memcpy(self->data, pdata, _PyDateTime_TIME_DATASIZE); self->hashcode = -1; Py_INCREF(Py_None); return Py_None; } /* XXX This seems a ridiculously inefficient way to pickle a short string. */ static PyObject * timetz_pickler(PyObject *module, PyDateTime_TimeTZ *time) { PyObject *state; PyObject *result = NULL; if (time->ob_type != &PyDateTime_TimeTZType) { PyErr_Format(PyExc_TypeError, "bad type passed to time pickler: %s", time->ob_type->tp_name); return NULL; } state = timetz_getstate(time); if (state) { result = Py_BuildValue("O(O)", time_unpickler_object, state); Py_DECREF(state); } return result; } static PyObject * timetz_unpickler(PyObject *module, PyObject *arg) { PyDateTime_TimeTZ *self; if (! PyString_CheckExact(arg)) { PyErr_Format(PyExc_TypeError, "bad type passed to time unpickler: %s", arg->ob_type->tp_name); return NULL; } self = PyObject_New(PyDateTime_TimeTZ, &PyDateTime_TimeTZType); if (self != NULL) { PyObject *res = timetz_setstate(self, arg); Py_XDECREF(res); } return (PyObject *)self; } static PyMethodDef timetz_methods[] = { {"isoformat", (PyCFunction)timetz_isoformat, METH_KEYWORDS, PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm].")}, {"strftime", (PyCFunction)timetz_strftime, METH_O, PyDoc_STR("format -> strftime() style string.")}, {"__setstate__", (PyCFunction)timetz_setstate, METH_O, PyDoc_STR("__setstate__(state)")}, {"__getstate__", (PyCFunction)timetz_getstate, METH_NOARGS, PyDoc_STR("__getstate__() -> state")}, {NULL, NULL} }; static char timetz_doc[] = PyDoc_STR("Time type."); static PyNumberMethods timetz_as_number = { 0, /* nb_add */ 0, /* nb_subtract */ 0, /* nb_multiply */ 0, /* nb_divide */ 0, /* nb_remainder */ 0, /* nb_divmod */ 0, /* nb_power */ 0, /* nb_negative */ 0, /* nb_positive */ 0, /* nb_absolute */ (inquiry)time_nonzero, /* nb_nonzero */ }; statichere PyTypeObject PyDateTime_TimeTZType = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ /* XXX When this module is renamed to datetime, change tp_name. */ "_datetime.time", /* tp_name */ sizeof(PyDateTime_TimeTZ), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)PyObject_Del, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ (reprfunc)timetz_repr, /* tp_repr */ &timetz_as_number, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ (hashfunc)timetz_hash, /* tp_hash */ 0, /* tp_call */ (reprfunc)timetz_str, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES | Py_TPFLAGS_BASETYPE, /* tp_flags */ time_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ (richcmpfunc)time_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ time_methods, /* tp_methods */ 0, /* tp_members */ time_getset, /* tp_getset */ &PyDateTime_TimeType, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ 0, /* tp_alloc */ timetz_new, /* tp_new */ _PyObject_Del, /* tp_free */ }; Index: datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.c,v retrieving revision 1.52 retrieving revision 1.53 diff -C2 -d -r1.52 -r1.53 *** datetime.c 9 Dec 2002 21:37:37 -0000 1.52 --- datetime.c 10 Dec 2002 02:04:26 -0000 1.53 *************** *** 72,75 **** --- 72,76 ---- static PyTypeObject PyDateTime_DeltaType; static PyTypeObject PyDateTime_TimeType; + static PyTypeObject PyDateTime_TimeTZType; /* *************** *** 632,635 **** --- 633,637 ---- static PyObject *datetime_unpickler_object = NULL; static PyObject *time_unpickler_object = NULL; + static PyObject *timetz_unpickler_object = NULL; /* For obscure reasons, we need to use tp_richcompare instead of tp_compare. *************** *** 663,666 **** --- 665,669 ---- #include "obj_datetime.c" #include "obj_time.c" + #include "obj_timetz.c" *************** *** 675,678 **** --- 678,683 ---- {"_time_pickler", (PyCFunction)time_pickler, METH_O, NULL}, {"_time_unpickler", (PyCFunction)time_unpickler, METH_O, NULL}, + {"_timetz_pickler", (PyCFunction)timetz_pickler, METH_O, NULL}, + {"_timetz_unpickler", (PyCFunction)timetz_unpickler, METH_O, NULL}, {NULL, NULL} }; *************** *** 699,702 **** --- 704,709 ---- if (PyType_Ready(&PyDateTime_TimeType) < 0) return; + if (PyType_Ready(&PyDateTime_TimeTZType) < 0) + return; /* timedelta values */ *************** *** 796,799 **** --- 803,809 ---- PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType); + Py_INCREF(&PyDateTime_TimeTZType); + PyModule_AddObject(m, "timetz", (PyObject *) &PyDateTime_TimeTZType); + /* A 4-year cycle has an extra leap day over what we'd get from *************** *** 875,878 **** --- 885,900 ---- Py_DECREF(pickler); + pickler = PyObject_GetAttrString(m, "_timetz_pickler"); + assert(pickler); + timetz_unpickler_object = PyObject_GetAttrString(m, + "_timetz_unpickler"); + assert(time_unpickler_object); + temp = PyObject_CallMethod(copyreg, "pickle", "OOO", + &PyDateTime_TimeTZType, + pickler, + timetz_unpickler_object); + assert(temp); + Py_DECREF(temp); + Py_DECREF(pickler); Py_DECREF(copyreg); } Index: datetime.h =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.h,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** datetime.h 7 Dec 2002 18:34:39 -0000 1.12 --- datetime.h 10 Dec 2002 02:04:26 -0000 1.13 *************** *** 53,56 **** --- 53,64 ---- { PyObject_HEAD + long hashcode; + unsigned char data[_PyDateTime_TIME_DATASIZE]; + PyObject *tzinfo; + } PyDateTime_TimeTZ; + + typedef struct + { + PyObject_HEAD long hashcode; /* -1 when unknown */ long days; /* -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS */ *************** *** 74,78 **** ((PyDateTime_DateTime*)o)->data[9]) ! /* Apply for time instances. */ #define PyDateTime_TIME_GET_HOUR(o) (((PyDateTime_Time*)o)->data[0]) #define PyDateTime_TIME_GET_MINUTE(o) (((PyDateTime_Time*)o)->data[1]) --- 82,86 ---- ((PyDateTime_DateTime*)o)->data[9]) ! /* Apply for time and timetz instances. */ #define PyDateTime_TIME_GET_HOUR(o) (((PyDateTime_Time*)o)->data[0]) #define PyDateTime_TIME_GET_MINUTE(o) (((PyDateTime_Time*)o)->data[1]) From nnorwitz@users.sourceforge.net Tue Dec 10 02:18:51 2002 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Mon, 09 Dec 2002 18:18:51 -0800 Subject: [Python-checkins] python/dist/src/Lib/lib-tk Tix.py,1.13,1.14 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/lib-tk In directory sc8-pr-cvs1:/tmp/cvs-serv8779/Lib/lib-tk Modified Files: Tix.py Log Message: Upgrade to Tix-8.1.4 from Mike Clarkson (the maintainer) Index: Tix.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/lib-tk/Tix.py,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** Tix.py 6 Dec 2002 10:33:44 -0000 1.13 --- Tix.py 10 Dec 2002 02:18:49 -0000 1.14 *************** *** 257,261 **** - Tkinter.Widget.__bases__ = Tkinter.Widget.__bases__ + (Form,) --- 257,260 ---- *************** *** 378,381 **** --- 377,400 ---- for name in names: self.tk.call(name, 'configure', '-' + option, value) + # These are missing from Tkinter + def image_create(self, imgtype, cnf={}, master=None, **kw): + if not master: + master = Tkinter._default_root + if not master: + raise RuntimeError, 'Too early to create image' + if kw and cnf: cnf = _cnfmerge((cnf, kw)) + elif kw: cnf = kw + options = () + for k, v in cnf.items(): + if callable(v): + v = self._register(v) + options = options + ('-'+k, v) + return master.tk.call(('image', 'create', imgtype,) + options) + def image_delete(self, imgname): + try: + self.tk.call('image', 'delete', imgname) + except TclError: + # May happen if the root was destroyed + pass # Subwidgets are child widgets created automatically by mega-widgets. *************** *** 566,569 **** --- 585,590 ---- pass + # align + def add_history(self, str): self.tk.call(self._w, 'addhistory', str) *************** *** 1248,1253 **** class ResizeHandle(TixWidget): """Internal widget to draw resize handles on Scrolled widgets.""" - # FIXME: This is dangerous to expose to be called on its own. - # Perhaps rename ResizeHandle to _ResizeHandle def __init__(self, master, cnf={}, **kw): # There seems to be a Tix bug rejecting the configure method --- 1269,1272 ---- From nnorwitz@users.sourceforge.net Tue Dec 10 02:18:51 2002 From: nnorwitz@users.sourceforge.net (nnorwitz@users.sourceforge.net) Date: Mon, 09 Dec 2002 18:18:51 -0800 Subject: [Python-checkins] python/dist/src/Demo/tix tixwidgets.py,1.8,1.9 Message-ID: Update of /cvsroot/python/python/dist/src/Demo/tix In directory sc8-pr-cvs1:/tmp/cvs-serv8779/Demo/tix Modified Files: tixwidgets.py Log Message: Upgrade to Tix-8.1.4 from Mike Clarkson (the maintainer) Index: tixwidgets.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Demo/tix/tixwidgets.py,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** tixwidgets.py 6 Dec 2002 10:33:45 -0000 1.8 --- tixwidgets.py 10 Dec 2002 02:18:49 -0000 1.9 *************** *** 1,5 **** # -*-mode: python; fill-column: 75; tab-width: 8; coding: iso-latin-1-unix -*- # - # Id: tixwidgets.py,v 1.7 2002/11/14 02:44:08 nnorwitz Exp # $Id$ # --- 1,4 ---- *************** *** 546,554 **** win = Tix.ScrolledWindow(top, scrollbar='auto') ! global image1 ! # This image is not showing up in the Label unless it is set to a ! # global variable - no problem under Tcl/Tix. It is being ! # garbage collected at the end of this proecedure if not global ! image1 = Tix.Image('photo', file=file) lbl = Tix.Label(win.window, image=image1) lbl.pack(expand=1, fill=Tix.BOTH) --- 545,549 ---- win = Tix.ScrolledWindow(top, scrollbar='auto') ! image1 = win.window.image_create('photo', file=file) lbl = Tix.Label(win.window, image=image1) lbl.pack(expand=1, fill=Tix.BOTH) From gward@users.sourceforge.net Tue Dec 10 16:24:25 2002 From: gward@users.sourceforge.net (gward@users.sourceforge.net) Date: Tue, 10 Dec 2002 08:24:25 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_ossaudiodev.py,NONE,1.1 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv30552 Added Files: test_ossaudiodev.py Log Message: Initial revision is rev 1.8 of test_linuxaudiodev.py, with the obvious s/linuxaudiodev/ossaudiodev/ change made. --- NEW FILE: test_ossaudiodev.py --- from test.test_support import verbose, findfile, TestFailed, TestSkipped import errno import fcntl import ossaudiodev import os import sys import select import sunaudio import time import audioop SND_FORMAT_MULAW_8 = 1 def play_sound_file(path): fp = open(path, 'r') size, enc, rate, nchannels, extra = sunaudio.gethdr(fp) data = fp.read() fp.close() if enc != SND_FORMAT_MULAW_8: print "Expect .au file with 8-bit mu-law samples" return try: a = ossaudiodev.open('w') except ossaudiodev.error, msg: if msg[0] in (errno.EACCES, errno.ENODEV, errno.EBUSY): raise TestSkipped, msg raise TestFailed, msg # convert the data to 16-bit signed data = audioop.ulaw2lin(data, 2) # set the data format if sys.byteorder == 'little': fmt = ossaudiodev.AFMT_S16_LE else: fmt = ossaudiodev.AFMT_S16_BE # at least check that these methods can be invoked a.bufsize() a.obufcount() a.obuffree() a.getptr() a.fileno() # set parameters based on .au file headers a.setparameters(rate, 16, nchannels, fmt) a.write(data) a.flush() a.close() def test_errors(): a = ossaudiodev.open("w") size = 8 fmt = ossaudiodev.AFMT_U8 rate = 8000 nchannels = 1 try: a.setparameters(-1, size, nchannels, fmt) except ValueError, msg: print msg try: a.setparameters(rate, -2, nchannels, fmt) except ValueError, msg: print msg try: a.setparameters(rate, size, 3, fmt) except ValueError, msg: print msg try: a.setparameters(rate, size, nchannels, 177) except ValueError, msg: print msg try: a.setparameters(rate, size, nchannels, ossaudiodev.AFMT_U16_LE) except ValueError, msg: print msg try: a.setparameters(rate, 16, nchannels, fmt) except ValueError, msg: print msg def test(): play_sound_file(findfile('audiotest.au')) test_errors() test() From gward@users.sourceforge.net Tue Dec 10 16:27:40 2002 From: gward@users.sourceforge.net (gward@users.sourceforge.net) Date: Tue, 10 Dec 2002 08:27:40 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_ossaudiodev.py,1.1,1.2 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv32233 Modified Files: test_ossaudiodev.py Log Message: Aesthetic tweakery: factor read_sound_file() out of play_sound_file(). Index: test_ossaudiodev.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_ossaudiodev.py,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** test_ossaudiodev.py 10 Dec 2002 16:24:21 -0000 1.1 --- test_ossaudiodev.py 10 Dec 2002 16:27:35 -0000 1.2 *************** *** 13,17 **** SND_FORMAT_MULAW_8 = 1 ! def play_sound_file(path): fp = open(path, 'r') size, enc, rate, nchannels, extra = sunaudio.gethdr(fp) --- 13,17 ---- SND_FORMAT_MULAW_8 = 1 ! def read_sound_file(path): fp = open(path, 'r') size, enc, rate, nchannels, extra = sunaudio.gethdr(fp) *************** *** 23,26 **** --- 23,32 ---- return + # Convert the data to 16-bit signed. + data = audioop.ulaw2lin(data, 2) + return (data, rate, 16, nchannels) + + + def play_sound_file(data, rate, ssize, nchannels): try: a = ossaudiodev.open('w') *************** *** 30,36 **** raise TestFailed, msg - # convert the data to 16-bit signed - data = audioop.ulaw2lin(data, 2) - # set the data format if sys.byteorder == 'little': --- 36,39 ---- *************** *** 84,88 **** def test(): ! play_sound_file(findfile('audiotest.au')) test_errors() --- 87,92 ---- def test(): ! (data, rate, ssize, nchannels) = read_sound_file(findfile('audiotest.au')) ! play_sound_file(data, rate, ssize, nchannels) test_errors() From tim_one@users.sourceforge.net Tue Dec 10 17:01:34 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 10 Dec 2002 09:01:34 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime doc.txt,1.39,1.40 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv12332 Modified Files: doc.txt Log Message: Added "implement tzinfo base class" issue. The FixedOffset semantics are probably going to be most useful to most people, so it would be nice to supply them. The implementation of *tz classes also needs a way to verify that their tzinfo argument implements the tzinfo interface, and forcing inheritance from a base tzinfo class is a clean and efficient way to enable that. Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.39 retrieving revision 1.40 diff -C2 -d -r1.39 -r1.40 *** doc.txt 9 Dec 2002 23:16:38 -0000 1.39 --- doc.txt 10 Dec 2002 17:01:21 -0000 1.40 *************** *** 1,4 **** --- 1,7 ---- TODO/OPEN ========= + - Implement a base tzinfo class, capturing the example FixedOffset + semantics. Variant tzinfo classes must subclass from this. + - datetimetz needs a C implementation. From tim_one@users.sourceforge.net Tue Dec 10 18:47:58 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 10 Dec 2002 10:47:58 -0800 Subject: [Python-checkins] python/dist/src/Lib/test regrtest.py,1.112,1.113 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv22018/python/Lib/test Modified Files: regrtest.py Log Message: Added test_ossaudiodev to expected skips on Windows. Index: regrtest.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/regrtest.py,v retrieving revision 1.112 retrieving revision 1.113 diff -C2 -d -r1.112 -r1.113 *** regrtest.py 5 Dec 2002 17:20:25 -0000 1.112 --- regrtest.py 10 Dec 2002 18:47:56 -0000 1.113 *************** *** 564,567 **** --- 564,568 ---- test_nis test_openpty + test_ossaudiodev test_poll test_pty From tim_one@users.sourceforge.net Tue Dec 10 19:03:54 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 10 Dec 2002 11:03:54 -0800 Subject: [Python-checkins] python/dist/src/PCbuild python20.wse,1.110,1.111 Message-ID: Update of /cvsroot/python/python/dist/src/PCbuild In directory sc8-pr-cvs1:/tmp/cvs-serv28475/python/PCbuild Modified Files: python20.wse Log Message: Install the tools/i18n directory on Windows. A user requested it, Barry agreed, and I see no reason not to. Index: python20.wse =================================================================== RCS file: /cvsroot/python/python/dist/src/PCbuild/python20.wse,v retrieving revision 1.110 retrieving revision 1.111 diff -C2 -d -r1.110 -r1.111 *** python20.wse 4 Dec 2002 04:00:09 -0000 1.110 --- python20.wse 10 Dec 2002 19:03:52 -0000 1.111 *************** *** 2242,2245 **** --- 2242,2253 ---- Flags=0000000100000010 end + item: Remark + end + item: Install File + Source=..\tools\i18n\*.py + Destination=%MAINDIR%\Tools\i18n + Description=Internationalization helpers + Flags=0000000000000010 + end item: End Block end From tim_one@users.sourceforge.net Tue Dec 10 20:10:52 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 10 Dec 2002 12:10:52 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.py,1.90,1.91 test_datetime.py,1.59,1.60 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv21800 Modified Files: datetime.py test_datetime.py Log Message: Added a tzinfo abstract base class to the Python implementation, and got rid of hasattr() calls in *tz constructors (tzinfo arguments must be instances of a tzinfo subclass now). Index: datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.py,v retrieving revision 1.90 retrieving revision 1.91 diff -C2 -d -r1.90 -r1.91 *** datetime.py 9 Dec 2002 22:10:53 -0000 1.90 --- datetime.py 10 Dec 2002 20:10:49 -0000 1.91 *************** *** 842,845 **** --- 842,873 ---- time.resolution = timedelta(microseconds=1) + class tzinfo(object): + """Abstract base class for time zone info classes. + + Subclasses must override the name(), utcoffset() and dst() methods. + """ + + def __init__(self, *args, **kw): + raise NotImplementedError("tzinfo must be subclassed") + + def tzname(self, dt): + "datetime -> string name of time zone." + raise NotImplementedError("tzinfo subclass must override tzname()") + + def utcoffset(self, dt): + "datetime -> minutes east of UTC (negative for west of UTC)" + raise NotImplementedError("tzinfo subclass must override utcoffset()") + + def dst(self, dt): + """datetime -> DST offset in minutes east of UTC. + + Return 0 if DST not in effect. utcoffset() must include the DST + offset. + """ + raise NotImplementedError("tzinfo subclass must override dst()") + + def __str__(self): + return self.tzname() + class timetz(time): *************** *** 876,885 **** tzinfo (default to None) """ super(timetz, self).__init__(hour, minute, second, microsecond) - if tzinfo is not None: - # Better fail now than later - assert hasattr(tzinfo, 'utcoffset') - assert hasattr(tzinfo, 'dst') - assert hasattr(tzinfo, 'tzname') self.__tzinfo = tzinfo --- 904,912 ---- tzinfo (default to None) """ + import datetime + if tzinfo is not None and not isinstance(tzinfo, datetime.tzinfo): + raise TypeError("tzinfo argument must be None or of a tzinfo " + "subclass") super(timetz, self).__init__(hour, minute, second, microsecond) self.__tzinfo = tzinfo *************** *** 1285,1295 **** def __init__(self, year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None): super(datetimetz, self).__init__(year, month, day, hour, minute, second, microsecond) - if tzinfo is not None: - # Better fail now than later - assert hasattr(tzinfo, 'utcoffset') - assert hasattr(tzinfo, 'dst') - assert hasattr(tzinfo, 'tzname') self.__tzinfo = tzinfo --- 1312,1321 ---- def __init__(self, year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None): + import datetime + if tzinfo is not None and not isinstance(tzinfo, datetime.tzinfo): + raise TypeError("tzinfo argument must be None or of a tzinfo " + "subclass") super(datetimetz, self).__init__(year, month, day, hour, minute, second, microsecond) self.__tzinfo = tzinfo Index: test_datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_datetime.py,v retrieving revision 1.59 retrieving revision 1.60 diff -C2 -d -r1.59 -r1.60 *** test_datetime.py 9 Dec 2002 19:50:34 -0000 1.59 --- test_datetime.py 10 Dec 2002 20:10:49 -0000 1.60 *************** *** 14,18 **** from datetime import date, time, timetz, datetime, datetimetz, timedelta, \ ! MINYEAR, MAXYEAR class TestTimeTZ(unittest.TestCase): --- 14,31 ---- from datetime import date, time, timetz, datetime, datetimetz, timedelta, \ ! tzinfo, MINYEAR, MAXYEAR ! ! class FixedOffset(tzinfo): ! def __init__(self, offset, name): ! self.__offset = offset ! self.__name = name ! def __repr__(self): ! return self.__name.lower() ! def utcoffset(self, dt): ! return self.__offset ! def tzname(self, dt): ! return self.__name ! def dst(self, dt): ! return 0 class TestTimeTZ(unittest.TestCase): *************** *** 73,89 **** self.assertEqual(dt, dt2) self.assertEqual(timestamp, tm.time()) - - class FixedOffset(object): - def __init__(self, offset, name): - self.__offset = offset - self.__name = name - def __repr__(self): - return self.__name.lower() - def utcoffset(self, dt): - return self.__offset - def tzname(self, dt): - return self.__name - def dst(self, dt): - return 0 --- 86,89 ---- From tim_one@users.sourceforge.net Tue Dec 10 20:44:30 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 10 Dec 2002 12:44:30 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.py,1.91,1.92 test_datetime.py,1.60,1.61 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv2526 Modified Files: datetime.py test_datetime.py Log Message: Added tests (necessarily trivial) for the new tzinfo base class. Removed __str__ implementation from tzinfo: it can't know what to pass to self.tzname! Index: datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.py,v retrieving revision 1.91 retrieving revision 1.92 diff -C2 -d -r1.91 -r1.92 *** datetime.py 10 Dec 2002 20:10:49 -0000 1.91 --- datetime.py 10 Dec 2002 20:44:23 -0000 1.92 *************** *** 867,873 **** raise NotImplementedError("tzinfo subclass must override dst()") - def __str__(self): - return self.tzname() - class timetz(time): --- 867,870 ---- Index: test_datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_datetime.py,v retrieving revision 1.60 retrieving revision 1.61 diff -C2 -d -r1.60 -r1.61 *** test_datetime.py 10 Dec 2002 20:10:49 -0000 1.60 --- test_datetime.py 10 Dec 2002 20:44:24 -0000 1.61 *************** *** 16,19 **** --- 16,24 ---- tzinfo, MINYEAR, MAXYEAR + class NotEnough(tzinfo): + def __init__(self, offset, name): + self.__offset = offset + self.__name = name + class FixedOffset(tzinfo): def __init__(self, offset, name): *************** *** 29,32 **** --- 34,61 ---- return 0 + class TestTZInfo(unittest.TestCase): + + def test_abstractness(self): + self.assertRaises(NotImplementedError, tzinfo) + + def test_subclass_must_override(self): + self.failUnless(issubclass(NotEnough, tzinfo)) + ne = NotEnough(3, "NotByALongShot") + self.failUnless(isinstance(ne, tzinfo)) + + dt = datetime.now() + self.assertRaises(NotImplementedError, ne.tzname, dt) + self.assertRaises(NotImplementedError, ne.utcoffset, dt) + self.assertRaises(NotImplementedError, ne.dst, dt) + + def test_normal(self): + fo = FixedOffset(3, "Three") + self.failUnless(isinstance(fo, tzinfo)) + for dt in datetime.now(), None: + self.assertEqual(fo.utcoffset(dt), 3) + self.assertEqual(fo.tzname(dt), "Three") + self.assertEqual(fo.dst(dt), 0) + + class TestTimeTZ(unittest.TestCase): *************** *** 141,148 **** def test_suite(): s4 = unittest.makeSuite(TestTimeTZ, 'test') s5 = unittest.makeSuite(TestDateTime, 'test') s6 = unittest.makeSuite(TestDateTimeTZ, 'test') ! return unittest.TestSuite([s4, s5, s6]) def test_main(): --- 170,178 ---- def test_suite(): + s3 = unittest.makeSuite(TestTZInfo, 'test') s4 = unittest.makeSuite(TestTimeTZ, 'test') s5 = unittest.makeSuite(TestDateTime, 'test') s6 = unittest.makeSuite(TestDateTimeTZ, 'test') ! return unittest.TestSuite([s3, s4, s5, s6]) def test_main(): From tim_one@users.sourceforge.net Tue Dec 10 21:04:30 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 10 Dec 2002 13:04:30 -0800 Subject: [Python-checkins] python/dist/src/Doc/whatsnew whatsnew23.tex,1.83,1.84 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/whatsnew In directory sc8-pr-cvs1:/tmp/cvs-serv10530/python/Doc/whatsnew Modified Files: whatsnew23.tex Log Message: Added a word to the heapq description in response to user confusion. Index: whatsnew23.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/whatsnew/whatsnew23.tex,v retrieving revision 1.83 retrieving revision 1.84 diff -C2 -d -r1.83 -r1.84 *** whatsnew23.tex 3 Dec 2002 13:35:17 -0000 1.83 --- whatsnew23.tex 10 Dec 2002 21:04:25 -0000 1.84 *************** *** 1105,1110 **** \item The new \module{heapq} module contains an implementation of a heap queue algorithm. A heap is an array-like data structure that ! keeps items in a sorted order such that, for every index k, heap[k] <= ! heap[2*k+1] and heap[k] <= heap[2*k+2]. This makes it quick to remove the smallest item, and inserting a new item while maintaining the heap property is O(lg~n). (See --- 1105,1111 ---- \item The new \module{heapq} module contains an implementation of a heap queue algorithm. A heap is an array-like data structure that ! keeps items in a partially sorted order such that, ! for every index k, heap[k] <= heap[2*k+1] and heap[k] <= heap[2*k+2]. ! This makes it quick to remove the smallest item, and inserting a new item while maintaining the heap property is O(lg~n). (See From tim_one@users.sourceforge.net Tue Dec 10 21:21:15 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 10 Dec 2002 13:21:15 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime doc.txt,1.40,1.41 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv16758 Modified Files: doc.txt Log Message: Added a subclass tree. Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.40 retrieving revision 1.41 diff -C2 -d -r1.40 -r1.41 *** doc.txt 10 Dec 2002 17:01:21 -0000 1.40 --- doc.txt 10 Dec 2002 21:21:13 -0000 1.41 *************** *** 1,6 **** TODO/OPEN ========= ! - Implement a base tzinfo class, capturing the example FixedOffset ! semantics. Variant tzinfo classes must subclass from this. - datetimetz needs a C implementation. --- 1,6 ---- TODO/OPEN ========= ! - Implement an abstract base tzinfo class semantics. Variant tzinfo ! classes must subclass from this. - datetimetz needs a C implementation. *************** *** 8,17 **** - timetz needs a C implementation. ! - Subclass relationships. Currently datetime is a subclass of date. ! I like this in practice, and think it's theoretically sound too. ! Should this be blessed? I expect the same questions to pop up for ! timetz wrt time, and datetimetz wrt datetime. ! Guido sez subclassing is fine. Add docs about the subclass ! relationships. - LaTeXize the docs. --- 8,12 ---- - timetz needs a C implementation. ! - tzinfo needs a C implementation. - LaTeXize the docs. *************** *** 22,25 **** --- 17,28 ---- CLOSED ====== + - Subclass relationships. Currently datetime is a subclass of date. + I like this in practice, and think it's theoretically sound too. + Should this be blessed? I expect the same questions to pop up for + timetz wrt time, and datetimetz wrt datetime. + Guido sez subclassing is fine. Add docs about the subclass + relationships. + Done. + - The METH_CLASS bug affects about a dozen functions here. They'll need to be recoded in minor ways when the bug gets fixed. The bug needs to *************** *** 82,99 **** time, or whatever else is convenient. class datetimetz Like datetime, but also supports a customizable notion of time - adjustment (for timezones, or daylight savings time, or any other - computable adjustment). - - class timetz - Like time, but also supports a customizable notion of time adjustment. ! class timedelta ! A duration, the difference between two datetimes, to microsecond ! resolution. Objects of these types are immutable. --- 85,118 ---- time, or whatever else is convenient. + class timedelta + A duration, the difference between two dates, times, or datetimes, to + microsecond resolution. + + class tzinfo + An abstract base class for time zone information objects. These are + used by the datetimetz and timetz classes to provided a customizable + notion of time adjustment (for example, to account for time zone + and/or daylight savings time). + class datetimetz Like datetime, but also supports a customizable notion of time adjustment. ! class timetz ! Like time, but also supports a customizable notion of time adjustment. Objects of these types are immutable. + + + Subclass relationships + ====================== + object + timedelta + tzinfo + date + datetime + datetimetz + time + timetz From tim_one@users.sourceforge.net Tue Dec 10 21:59:53 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 10 Dec 2002 13:59:53 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime doc.txt,1.41,1.42 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv31262 Modified Files: doc.txt Log Message: Added docs for tzinfo. I'm pretty sure these are full of holes. For example, can None be passed to tzinfo.tzname(), and if so, what should tzinfo.tzname(None) do? Note that if None cannot be passed to tzinfo.tzname(), then how is timetz.tzname() supposed to work? That is, a timetz doesn't have a datetimetz available to pass back to tzinfo. Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.41 retrieving revision 1.42 diff -C2 -d -r1.41 -r1.42 *** doc.txt 10 Dec 2002 21:21:13 -0000 1.41 --- doc.txt 10 Dec 2002 21:59:51 -0000 1.42 *************** *** 1,6 **** TODO/OPEN ========= ! - Implement an abstract base tzinfo class semantics. Variant tzinfo ! classes must subclass from this. - datetimetz needs a C implementation. --- 1,6 ---- TODO/OPEN ========= ! - Implement an abstract base tzinfo class. Variant tzinfo classes must ! subclass from this. - datetimetz needs a C implementation. *************** *** 605,612 **** - class datetimetz - ================ - - class time ========== --- 605,608 ---- *************** *** 679,682 **** --- 675,736 ---- and second should not be used, since a time object has meaningful values only for those fields. + + + class tzinfo + ============ + tzinfo is an abstract base clase, meaning that objects of this class + cannot be instantiated. You need to derive a concrete subclass, and + supply implementations of (at least) the standard tzinfo methods. + The datetime module does not supply any concrete subclasses of tzinfo. + + An instance of (a concrete subclass of) tzinfo can be passed to the + constructors for datetimetz and timetz objects. The latter objects + view their fields as being in local time, and the tzinfo object supports + methods revealing offset of local time from UTC, and the name of the + time zone. + + A concrete subclass of tzinfo must implement the following methods. + + - __init__() + There are no special requirements on the constructor. + tzinfo.__init__() must not be called, since tzinfo is an abstract + class. + + The remaining methods are normally called by a datetimetz object, in + response to the datetimetz method of the same name, passing itself as + the argument. If dt.tzinfo is not None and not equal to self, an + exception should be raised: + + - utcoffset(dt) + Return offset of local time from UTC, in minutes east of UTC. If + local time is west of UTC, this should be negative. Note that this + is intended to be the total offset from UTC; for example, if a + tzinfo object represents both time zone and DST adjustments, + utcoffset() should return their sum. Return None if the UTC offset + isn't known. + + - tzname(dt) + Return the timezone name corresponding to the date and time + represented by dt, as a string. Nothing about string names is + defined by the datetime module, and there's no requirement that + it mean anything in particular. For example, "GMT", "UTC", "-500", + "-5:00", "EDT", "US/Eastern", "America/New York" are all valid + replies. Return None if a string name isn't known. Note that + this is a method rather than a fixed string primarily because + some tzinfo objects will wish to return different names depending + on the specific value of dt passed, especially if the tzinfo class + is accounting for DST. + + - dst(dt) + Return the DST offset, in minutes east of UTC, or None if DST + information isn't known. Return 0 if DST is not in effect. + Note that DST offset, if applicable, has already been added to + the UTC offset returned by utcoffset(), so there's no need to + consult dst() unless you're interested in displaying DST info + separately. + + + class datetimetz + ================ From tim_one@users.sourceforge.net Wed Dec 11 00:11:18 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 10 Dec 2002 16:11:18 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_timetz.c,1.1,1.2 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv22580 Modified Files: obj_timetz.c Log Message: Just noted that timetz is wholly non-functional now in the C implementation. This is taking a detour to implement the tzinfo class first. Index: obj_timetz.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_timetz.c,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** obj_timetz.c 10 Dec 2002 02:04:26 -0000 1.1 --- obj_timetz.c 11 Dec 2002 00:11:15 -0000 1.2 *************** *** 1,2 **** --- 1,6 ---- + /* XXX The timetz type here isn't functional -- it merely compiles. + * XXX This is a copy and very light edit of obj_time.c. + * XXX The tzinfo base clase has to get implemented first. + */ /* * PyDateTime_TimeTZ implementation. From tim_one@users.sourceforge.net Wed Dec 11 01:47:23 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 10 Dec 2002 17:47:23 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_tzinfo.c,NONE,1.1 datetime.c,1.53,1.54 datetime.h,1.13,1.14 doc.txt,1.42,1.43 test_both.py,1.57,1.58 test_datetime.py,1.61,1.62 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv30696 Modified Files: datetime.c datetime.h doc.txt test_both.py test_datetime.py Added Files: obj_tzinfo.c Log Message: Gave the tzinfo abstract base class a C implementation, and moved the tests for it into test_both. I never tried to implement an abstract base class in C before, and had lots of problems, mostly cured by poking 0 into type slots. Some Guido who knows what he's doing here should review obj_tzinfo.c! --- NEW FILE: obj_tzinfo.c --- /* * PyDateTime_TZInfo implementation. */ /* This is a pure abstract base class, so doesn't do anything beyond * raising NotImplemented exceptions. Real tzinfo classes need * to derive from this. This is mostly for clarity, and for efficiency in * datetimetz and timetz constructors (their tzinfo arguments need to * be subclasses of this tzinfo class, which is easy and quick to check). */ static PyObject * tzinfo_nogo(const char* methodname) { PyErr_Format(PyExc_NotImplementedError, "a tzinfo subclass must implement %s()", methodname); return NULL; } /* Constructors -- you can't actually construct one of these! Well, * you can, via fooling __new__, but you can't do much with it. */ static int tzinfo_init(PyDateTime_TZInfo *self, PyObject *args, PyObject *kw) { (void)tzinfo_nogo("__init__"); return -1; } /* Methods. A subclass must implement these. */ static PyObject* tzinfo_tzname(PyTypeObject *self, PyObject *dt) { return tzinfo_nogo("tzname"); } static PyObject* tzinfo_utcoffset(PyTypeObject *self, PyObject *dt) { return tzinfo_nogo("utcoffset"); } static PyObject* tzinfo_dst(PyTypeObject *self, PyObject *dt) { return tzinfo_nogo("dst"); } static PyMethodDef tzinfo_methods[] = { {"tzname", (PyCFunction)tzinfo_tzname, METH_O, PyDoc_STR("datetime -> string name of time zone.")}, {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O, PyDoc_STR("datetime -> minutes east of UTC (negative for " "west of UTC).")}, {"dst", (PyCFunction)tzinfo_dst, METH_O, PyDoc_STR("datetime -> DST offset in minutes east of UTC.")}, {NULL, NULL} }; static char tzinfo_doc[] = PyDoc_STR("Abstract base class for time zone info objects."); statichere PyTypeObject PyDateTime_TZInfoType = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ /* XXX When this module is renamed to datetime, change tp_name. */ "_datetime.tzinfo", /* tp_name */ sizeof(PyDateTime_TZInfo), /* tp_basicsize */ 0, /* tp_itemsize */ 0, /* 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_CHECKTYPES | Py_TPFLAGS_BASETYPE, /* tp_flags */ tzinfo_doc, /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ tzinfo_methods, /* 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 */ (initproc)tzinfo_init, /* tp_init */ 0, /* tp_alloc */ PyType_GenericNew, /* tp_new */ 0, /* tp_free */ }; Index: datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.c,v retrieving revision 1.53 retrieving revision 1.54 diff -C2 -d -r1.53 -r1.54 *** datetime.c 10 Dec 2002 02:04:26 -0000 1.53 --- datetime.c 11 Dec 2002 01:47:20 -0000 1.54 *************** *** 72,75 **** --- 72,76 ---- static PyTypeObject PyDateTime_DeltaType; static PyTypeObject PyDateTime_TimeType; + static PyTypeObject PyDateTime_TZInfoType; static PyTypeObject PyDateTime_TimeTZType; *************** *** 665,668 **** --- 666,670 ---- #include "obj_datetime.c" #include "obj_time.c" + #include "obj_tzinfo.c" #include "obj_timetz.c" *************** *** 704,707 **** --- 706,711 ---- if (PyType_Ready(&PyDateTime_TimeType) < 0) return; + if (PyType_Ready(&PyDateTime_TZInfoType) < 0) + return; if (PyType_Ready(&PyDateTime_TimeTZType) < 0) return; *************** *** 802,805 **** --- 806,812 ---- Py_INCREF(&PyDateTime_TimeType); PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType); + + Py_INCREF(&PyDateTime_TZInfoType); + PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType); Py_INCREF(&PyDateTime_TimeTZType); Index: datetime.h =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.h,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** datetime.h 10 Dec 2002 02:04:26 -0000 1.13 --- datetime.h 11 Dec 2002 01:47:20 -0000 1.14 *************** *** 67,70 **** --- 67,75 ---- } PyDateTime_Delta; + typedef struct + { + PyObject_HEAD /* a pure abstract base clase */ + } PyDateTime_TZInfo; + /* Apply for date instances. */ #define PyDateTime_GET_YEAR(o) ((((PyDateTime_Date*)o)->data[0] << 8) | \ Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.42 retrieving revision 1.43 diff -C2 -d -r1.42 -r1.43 *** doc.txt 10 Dec 2002 21:59:51 -0000 1.42 --- doc.txt 11 Dec 2002 01:47:20 -0000 1.43 *************** *** 1,13 **** TODO/OPEN ========= - - Implement an abstract base tzinfo class. Variant tzinfo classes must - subclass from this. - - datetimetz needs a C implementation. - timetz needs a C implementation. - - tzinfo needs a C implementation. - - LaTeXize the docs. --- 1,8 ---- *************** *** 17,20 **** --- 12,23 ---- CLOSED ====== + - tzinfo needs a C implementation. + Done. + + - Implement an abstract base tzinfo class. Variant tzinfo classes must + subclass from this. + Done. + + - Subclass relationships. Currently datetime is a subclass of date. I like this in practice, and think it's theoretically sound too. Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.57 retrieving revision 1.58 diff -C2 -d -r1.57 -r1.58 *** test_both.py 9 Dec 2002 19:50:33 -0000 1.57 --- test_both.py 11 Dec 2002 01:47:20 -0000 1.58 *************** *** 41,44 **** --- 41,45 ---- timedelta = datetime.timedelta time = datetime.time + tzinfo = datetime.tzinfo MINYEAR = datetime.MINYEAR MAXYEAR = datetime.MAXYEAR *************** *** 54,57 **** --- 55,102 ---- ############################################################################# + # tzinfo tests + + class NotEnough(tzinfo): + def __init__(self, offset, name): + self.__offset = offset + self.__name = name + + class FixedOffset(tzinfo): + def __init__(self, offset, name): + self.__offset = offset + self.__name = name + def __repr__(self): + return self.__name.lower() + def utcoffset(self, dt): + return self.__offset + def tzname(self, dt): + return self.__name + def dst(self, dt): + return 0 + + class TestTZInfo(unittest.TestCase): + + def test_abstractness(self): + self.assertRaises(NotImplementedError, tzinfo) + + def test_subclass_must_override(self): + self.failUnless(issubclass(NotEnough, tzinfo)) + ne = NotEnough(3, "NotByALongShot") + self.failUnless(isinstance(ne, tzinfo)) + + dt = datetime.datetime.now() + self.assertRaises(NotImplementedError, ne.tzname, dt) + self.assertRaises(NotImplementedError, ne.utcoffset, dt) + self.assertRaises(NotImplementedError, ne.dst, dt) + + def test_normal(self): + fo = FixedOffset(3, "Three") + self.failUnless(isinstance(fo, tzinfo)) + for dt in datetime.datetime.now(), None: + self.assertEqual(fo.utcoffset(dt), 3) + self.assertEqual(fo.tzname(dt), "Three") + self.assertEqual(fo.dst(dt), 0) + + ############################################################################# # timedelta tests *************** *** 1397,1400 **** --- 1442,1446 ---- allsuites = [unittest.makeSuite(klass, 'test') for klass in (TestModule, + TestTZInfo, TestTimeDelta, TestDateOnly, Index: test_datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_datetime.py,v retrieving revision 1.61 retrieving revision 1.62 diff -C2 -d -r1.61 -r1.62 *** test_datetime.py 10 Dec 2002 20:44:24 -0000 1.61 --- test_datetime.py 11 Dec 2002 01:47:20 -0000 1.62 *************** *** 16,24 **** tzinfo, MINYEAR, MAXYEAR - class NotEnough(tzinfo): - def __init__(self, offset, name): - self.__offset = offset - self.__name = name - class FixedOffset(tzinfo): def __init__(self, offset, name): --- 16,19 ---- *************** *** 34,60 **** return 0 - class TestTZInfo(unittest.TestCase): - - def test_abstractness(self): - self.assertRaises(NotImplementedError, tzinfo) - - def test_subclass_must_override(self): - self.failUnless(issubclass(NotEnough, tzinfo)) - ne = NotEnough(3, "NotByALongShot") - self.failUnless(isinstance(ne, tzinfo)) - - dt = datetime.now() - self.assertRaises(NotImplementedError, ne.tzname, dt) - self.assertRaises(NotImplementedError, ne.utcoffset, dt) - self.assertRaises(NotImplementedError, ne.dst, dt) - - def test_normal(self): - fo = FixedOffset(3, "Three") - self.failUnless(isinstance(fo, tzinfo)) - for dt in datetime.now(), None: - self.assertEqual(fo.utcoffset(dt), 3) - self.assertEqual(fo.tzname(dt), "Three") - self.assertEqual(fo.dst(dt), 0) - class TestTimeTZ(unittest.TestCase): --- 29,32 ---- *************** *** 170,178 **** def test_suite(): - s3 = unittest.makeSuite(TestTZInfo, 'test') s4 = unittest.makeSuite(TestTimeTZ, 'test') s5 = unittest.makeSuite(TestDateTime, 'test') s6 = unittest.makeSuite(TestDateTimeTZ, 'test') ! return unittest.TestSuite([s3, s4, s5, s6]) def test_main(): --- 142,149 ---- def test_suite(): s4 = unittest.makeSuite(TestTimeTZ, 'test') s5 = unittest.makeSuite(TestDateTime, 'test') s6 = unittest.makeSuite(TestDateTimeTZ, 'test') ! return unittest.TestSuite([s4, s5, s6]) def test_main(): From tim_one@users.sourceforge.net Wed Dec 11 02:06:54 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Tue, 10 Dec 2002 18:06:54 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_tzinfo.c,1.1,1.2 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv5768 Modified Files: obj_tzinfo.c Log Message: Repaired stupid cut'n'paste errors in function signatures. No semantic effect, it was just confusing. Index: obj_tzinfo.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_tzinfo.c,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** obj_tzinfo.c 11 Dec 2002 01:47:20 -0000 1.1 --- obj_tzinfo.c 11 Dec 2002 02:06:52 -0000 1.2 *************** *** 33,37 **** static PyObject* ! tzinfo_tzname(PyTypeObject *self, PyObject *dt) { return tzinfo_nogo("tzname"); --- 33,37 ---- static PyObject* ! tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt) { return tzinfo_nogo("tzname"); *************** *** 39,43 **** static PyObject* ! tzinfo_utcoffset(PyTypeObject *self, PyObject *dt) { return tzinfo_nogo("utcoffset"); --- 39,43 ---- static PyObject* ! tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt) { return tzinfo_nogo("utcoffset"); *************** *** 45,49 **** static PyObject* ! tzinfo_dst(PyTypeObject *self, PyObject *dt) { return tzinfo_nogo("dst"); --- 45,49 ---- static PyObject* ! tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt) { return tzinfo_nogo("dst"); From rhettinger@users.sourceforge.net Wed Dec 11 07:14:05 2002 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Tue, 10 Dec 2002 23:14:05 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libstdtypes.tex,1.112,1.113 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv21026/Doc/lib Modified Files: libstdtypes.tex Log Message: Update comments about the performance of xrange(). Index: libstdtypes.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libstdtypes.tex,v retrieving revision 1.112 retrieving revision 1.113 diff -C2 -d -r1.112 -r1.113 *** libstdtypes.tex 3 Dec 2002 18:09:02 -0000 1.112 --- libstdtypes.tex 11 Dec 2002 07:14:03 -0000 1.113 *************** *** 885,890 **** advantages. ! XRange objects have very little behavior: they only support indexing ! and the \function{len()} function. --- 885,890 ---- advantages. ! XRange objects have very little behavior: they only support indexing, ! iteration, and the \function{len()} function. From rhettinger@users.sourceforge.net Wed Dec 11 07:14:05 2002 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Tue, 10 Dec 2002 23:14:05 -0800 Subject: [Python-checkins] python/dist/src/Objects rangeobject.c,2.45,2.46 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv21026/Objects Modified Files: rangeobject.c Log Message: Update comments about the performance of xrange(). Index: rangeobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/rangeobject.c,v retrieving revision 2.45 retrieving revision 2.46 diff -C2 -d -r2.45 -r2.46 *** rangeobject.c 7 Nov 2002 16:55:54 -0000 2.45 --- rangeobject.c 11 Dec 2002 07:14:02 -0000 2.46 *************** *** 114,119 **** \n\ Like range(), but instead of returning a list, returns an object that\n\ ! generates the numbers in the range on demand. This is slightly slower\n\ ! than range() but more memory efficient."); static PyObject * --- 114,119 ---- \n\ Like range(), but instead of returning a list, returns an object that\n\ ! generates the numbers in the range on demand. For looping, this is \n\ ! slightly faster than range() and more memory efficient."); static PyObject * From rhettinger@users.sourceforge.net Wed Dec 11 07:16:08 2002 From: rhettinger@users.sourceforge.net (rhettinger@users.sourceforge.net) Date: Tue, 10 Dec 2002 23:16:08 -0800 Subject: [Python-checkins] python/dist/src/Lib/test test_userdict.py,1.10,1.11 Message-ID: Update of /cvsroot/python/python/dist/src/Lib/test In directory sc8-pr-cvs1:/tmp/cvs-serv22067 Modified Files: test_userdict.py Log Message: Clean-up test class for DictMixin. Index: test_userdict.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_userdict.py,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** test_userdict.py 27 Nov 2002 08:29:11 -0000 1.10 --- test_userdict.py 11 Dec 2002 07:16:06 -0000 1.11 *************** *** 156,161 **** return self.valuelist[i] def __setitem__(self, key, value): ! self.keylist.append(key) ! self.valuelist.append(value) def __delitem__(self, key): try: --- 156,165 ---- return self.valuelist[i] def __setitem__(self, key, value): ! try: ! i = self.keylist.index(key) ! self.valuelist[i] = value ! except ValueError: ! self.keylist.append(key) ! self.valuelist.append(value) def __delitem__(self, key): try: From just@letterror.com Wed Dec 11 09:40:33 2002 From: just@letterror.com (Just van Rossum) Date: Wed, 11 Dec 2002 10:40:33 +0100 Subject: [Python-checkins] python/dist/src/Lib textwrap.py,1.18,1.19 In-Reply-To: Message-ID: This checkin makes textwrap fail for me when running python -S ("don't run site.py"): Python 2.3a0 (#42, Dec 11 2002, 10:33:42) [GCC 3.1 20020420 (prerelease)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import textwrap Traceback (most recent call last): File "", line 1, in ? File "/Users/just/code/python_cvs/Lib/textwrap.py", line 15, in ? class TextWrapper: File "/Users/just/code/python_cvs/Lib/textwrap.py", line 56, in TextWrapper unicode_whitespace_trans[ord(unicode(c))] = ord(u' ') UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 0: ordinal not in range(128) >>> Just gward@users.sourceforge.net wrote: > Update of /cvsroot/python/python/dist/src/Lib > In directory sc8-pr-cvs1:/tmp/cvs-serv26875 > > Modified Files: > textwrap.py > Log Message: > Fix SF bug #622831 (I think): add unicode_whitespace_trans class > attribute, and modify _munge_whitespace() to recognize Unicode strings > and use unicode_whitespace_trans to munge them. Still need to add a > test to make sure I've really fixed the bug. > > > Index: textwrap.py > =================================================================== > RCS file: /cvsroot/python/python/dist/src/Lib/textwrap.py,v > retrieving revision 1.18 > retrieving revision 1.19 > diff -C2 -d -r1.18 -r1.19 > *** textwrap.py 22 Oct 2002 18:31:50 -0000 1.18 > --- textwrap.py 9 Dec 2002 16:23:08 -0000 1.19 > *************** > *** 52,55 **** > --- 52,59 ---- > ' ' * len(string.whitespace)) > > + unicode_whitespace_trans = {} > + for c in string.whitespace: > + unicode_whitespace_trans[ord(unicode(c))] = ord(u' ') > + > # This funky little regex is just the trick for splitting > # text up into word-wrappable chunks. E.g. > *************** > *** 100,104 **** > text = text.expandtabs() > if self.replace_whitespace: > ! text = text.translate(self.whitespace_trans) > return text > > --- 104,111 ---- > text = text.expandtabs() > if self.replace_whitespace: > ! if isinstance(text, str): > ! text = text.translate(self.whitespace_trans) > ! elif isinstance(text, unicode): > ! text = text.translate(self.unicode_whitespace_trans) > return text > > > > > _______________________________________________ > Python-checkins mailing list > Python-checkins@python.org > http://mail.python.org/mailman/listinfo/python-checkins > From mal@lemburg.com Wed Dec 11 10:34:14 2002 From: mal@lemburg.com (M.-A. Lemburg) Date: Wed, 11 Dec 2002 11:34:14 +0100 Subject: [Python-checkins] python/dist/src/Lib textwrap.py,1.18,1.19 References: Message-ID: <3DF714A6.5010100@lemburg.com> Just van Rossum wrote: > This checkin makes textwrap fail for me when running python -S ("don't run > site.py"): > > Python 2.3a0 (#42, Dec 11 2002, 10:33:42) > [GCC 3.1 20020420 (prerelease)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>>>import textwrap > > Traceback (most recent call last): > File "", line 1, in ? > File "/Users/just/code/python_cvs/Lib/textwrap.py", line 15, in ? > class TextWrapper: > File "/Users/just/code/python_cvs/Lib/textwrap.py", line 56, in TextWrapper > unicode_whitespace_trans[ord(unicode(c))] = ord(u' ') > UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 0: ordinal > not in range(128) > >>+ unicode_whitespace_trans = {} >>+ for c in string.whitespace: >>+ unicode_whitespace_trans[ord(unicode(c))] = ord(u' ') >>+ This should probably read: uspace = ord(u' ') # no idea what this gives you on non-ASCII machines for x in map(ord, string.whitespace): unicode_whitespace_trans[x] = uspace Note that Unicode has many more whitespace characters than the ones mentioned in string.whitespace, so this approach is not 100% correct. -- Marc-Andre Lemburg CEO eGenix.com Software GmbH _______________________________________________________________________ eGenix.com -- Makers of the Python mx Extensions: mxDateTime,mxODBC,... Python Consulting: http://www.egenix.com/ Python Software: http://www.egenix.com/files/python/ From loewis@users.sourceforge.net Wed Dec 11 12:52:01 2002 From: loewis@users.sourceforge.net (loewis@users.sourceforge.net) Date: Wed, 11 Dec 2002 04:52:01 -0800 Subject: [Python-checkins] python/dist/src configure,1.363,1.364 configure.in,1.374,1.375 Message-ID: Update of /cvsroot/python/python/dist/src In directory sc8-pr-cvs1:/tmp/cvs-serv23191 Modified Files: configure configure.in Log Message: Patch #651289: Fix quoting errors. Index: configure =================================================================== RCS file: /cvsroot/python/python/dist/src/configure,v retrieving revision 1.363 retrieving revision 1.364 diff -C2 -d -r1.363 -r1.364 *** configure 2 Dec 2002 22:23:52 -0000 1.363 --- configure 11 Dec 2002 12:51:56 -0000 1.364 *************** *** 1,4 **** #! /bin/sh ! # From configure.in Revision: 1.373 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.53 for python 2.3. --- 1,4 ---- #! /bin/sh ! # From configure.in Revision: 1.374 . # Guess values for system-dependent variables and create Makefiles. # Generated by GNU Autoconf 2.53 for python 2.3. *************** *** 9301,9308 **** OpenUNIX*|UnixWare*) if test "$GCC" = "yes" ! then LDSHARED="$(CC) -shared" ! else LDSHARED="$(CC) -G" fi;; ! SCO_SV*) LDSHARED="$(CC) -Wl,-G,-Bexport";; Monterey*) LDSHARED="cc -G -dy -Bdynamic -Bexport -L/usr/lib/ia64l64";; CYGWIN*) LDSHARED="gcc -shared -Wl,--enable-auto-image-base";; --- 9301,9308 ---- OpenUNIX*|UnixWare*) if test "$GCC" = "yes" ! then LDSHARED='$(CC) -shared' ! else LDSHARED='$(CC) -G' fi;; ! SCO_SV*) LDSHARED='$(CC) -Wl,-G,-Bexport';; Monterey*) LDSHARED="cc -G -dy -Bdynamic -Bexport -L/usr/lib/ia64l64";; CYGWIN*) LDSHARED="gcc -shared -Wl,--enable-auto-image-base";; Index: configure.in =================================================================== RCS file: /cvsroot/python/python/dist/src/configure.in,v retrieving revision 1.374 retrieving revision 1.375 diff -C2 -d -r1.374 -r1.375 *** configure.in 2 Dec 2002 22:23:56 -0000 1.374 --- configure.in 11 Dec 2002 12:51:58 -0000 1.375 *************** *** 1030,1037 **** OpenUNIX*|UnixWare*) if test "$GCC" = "yes" ! then LDSHARED="$(CC) -shared" ! else LDSHARED="$(CC) -G" fi;; ! SCO_SV*) LDSHARED="$(CC) -Wl,-G,-Bexport";; Monterey*) LDSHARED="cc -G -dy -Bdynamic -Bexport -L/usr/lib/ia64l64";; CYGWIN*) LDSHARED="gcc -shared -Wl,--enable-auto-image-base";; --- 1030,1037 ---- OpenUNIX*|UnixWare*) if test "$GCC" = "yes" ! then LDSHARED='$(CC) -shared' ! else LDSHARED='$(CC) -G' fi;; ! SCO_SV*) LDSHARED='$(CC) -Wl,-G,-Bexport';; Monterey*) LDSHARED="cc -G -dy -Bdynamic -Bexport -L/usr/lib/ia64l64";; CYGWIN*) LDSHARED="gcc -shared -Wl,--enable-auto-image-base";; From loewis@users.sourceforge.net Wed Dec 11 12:55:57 2002 From: loewis@users.sourceforge.net (loewis@users.sourceforge.net) Date: Wed, 11 Dec 2002 04:55:57 -0800 Subject: [Python-checkins] python/dist/src/Doc/lib libposixpath.tex,1.29,1.30 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/lib In directory sc8-pr-cvs1:/tmp/cvs-serv24345 Modified Files: libposixpath.tex Log Message: Patch #651006: Better explain what component might be empty. Index: libposixpath.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libposixpath.tex,v retrieving revision 1.29 retrieving revision 1.30 diff -C2 -d -r1.29 -r1.30 *** libposixpath.tex 8 Oct 2002 02:44:29 -0000 1.29 --- libposixpath.tex 11 Dec 2002 12:55:53 -0000 1.30 *************** *** 124,128 **** continues. The return value is the concatenation of \var{path1}, and optionally \var{path2}, etc., with exactly one directory separator ! (\code{os.sep}) inserted between components, unless \var{path} is empty. Note that on Windows, since there is a current directory for each drive, \function{os.path.join("c:", "foo")} represents a path --- 124,128 ---- continues. The return value is the concatenation of \var{path1}, and optionally \var{path2}, etc., with exactly one directory separator ! (\code{os.sep}) inserted between components, unless \var{path2} is empty. Note that on Windows, since there is a current directory for each drive, \function{os.path.join("c:", "foo")} represents a path From loewis@users.sourceforge.net Wed Dec 11 13:06:55 2002 From: loewis@users.sourceforge.net (loewis@users.sourceforge.net) Date: Wed, 11 Dec 2002 05:06:55 -0800 Subject: [Python-checkins] python/dist/src/Objects fileobject.c,2.170,2.171 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv27678 Modified Files: fileobject.c Log Message: Patch #650834: Document 'U' in file mode, remove stale variables. Index: fileobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/fileobject.c,v retrieving revision 2.170 retrieving revision 2.171 diff -C2 -d -r2.170 -r2.171 *** fileobject.c 21 Nov 2002 23:52:35 -0000 2.170 --- fileobject.c 11 Dec 2002 13:06:53 -0000 2.171 *************** *** 1615,1619 **** "flag indicating that a space needs to be printed; used by print"}, {"mode", T_OBJECT, OFF(f_mode), RO, ! "file mode ('r', 'w', 'a', possibly with 'b' or '+' added)"}, {"name", T_OBJECT, OFF(f_name), RO, "file name"}, --- 1615,1619 ---- "flag indicating that a space needs to be printed; used by print"}, {"mode", T_OBJECT, OFF(f_mode), RO, ! "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"}, {"name", T_OBJECT, OFF(f_name), RO, "file name"}, *************** *** 1768,1777 **** PyStringObject* l; - int i; - if (f->f_fp == NULL) return err_closed(); - - i = f->f_softspace; l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE); --- 1768,1773 ---- From loewis@users.sourceforge.net Wed Dec 11 13:11:00 2002 From: loewis@users.sourceforge.net (loewis@users.sourceforge.net) Date: Wed, 11 Dec 2002 05:11:00 -0800 Subject: [Python-checkins] python/dist/src/Modules socketmodule.c,1.248,1.249 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv28730 Modified Files: socketmodule.c Log Message: Patch #650422: Use Posix AF_ constants instead of PF_ ones. Index: socketmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/socketmodule.c,v retrieving revision 1.248 retrieving revision 1.249 diff -C2 -d -r1.248 -r1.249 *** socketmodule.c 6 Dec 2002 12:57:26 -0000 1.248 --- socketmodule.c 11 Dec 2002 13:10:57 -0000 1.249 *************** *** 662,666 **** if (name[0] == '<' && strcmp(name, "") == 0) { struct sockaddr_in *sin; ! if (af != PF_INET && af != PF_UNSPEC) { PyErr_SetString(socket_error, "address family mismatched"); --- 662,666 ---- if (name[0] == '<' && strcmp(name, "") == 0) { struct sockaddr_in *sin; ! if (af != AF_INET && af != AF_UNSPEC) { PyErr_SetString(socket_error, "address family mismatched"); *************** *** 2351,2355 **** if (!PyArg_ParseTuple(args, "s:gethostbyname_ex", &name)) return NULL; ! if (setipaddr(name, (struct sockaddr *)&addr, sizeof(addr), PF_INET) < 0) return NULL; Py_BEGIN_ALLOW_THREADS --- 2351,2355 ---- if (!PyArg_ParseTuple(args, "s:gethostbyname_ex", &name)) return NULL; ! if (setipaddr(name, (struct sockaddr *)&addr, sizeof(addr), AF_INET) < 0) return NULL; Py_BEGIN_ALLOW_THREADS *************** *** 2426,2430 **** if (!PyArg_ParseTuple(args, "s:gethostbyaddr", &ip_num)) return NULL; ! af = PF_UNSPEC; if (setipaddr(ip_num, sa, sizeof(addr), af) < 0) return NULL; --- 2426,2430 ---- if (!PyArg_ParseTuple(args, "s:gethostbyaddr", &ip_num)) return NULL; ! af = AF_UNSPEC; if (setipaddr(ip_num, sa, sizeof(addr), af) < 0) return NULL; *************** *** 2775,2779 **** family = socktype = protocol = flags = 0; ! family = PF_UNSPEC; if (!PyArg_ParseTuple(args, "zO|iiii:getaddrinfo", &hptr, &pobj, &family, &socktype, --- 2775,2779 ---- family = socktype = protocol = flags = 0; ! family = AF_UNSPEC; if (!PyArg_ParseTuple(args, "zO|iiii:getaddrinfo", &hptr, &pobj, &family, &socktype, *************** *** 2862,2866 **** PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port); memset(&hints, 0, sizeof(hints)); ! hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; /* make numeric port happy */ error = getaddrinfo(hostp, pbuf, &hints, &res); --- 2862,2866 ---- PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port); memset(&hints, 0, sizeof(hints)); ! hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; /* make numeric port happy */ error = getaddrinfo(hostp, pbuf, &hints, &res); *************** *** 3251,3255 **** --- 3251,3257 ---- PyModule_AddIntConstant(m, "SOCK_RAW", SOCK_RAW); PyModule_AddIntConstant(m, "SOCK_SEQPACKET", SOCK_SEQPACKET); + #if defined(SOCK_RDM) PyModule_AddIntConstant(m, "SOCK_RDM", SOCK_RDM); + #endif #endif From loewis@users.sourceforge.net Wed Dec 11 13:12:32 2002 From: loewis@users.sourceforge.net (loewis@users.sourceforge.net) Date: Wed, 11 Dec 2002 05:12:32 -0800 Subject: [Python-checkins] python/dist/src/Python thread_pthread.h,2.42,2.43 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv29274 Modified Files: thread_pthread.h Log Message: Patch #650415: Avoid redefinition of macros. Index: thread_pthread.h =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/thread_pthread.h,v retrieving revision 2.42 retrieving revision 2.43 diff -C2 -d -r2.42 -r2.43 *** thread_pthread.h 2 Dec 2002 22:17:01 -0000 2.42 --- thread_pthread.h 11 Dec 2002 13:12:30 -0000 2.43 *************** *** 80,90 **** --- 80,102 ---- #if defined(PY_PTHREAD_D4) || defined(PY_PTHREAD_D7) + #if !defined(pthread_attr_default) # define pthread_attr_default pthread_attr_default + #endif + #if !defined(pthread_mutexattr_default) # define pthread_mutexattr_default pthread_mutexattr_default + #endif + #if !defined(pthread_condattr_default) # define pthread_condattr_default pthread_condattr_default + #endif #elif defined(PY_PTHREAD_STD) || defined(PY_PTHREAD_D6) + #if !defined(pthread_attr_default) # define pthread_attr_default ((pthread_attr_t *)NULL) + #endif + #if !defined(pthread_mutexattr_default) # define pthread_mutexattr_default ((pthread_mutexattr_t *)NULL) + #endif + #if !defined(pthread_condattr_default) # define pthread_condattr_default ((pthread_condattr_t *)NULL) + #endif #endif From loewis@users.sourceforge.net Wed Dec 11 13:21:14 2002 From: loewis@users.sourceforge.net (loewis@users.sourceforge.net) Date: Wed, 11 Dec 2002 05:21:14 -0800 Subject: [Python-checkins] python/dist/src/Include dictobject.h,2.25,2.26 Message-ID: Update of /cvsroot/python/python/dist/src/Include In directory sc8-pr-cvs1:/tmp/cvs-serv31895/Include Modified Files: dictobject.h Log Message: Constify char* API. Fixes #651363. 2.2 candidate. Index: dictobject.h =================================================================== RCS file: /cvsroot/python/python/dist/src/Include/dictobject.h,v retrieving revision 2.25 retrieving revision 2.26 diff -C2 -d -r2.25 -r2.26 *** dictobject.h 12 Aug 2002 07:21:56 -0000 2.25 --- dictobject.h 11 Dec 2002 13:21:12 -0000 2.26 *************** *** 117,123 **** int override); ! PyAPI_FUNC(PyObject *) PyDict_GetItemString(PyObject *dp, char *key); ! PyAPI_FUNC(int) PyDict_SetItemString(PyObject *dp, char *key, PyObject *item); ! PyAPI_FUNC(int) PyDict_DelItemString(PyObject *dp, char *key); #ifdef __cplusplus --- 117,123 ---- int override); ! PyAPI_FUNC(PyObject *) PyDict_GetItemString(PyObject *dp, const char *key); ! PyAPI_FUNC(int) PyDict_SetItemString(PyObject *dp, const char *key, PyObject *item); ! PyAPI_FUNC(int) PyDict_DelItemString(PyObject *dp, const char *key); #ifdef __cplusplus From loewis@users.sourceforge.net Wed Dec 11 13:21:14 2002 From: loewis@users.sourceforge.net (loewis@users.sourceforge.net) Date: Wed, 11 Dec 2002 05:21:14 -0800 Subject: [Python-checkins] python/dist/src/Objects dictobject.c,2.136,2.137 Message-ID: Update of /cvsroot/python/python/dist/src/Objects In directory sc8-pr-cvs1:/tmp/cvs-serv31895/Objects Modified Files: dictobject.c Log Message: Constify char* API. Fixes #651363. 2.2 candidate. Index: dictobject.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Objects/dictobject.c,v retrieving revision 2.136 retrieving revision 2.137 diff -C2 -d -r2.136 -r2.137 *** dictobject.c 9 Dec 2002 22:56:13 -0000 2.136 --- dictobject.c 11 Dec 2002 13:21:11 -0000 2.137 *************** *** 1920,1924 **** PyObject * ! PyDict_GetItemString(PyObject *v, char *key) { PyObject *kv, *rv; --- 1920,1924 ---- PyObject * ! PyDict_GetItemString(PyObject *v, const char *key) { PyObject *kv, *rv; *************** *** 1932,1936 **** int ! PyDict_SetItemString(PyObject *v, char *key, PyObject *item) { PyObject *kv; --- 1932,1936 ---- int ! PyDict_SetItemString(PyObject *v, const char *key, PyObject *item) { PyObject *kv; *************** *** 1946,1950 **** int ! PyDict_DelItemString(PyObject *v, char *key) { PyObject *kv; --- 1946,1950 ---- int ! PyDict_DelItemString(PyObject *v, const char *key) { PyObject *kv; From gward@users.sourceforge.net Wed Dec 11 13:54:23 2002 From: gward@users.sourceforge.net (gward@users.sourceforge.net) Date: Wed, 11 Dec 2002 05:54:23 -0800 Subject: [Python-checkins] python/dist/src/Lib textwrap.py,1.20,1.21 Message-ID: Update of /cvsroot/python/python/dist/src/Lib In directory sc8-pr-cvs1:/tmp/cvs-serv12102 Modified Files: textwrap.py Log Message: Tweak generation of unicode_whitespace_trans -- clearer, more efficient. Suggested by MAL. Index: textwrap.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/textwrap.py,v retrieving revision 1.20 retrieving revision 1.21 diff -C2 -d -r1.20 -r1.21 *** textwrap.py 9 Dec 2002 16:26:05 -0000 1.20 --- textwrap.py 11 Dec 2002 13:54:20 -0000 1.21 *************** *** 53,58 **** unicode_whitespace_trans = {} ! for c in string.whitespace: ! unicode_whitespace_trans[ord(unicode(c))] = ord(u' ') # This funky little regex is just the trick for splitting --- 53,59 ---- unicode_whitespace_trans = {} ! uspace = ord(u' ') ! for x in map(ord, string.whitespace): ! unicode_whitespace_trans[x] = uspace # This funky little regex is just the trick for splitting From loewis@users.sourceforge.net Wed Dec 11 14:05:01 2002 From: loewis@users.sourceforge.net (loewis@users.sourceforge.net) Date: Wed, 11 Dec 2002 06:05:01 -0800 Subject: [Python-checkins] python/dist/src/Parser parsetok.c,2.33,2.34 tokenizer.c,2.69,2.70 tokenizer.h,2.19,2.20 Message-ID: Update of /cvsroot/python/python/dist/src/Parser In directory sc8-pr-cvs1:/tmp/cvs-serv15966/Parser Modified Files: parsetok.c tokenizer.c tokenizer.h Log Message: Constify filenames and scripts. Fixes #651362. Index: parsetok.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Parser/parsetok.c,v retrieving revision 2.33 retrieving revision 2.34 diff -C2 -d -r2.33 -r2.34 *** parsetok.c 4 Aug 2002 17:29:52 -0000 2.33 --- parsetok.c 11 Dec 2002 14:04:58 -0000 2.34 *************** *** 16,24 **** /* Forward */ static node *parsetok(struct tok_state *, grammar *, int, perrdetail *, int); ! static void initerr(perrdetail *err_ret, char* filename); /* Parse input coming from a string. Return error code, print some errors. */ node * ! PyParser_ParseString(char *s, grammar *g, int start, perrdetail *err_ret) { return PyParser_ParseStringFlags(s, g, start, err_ret, 0); --- 16,24 ---- /* Forward */ static node *parsetok(struct tok_state *, grammar *, int, perrdetail *, int); ! static void initerr(perrdetail *err_ret, const char* filename); /* Parse input coming from a string. Return error code, print some errors. */ node * ! PyParser_ParseString(const char *s, grammar *g, int start, perrdetail *err_ret) { return PyParser_ParseStringFlags(s, g, start, err_ret, 0); *************** *** 26,30 **** node * ! PyParser_ParseStringFlags(char *s, grammar *g, int start, perrdetail *err_ret, int flags) { --- 26,30 ---- node * ! PyParser_ParseStringFlags(const char *s, grammar *g, int start, perrdetail *err_ret, int flags) { *************** *** 34,38 **** node * ! PyParser_ParseStringFlagsFilename(char *s, char *filename, grammar *g, int start, perrdetail *err_ret, int flags) --- 34,38 ---- node * ! PyParser_ParseStringFlagsFilename(const char *s, const char *filename, grammar *g, int start, perrdetail *err_ret, int flags) *************** *** 61,65 **** node * ! PyParser_ParseFile(FILE *fp, char *filename, grammar *g, int start, char *ps1, char *ps2, perrdetail *err_ret) { --- 61,65 ---- node * ! PyParser_ParseFile(FILE *fp, const char *filename, grammar *g, int start, char *ps1, char *ps2, perrdetail *err_ret) { *************** *** 69,73 **** node * ! PyParser_ParseFileFlags(FILE *fp, char *filename, grammar *g, int start, char *ps1, char *ps2, perrdetail *err_ret, int flags) { --- 69,73 ---- node * ! PyParser_ParseFileFlags(FILE *fp, const char *filename, grammar *g, int start, char *ps1, char *ps2, perrdetail *err_ret, int flags) { *************** *** 202,206 **** static void ! initerr(perrdetail *err_ret, char* filename) { err_ret->error = E_OK; --- 202,206 ---- static void ! initerr(perrdetail *err_ret, const char* filename) { err_ret->error = E_OK; Index: tokenizer.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Parser/tokenizer.c,v retrieving revision 2.69 retrieving revision 2.70 diff -C2 -d -r2.69 -r2.70 *** tokenizer.c 2 Nov 2002 20:43:25 -0000 2.69 --- tokenizer.c 11 Dec 2002 14:04:58 -0000 2.70 *************** *** 387,391 **** PyObject *reader, *stream, *readline; ! stream = PyFile_FromFile(tok->fp, tok->filename, "rb", NULL); if (stream == NULL) return 0; --- 387,392 ---- PyObject *reader, *stream, *readline; ! /* XXX: constify filename argument. */ ! stream = PyFile_FromFile(tok->fp, (char*)tok->filename, "rb", NULL); if (stream == NULL) return 0; *************** *** 592,596 **** struct tok_state * ! PyTokenizer_FromString(char *str) { struct tok_state *tok = tok_new(); --- 593,597 ---- struct tok_state * ! PyTokenizer_FromString(const char *str) { struct tok_state *tok = tok_new(); *************** *** 600,604 **** if (str == NULL) return NULL; ! tok->buf = tok->cur = tok->end = tok->inp = str; return tok; } --- 601,606 ---- if (str == NULL) return NULL; ! /* XXX: constify members. */ ! tok->buf = tok->cur = tok->end = tok->inp = (char*)str; return tok; } Index: tokenizer.h =================================================================== RCS file: /cvsroot/python/python/dist/src/Parser/tokenizer.h,v retrieving revision 2.19 retrieving revision 2.20 diff -C2 -d -r2.19 -r2.20 *** tokenizer.h 3 Sep 2002 11:52:44 -0000 2.19 --- tokenizer.h 11 Dec 2002 14:04:58 -0000 2.20 *************** *** 35,39 **** /* Used to allow free continuations inside them */ /* Stuff for checking on different tab sizes */ ! char *filename; /* For error messages */ int altwarning; /* Issue warning if alternate tabs don't match */ int alterror; /* Issue error if alternate tabs don't match */ --- 35,39 ---- /* Used to allow free continuations inside them */ /* Stuff for checking on different tab sizes */ ! const char *filename; /* For error messages */ int altwarning; /* Issue warning if alternate tabs don't match */ int alterror; /* Issue error if alternate tabs don't match */ *************** *** 55,59 **** }; ! extern struct tok_state *PyTokenizer_FromString(char *); extern struct tok_state *PyTokenizer_FromFile(FILE *, char *, char *); extern void PyTokenizer_Free(struct tok_state *); --- 55,59 ---- }; ! extern struct tok_state *PyTokenizer_FromString(const char *); extern struct tok_state *PyTokenizer_FromFile(FILE *, char *, char *); extern void PyTokenizer_Free(struct tok_state *); From loewis@users.sourceforge.net Wed Dec 11 14:05:01 2002 From: loewis@users.sourceforge.net (loewis@users.sourceforge.net) Date: Wed, 11 Dec 2002 06:05:01 -0800 Subject: [Python-checkins] python/dist/src/Python compile.c,2.265,2.266 errors.c,2.74,2.75 future.c,2.12,2.13 pythonrun.c,2.169,2.170 Message-ID: Update of /cvsroot/python/python/dist/src/Python In directory sc8-pr-cvs1:/tmp/cvs-serv15966/Python Modified Files: compile.c errors.c future.c pythonrun.c Log Message: Constify filenames and scripts. Fixes #651362. Index: compile.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/compile.c,v retrieving revision 2.265 retrieving revision 2.266 diff -C2 -d -r2.265 -r2.266 *** compile.c 21 Nov 2002 20:13:40 -0000 2.265 --- compile.c 11 Dec 2002 14:04:58 -0000 2.266 *************** *** 473,477 **** int c_block[CO_MAXBLOCKS]; /* stack of block types */ int c_nblocks; /* current block stack level */ ! char *c_filename; /* filename of current node */ char *c_name; /* name of object (e.g. function) */ int c_lineno; /* Current line number */ --- 473,477 ---- int c_block[CO_MAXBLOCKS]; /* stack of block types */ int c_nblocks; /* current block stack level */ ! const char *c_filename; /* filename of current node */ char *c_name; /* name of object (e.g. function) */ int c_lineno; /* Current line number */ *************** *** 575,580 **** /* Prototype forward declarations */ ! static int issue_warning(char *, char *, int); ! static int com_init(struct compiling *, char *); static void com_free(struct compiling *); static void com_push(struct compiling *, int); --- 575,580 ---- /* Prototype forward declarations */ ! static int issue_warning(const char *, const char *, int); ! static int com_init(struct compiling *, const char *); static void com_free(struct compiling *); static void com_push(struct compiling *, int); *************** *** 598,602 **** static void com_assign_name(struct compiling *, node *, int); static PyCodeObject *icompile(node *, struct compiling *); ! static PyCodeObject *jcompile(node *, char *, struct compiling *, PyCompilerFlags *); static PyObject *parsestrplus(struct compiling*, node *); --- 598,602 ---- static void com_assign_name(struct compiling *, node *, int); static PyCodeObject *icompile(node *, struct compiling *); ! static PyCodeObject *jcompile(node *, const char *, struct compiling *, PyCompilerFlags *); static PyObject *parsestrplus(struct compiling*, node *); *************** *** 655,659 **** static int ! com_init(struct compiling *c, char *filename) { memset((void *)c, '\0', sizeof(struct compiling)); --- 655,659 ---- static int ! com_init(struct compiling *c, const char *filename) { memset((void *)c, '\0', sizeof(struct compiling)); *************** *** 1183,1187 **** "will return positive values " "in Python 2.4 and up", ! c->c_filename, c->c_lineno, NULL, --- 1183,1189 ---- "will return positive values " "in Python 2.4 and up", ! /* XXX: Give WarnExplicit ! a const char* argument. */ ! (char*)c->c_filename, c->c_lineno, NULL, *************** *** 4143,4147 **** PyCodeObject * ! PyNode_Compile(node *n, char *filename) { return PyNode_CompileFlags(n, filename, NULL); --- 4145,4149 ---- PyCodeObject * ! PyNode_Compile(node *n, const char *filename) { return PyNode_CompileFlags(n, filename, NULL); *************** *** 4149,4153 **** PyCodeObject * ! PyNode_CompileFlags(node *n, char *filename, PyCompilerFlags *flags) { return jcompile(n, filename, NULL, flags); --- 4151,4155 ---- PyCodeObject * ! PyNode_CompileFlags(node *n, const char *filename, PyCompilerFlags *flags) { return jcompile(n, filename, NULL, flags); *************** *** 4155,4159 **** struct symtable * ! PyNode_CompileSymtable(node *n, char *filename) { struct symtable *st; --- 4157,4161 ---- struct symtable * ! PyNode_CompileSymtable(node *n, const char *filename) { struct symtable *st; *************** *** 4192,4196 **** static PyCodeObject * ! jcompile(node *n, char *filename, struct compiling *base, PyCompilerFlags *flags) { --- 4194,4198 ---- static PyCodeObject * ! jcompile(node *n, const char *filename, struct compiling *base, PyCompilerFlags *flags) { *************** *** 4352,4356 **** static int ! issue_warning(char *msg, char *filename, int lineno) { if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, filename, --- 4354,4358 ---- static int ! issue_warning(const char *msg, const char *filename, int lineno) { if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, filename, Index: errors.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/errors.c,v retrieving revision 2.74 retrieving revision 2.75 diff -C2 -d -r2.74 -r2.75 *** errors.c 4 Oct 2002 00:13:02 -0000 2.74 --- errors.c 11 Dec 2002 14:04:59 -0000 2.75 *************** *** 638,644 **** /* Warning with explicit origin */ int ! PyErr_WarnExplicit(PyObject *category, char *message, ! char *filename, int lineno, ! char *module, PyObject *registry) { PyObject *mod, *dict, *func = NULL; --- 638,644 ---- /* Warning with explicit origin */ int ! PyErr_WarnExplicit(PyObject *category, const char *message, ! const char *filename, int lineno, ! const char *module, PyObject *registry) { PyObject *mod, *dict, *func = NULL; *************** *** 680,684 **** void ! PyErr_SyntaxLocation(char *filename, int lineno) { PyObject *exc, *v, *tb, *tmp; --- 680,684 ---- void ! PyErr_SyntaxLocation(const char *filename, int lineno) { PyObject *exc, *v, *tb, *tmp; *************** *** 744,748 **** PyObject * ! PyErr_ProgramText(char *filename, int lineno) { FILE *fp; --- 744,748 ---- PyObject * ! PyErr_ProgramText(const char *filename, int lineno) { FILE *fp; Index: future.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/future.c,v retrieving revision 2.12 retrieving revision 2.13 diff -C2 -d -r2.12 -r2.13 *** future.c 12 Apr 2002 01:20:10 -0000 2.12 --- future.c 11 Dec 2002 14:04:59 -0000 2.13 *************** *** 15,19 **** static int ! future_check_features(PyFutureFeatures *ff, node *n, char *filename) { int i; --- 15,19 ---- static int ! future_check_features(PyFutureFeatures *ff, node *n, const char *filename) { int i; *************** *** 55,59 **** static void ! future_error(node *n, char *filename) { PyErr_SetString(PyExc_SyntaxError, --- 55,59 ---- static void ! future_error(node *n, const char *filename) { PyErr_SetString(PyExc_SyntaxError, *************** *** 90,94 **** static int ! future_parse(PyFutureFeatures *ff, node *n, char *filename) { int i, r; --- 90,94 ---- static int ! future_parse(PyFutureFeatures *ff, node *n, const char *filename) { int i, r; *************** *** 241,245 **** PyFutureFeatures * ! PyNode_Future(node *n, char *filename) { PyFutureFeatures *ff; --- 241,245 ---- PyFutureFeatures * ! PyNode_Future(node *n, const char *filename) { PyFutureFeatures *ff; Index: pythonrun.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Python/pythonrun.c,v retrieving revision 2.169 retrieving revision 2.170 diff -C2 -d -r2.169 -r2.170 *** pythonrun.c 17 Nov 2002 17:52:44 -0000 2.169 --- pythonrun.c 11 Dec 2002 14:04:59 -0000 2.170 *************** *** 33,41 **** static void initmain(void); static void initsite(void); ! static PyObject *run_err_node(node *, char *, PyObject *, PyObject *, PyCompilerFlags *); ! static PyObject *run_node(node *, char *, PyObject *, PyObject *, PyCompilerFlags *); ! static PyObject *run_pyc_file(FILE *, char *, PyObject *, PyObject *, PyCompilerFlags *); static void err_input(perrdetail *); --- 33,41 ---- static void initmain(void); static void initsite(void); ! static PyObject *run_err_node(node *, const char *, PyObject *, PyObject *, PyCompilerFlags *); ! static PyObject *run_node(node *, const char *, PyObject *, PyObject *, PyCompilerFlags *); ! static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *, PyCompilerFlags *); static void err_input(perrdetail *); *************** *** 459,463 **** int ! PyRun_AnyFile(FILE *fp, char *filename) { return PyRun_AnyFileExFlags(fp, filename, 0, NULL); --- 459,463 ---- int ! PyRun_AnyFile(FILE *fp, const char *filename) { return PyRun_AnyFileExFlags(fp, filename, 0, NULL); *************** *** 465,469 **** int ! PyRun_AnyFileFlags(FILE *fp, char *filename, PyCompilerFlags *flags) { return PyRun_AnyFileExFlags(fp, filename, 0, flags); --- 465,469 ---- int ! PyRun_AnyFileFlags(FILE *fp, const char *filename, PyCompilerFlags *flags) { return PyRun_AnyFileExFlags(fp, filename, 0, flags); *************** *** 471,475 **** int ! PyRun_AnyFileEx(FILE *fp, char *filename, int closeit) { return PyRun_AnyFileExFlags(fp, filename, closeit, NULL); --- 471,475 ---- int ! PyRun_AnyFileEx(FILE *fp, const char *filename, int closeit) { return PyRun_AnyFileExFlags(fp, filename, closeit, NULL); *************** *** 477,481 **** int ! PyRun_AnyFileExFlags(FILE *fp, char *filename, int closeit, PyCompilerFlags *flags) { --- 477,481 ---- int ! PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags) { *************** *** 493,497 **** int ! PyRun_InteractiveLoop(FILE *fp, char *filename) { return PyRun_InteractiveLoopFlags(fp, filename, NULL); --- 493,497 ---- int ! PyRun_InteractiveLoop(FILE *fp, const char *filename) { return PyRun_InteractiveLoopFlags(fp, filename, NULL); *************** *** 499,503 **** int ! PyRun_InteractiveLoopFlags(FILE *fp, char *filename, PyCompilerFlags *flags) { PyObject *v; --- 499,503 ---- int ! PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags) { PyObject *v; *************** *** 534,538 **** int ! PyRun_InteractiveOne(FILE *fp, char *filename) { return PyRun_InteractiveOneFlags(fp, filename, NULL); --- 534,538 ---- int ! PyRun_InteractiveOne(FILE *fp, const char *filename) { return PyRun_InteractiveOneFlags(fp, filename, NULL); *************** *** 549,553 **** int ! PyRun_InteractiveOneFlags(FILE *fp, char *filename, PyCompilerFlags *flags) { PyObject *m, *d, *v, *w; --- 549,553 ---- int ! PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags) { PyObject *m, *d, *v, *w; *************** *** 603,607 **** int ! PyRun_SimpleFile(FILE *fp, char *filename) { return PyRun_SimpleFileEx(fp, filename, 0); --- 603,607 ---- int ! PyRun_SimpleFile(FILE *fp, const char *filename) { return PyRun_SimpleFileEx(fp, filename, 0); *************** *** 612,616 **** static int ! maybe_pyc_file(FILE *fp, char* filename, char* ext, int closeit) { if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0) --- 612,616 ---- static int ! maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit) { if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0) *************** *** 656,660 **** int ! PyRun_SimpleFileEx(FILE *fp, char *filename, int closeit) { return PyRun_SimpleFileExFlags(fp, filename, closeit, NULL); --- 656,660 ---- int ! PyRun_SimpleFileEx(FILE *fp, const char *filename, int closeit) { return PyRun_SimpleFileExFlags(fp, filename, closeit, NULL); *************** *** 662,670 **** int ! PyRun_SimpleFileExFlags(FILE *fp, char *filename, int closeit, PyCompilerFlags *flags) { PyObject *m, *d, *v; ! char *ext; m = PyImport_AddModule("__main__"); --- 662,670 ---- int ! PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit, PyCompilerFlags *flags) { PyObject *m, *d, *v; ! const char *ext; m = PyImport_AddModule("__main__"); *************** *** 710,714 **** int ! PyRun_SimpleString(char *command) { return PyRun_SimpleStringFlags(command, NULL); --- 710,714 ---- int ! PyRun_SimpleString(const char *command) { return PyRun_SimpleStringFlags(command, NULL); *************** *** 716,720 **** int ! PyRun_SimpleStringFlags(char *command, PyCompilerFlags *flags) { PyObject *m, *d, *v; --- 716,720 ---- int ! PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags) { PyObject *m, *d, *v; *************** *** 735,740 **** static int ! parse_syntax_error(PyObject *err, PyObject **message, char **filename, ! int *lineno, int *offset, char **text) { long hold; --- 735,740 ---- static int ! parse_syntax_error(PyObject *err, PyObject **message, const char **filename, ! int *lineno, int *offset, const char **text) { long hold; *************** *** 805,809 **** static void ! print_error_text(PyObject *f, int offset, char *text) { char *nl; --- 805,809 ---- static void ! print_error_text(PyObject *f, int offset, const char *text) { char *nl; *************** *** 937,941 **** { PyObject *message; ! char *filename, *text; int lineno, offset; if (!parse_syntax_error(v, &message, &filename, --- 937,941 ---- { PyObject *message; ! const char *filename, *text; int lineno, offset; if (!parse_syntax_error(v, &message, &filename, *************** *** 1017,1021 **** PyObject * ! PyRun_String(char *str, int start, PyObject *globals, PyObject *locals) { return run_err_node(PyParser_SimpleParseString(str, start), --- 1017,1021 ---- PyObject * ! PyRun_String(const char *str, int start, PyObject *globals, PyObject *locals) { return run_err_node(PyParser_SimpleParseString(str, start), *************** *** 1024,1028 **** PyObject * ! PyRun_File(FILE *fp, char *filename, int start, PyObject *globals, PyObject *locals) { --- 1024,1028 ---- PyObject * ! PyRun_File(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals) { *************** *** 1031,1035 **** PyObject * ! PyRun_FileEx(FILE *fp, char *filename, int start, PyObject *globals, PyObject *locals, int closeit) { --- 1031,1035 ---- PyObject * ! PyRun_FileEx(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, int closeit) { *************** *** 1041,1045 **** PyObject * ! PyRun_StringFlags(char *str, int start, PyObject *globals, PyObject *locals, PyCompilerFlags *flags) { --- 1041,1045 ---- PyObject * ! PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals, PyCompilerFlags *flags) { *************** *** 1050,1054 **** PyObject * ! PyRun_FileFlags(FILE *fp, char *filename, int start, PyObject *globals, PyObject *locals, PyCompilerFlags *flags) { --- 1050,1054 ---- PyObject * ! PyRun_FileFlags(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, PyCompilerFlags *flags) { *************** *** 1058,1062 **** PyObject * ! PyRun_FileExFlags(FILE *fp, char *filename, int start, PyObject *globals, PyObject *locals, int closeit, PyCompilerFlags *flags) { --- 1058,1062 ---- PyObject * ! PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals, PyObject *locals, int closeit, PyCompilerFlags *flags) { *************** *** 1069,1073 **** static PyObject * ! run_err_node(node *n, char *filename, PyObject *globals, PyObject *locals, PyCompilerFlags *flags) { --- 1069,1073 ---- static PyObject * ! run_err_node(node *n, const char *filename, PyObject *globals, PyObject *locals, PyCompilerFlags *flags) { *************** *** 1078,1082 **** static PyObject * ! run_node(node *n, char *filename, PyObject *globals, PyObject *locals, PyCompilerFlags *flags) { --- 1078,1082 ---- static PyObject * ! run_node(node *n, const char *filename, PyObject *globals, PyObject *locals, PyCompilerFlags *flags) { *************** *** 1093,1097 **** static PyObject * ! run_pyc_file(FILE *fp, char *filename, PyObject *globals, PyObject *locals, PyCompilerFlags *flags) { --- 1093,1097 ---- static PyObject * ! run_pyc_file(FILE *fp, const char *filename, PyObject *globals, PyObject *locals, PyCompilerFlags *flags) { *************** *** 1125,1129 **** PyObject * ! Py_CompileString(char *str, char *filename, int start) { return Py_CompileStringFlags(str, filename, start, NULL); --- 1125,1129 ---- PyObject * ! Py_CompileString(const char *str, const char *filename, int start) { return Py_CompileStringFlags(str, filename, start, NULL); *************** *** 1131,1135 **** PyObject * ! Py_CompileStringFlags(char *str, char *filename, int start, PyCompilerFlags *flags) { --- 1131,1135 ---- PyObject * ! Py_CompileStringFlags(const char *str, const char *filename, int start, PyCompilerFlags *flags) { *************** *** 1147,1151 **** struct symtable * ! Py_SymtableString(char *str, char *filename, int start) { node *n; --- 1147,1151 ---- struct symtable * ! Py_SymtableString(const char *str, const char *filename, int start) { node *n; *************** *** 1163,1167 **** node * ! PyParser_SimpleParseFileFlags(FILE *fp, char *filename, int start, int flags) { node *n; --- 1163,1167 ---- node * ! PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags) { node *n; *************** *** 1175,1179 **** node * ! PyParser_SimpleParseFile(FILE *fp, char *filename, int start) { return PyParser_SimpleParseFileFlags(fp, filename, start, 0); --- 1175,1179 ---- node * ! PyParser_SimpleParseFile(FILE *fp, const char *filename, int start) { return PyParser_SimpleParseFileFlags(fp, filename, start, 0); *************** *** 1183,1187 **** node * ! PyParser_SimpleParseStringFlags(char *str, int start, int flags) { node *n; --- 1183,1187 ---- node * ! PyParser_SimpleParseStringFlags(const char *str, int start, int flags) { node *n; *************** *** 1195,1199 **** node * ! PyParser_SimpleParseString(char *str, int start) { return PyParser_SimpleParseStringFlags(str, start, 0); --- 1195,1199 ---- node * ! PyParser_SimpleParseString(const char *str, int start) { return PyParser_SimpleParseStringFlags(str, start, 0); *************** *** 1201,1205 **** node * ! PyParser_SimpleParseStringFlagsFilename(char *str, char *filename, int start, int flags) { --- 1201,1205 ---- node * ! PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename, int start, int flags) { *************** *** 1216,1220 **** node * ! PyParser_SimpleParseStringFilename(char *str, char *filename, int start) { return PyParser_SimpleParseStringFlagsFilename(str, filename, --- 1216,1220 ---- node * ! PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start) { return PyParser_SimpleParseStringFlagsFilename(str, filename, *************** *** 1430,1434 **** */ int ! Py_FdIsInteractive(FILE *fp, char *filename) { if (isatty((int)fileno(fp))) --- 1430,1434 ---- */ int ! Py_FdIsInteractive(FILE *fp, const char *filename) { if (isatty((int)fileno(fp))) From loewis@users.sourceforge.net Wed Dec 11 14:05:00 2002 From: loewis@users.sourceforge.net (loewis@users.sourceforge.net) Date: Wed, 11 Dec 2002 06:05:00 -0800 Subject: [Python-checkins] python/dist/src/Include compile.h,2.38,2.39 parsetok.h,2.19,2.20 pyerrors.h,2.63,2.64 pythonrun.h,2.55,2.56 symtable.h,2.10,2.11 Message-ID: Update of /cvsroot/python/python/dist/src/Include In directory sc8-pr-cvs1:/tmp/cvs-serv15966/Include Modified Files: compile.h parsetok.h pyerrors.h pythonrun.h symtable.h Log Message: Constify filenames and scripts. Fixes #651362. Index: compile.h =================================================================== RCS file: /cvsroot/python/python/dist/src/Include/compile.h,v retrieving revision 2.38 retrieving revision 2.39 diff -C2 -d -r2.38 -r2.39 *** compile.h 12 Aug 2002 07:21:56 -0000 2.38 --- compile.h 11 Dec 2002 14:04:57 -0000 2.39 *************** *** 53,57 **** /* Public interface */ struct _node; /* Declare the existence of this type */ ! PyAPI_FUNC(PyCodeObject *) PyNode_Compile(struct _node *, char *); PyAPI_FUNC(PyCodeObject *) PyCode_New( int, int, int, int, PyObject *, PyObject *, PyObject *, PyObject *, --- 53,57 ---- /* Public interface */ struct _node; /* Declare the existence of this type */ ! PyAPI_FUNC(PyCodeObject *) PyNode_Compile(struct _node *, const char *); PyAPI_FUNC(PyCodeObject *) PyCode_New( int, int, int, int, PyObject *, PyObject *, PyObject *, PyObject *, *************** *** 68,73 **** } PyFutureFeatures; ! PyAPI_FUNC(PyFutureFeatures *) PyNode_Future(struct _node *, char *); ! PyAPI_FUNC(PyCodeObject *) PyNode_CompileFlags(struct _node *, char *, PyCompilerFlags *); --- 68,73 ---- } PyFutureFeatures; ! PyAPI_FUNC(PyFutureFeatures *) PyNode_Future(struct _node *, const char *); ! PyAPI_FUNC(PyCodeObject *) PyNode_CompileFlags(struct _node *, const char *, PyCompilerFlags *); Index: parsetok.h =================================================================== RCS file: /cvsroot/python/python/dist/src/Include/parsetok.h,v retrieving revision 2.19 retrieving revision 2.20 diff -C2 -d -r2.19 -r2.20 *** parsetok.h 12 Aug 2002 07:21:57 -0000 2.19 --- parsetok.h 11 Dec 2002 14:04:57 -0000 2.20 *************** *** 10,14 **** typedef struct { int error; ! char *filename; int lineno; int offset; --- 10,14 ---- typedef struct { int error; ! const char *filename; int lineno; int offset; *************** *** 22,38 **** #endif ! PyAPI_FUNC(node *) PyParser_ParseString(char *, grammar *, int, perrdetail *); ! PyAPI_FUNC(node *) PyParser_ParseFile (FILE *, char *, grammar *, int, char *, char *, perrdetail *); ! PyAPI_FUNC(node *) PyParser_ParseStringFlags(char *, grammar *, int, perrdetail *, int); ! PyAPI_FUNC(node *) PyParser_ParseFileFlags(FILE *, char *, grammar *, int, char *, char *, perrdetail *, int); ! PyAPI_FUNC(node *) PyParser_ParseStringFlagsFilename(char *, ! char *, grammar *, int, perrdetail *, int); --- 22,38 ---- #endif ! PyAPI_FUNC(node *) PyParser_ParseString(const char *, grammar *, int, perrdetail *); ! PyAPI_FUNC(node *) PyParser_ParseFile (FILE *, const char *, grammar *, int, char *, char *, perrdetail *); ! PyAPI_FUNC(node *) PyParser_ParseStringFlags(const char *, grammar *, int, perrdetail *, int); ! PyAPI_FUNC(node *) PyParser_ParseFileFlags(FILE *, const char *, grammar *, int, char *, char *, perrdetail *, int); ! PyAPI_FUNC(node *) PyParser_ParseStringFlagsFilename(const char *, ! const char *, grammar *, int, perrdetail *, int); Index: pyerrors.h =================================================================== RCS file: /cvsroot/python/python/dist/src/Include/pyerrors.h,v retrieving revision 2.63 retrieving revision 2.64 diff -C2 -d -r2.63 -r2.64 *** pyerrors.h 6 Dec 2002 12:48:44 -0000 2.63 --- pyerrors.h 11 Dec 2002 14:04:57 -0000 2.64 *************** *** 131,136 **** /* Issue a warning or exception */ PyAPI_FUNC(int) PyErr_Warn(PyObject *, char *); ! PyAPI_FUNC(int) PyErr_WarnExplicit(PyObject *, char *, ! char *, int, char *, PyObject *); /* In sigcheck.c or signalmodule.c */ --- 131,137 ---- /* Issue a warning or exception */ PyAPI_FUNC(int) PyErr_Warn(PyObject *, char *); ! PyAPI_FUNC(int) PyErr_WarnExplicit(PyObject *, const char *, ! const char *, int, ! const char *, PyObject *); /* In sigcheck.c or signalmodule.c */ *************** *** 139,144 **** /* Support for adding program text to SyntaxErrors */ ! PyAPI_FUNC(void) PyErr_SyntaxLocation(char *, int); ! PyAPI_FUNC(PyObject *) PyErr_ProgramText(char *, int); #ifdef Py_USING_UNICODE --- 140,145 ---- /* Support for adding program text to SyntaxErrors */ ! PyAPI_FUNC(void) PyErr_SyntaxLocation(const char *, int); ! PyAPI_FUNC(PyObject *) PyErr_ProgramText(const char *, int); #ifdef Py_USING_UNICODE Index: pythonrun.h =================================================================== RCS file: /cvsroot/python/python/dist/src/Include/pythonrun.h,v retrieving revision 2.55 retrieving revision 2.56 diff -C2 -d -r2.55 -r2.56 *** pythonrun.h 26 Oct 2002 14:39:09 -0000 2.55 --- pythonrun.h 11 Dec 2002 14:04:58 -0000 2.56 *************** *** 27,71 **** PyAPI_FUNC(void) Py_EndInterpreter(PyThreadState *); ! PyAPI_FUNC(int) PyRun_AnyFile(FILE *, char *); ! PyAPI_FUNC(int) PyRun_AnyFileEx(FILE *, char *, int); ! PyAPI_FUNC(int) PyRun_AnyFileFlags(FILE *, char *, PyCompilerFlags *); ! PyAPI_FUNC(int) PyRun_AnyFileExFlags(FILE *, char *, int, PyCompilerFlags *); ! PyAPI_FUNC(int) PyRun_SimpleString(char *); ! PyAPI_FUNC(int) PyRun_SimpleStringFlags(char *, PyCompilerFlags *); ! PyAPI_FUNC(int) PyRun_SimpleFile(FILE *, char *); ! PyAPI_FUNC(int) PyRun_SimpleFileEx(FILE *, char *, int); ! PyAPI_FUNC(int) PyRun_SimpleFileExFlags(FILE *, char *, int, PyCompilerFlags *); ! PyAPI_FUNC(int) PyRun_InteractiveOne(FILE *, char *); ! PyAPI_FUNC(int) PyRun_InteractiveOneFlags(FILE *, char *, PyCompilerFlags *); ! PyAPI_FUNC(int) PyRun_InteractiveLoop(FILE *, char *); ! PyAPI_FUNC(int) PyRun_InteractiveLoopFlags(FILE *, char *, PyCompilerFlags *); ! PyAPI_FUNC(struct _node *) PyParser_SimpleParseString(char *, int); ! PyAPI_FUNC(struct _node *) PyParser_SimpleParseFile(FILE *, char *, int); ! PyAPI_FUNC(struct _node *) PyParser_SimpleParseStringFlags(char *, int, int); ! PyAPI_FUNC(struct _node *) PyParser_SimpleParseStringFlagsFilename(char *, ! char *, int, int); ! PyAPI_FUNC(struct _node *) PyParser_SimpleParseFileFlags(FILE *, char *, int, int); ! PyAPI_FUNC(PyObject *) PyRun_String(char *, int, PyObject *, PyObject *); ! PyAPI_FUNC(PyObject *) PyRun_File(FILE *, char *, int, PyObject *, PyObject *); ! PyAPI_FUNC(PyObject *) PyRun_FileEx(FILE *, char *, int, PyObject *, PyObject *, int); ! PyAPI_FUNC(PyObject *) PyRun_StringFlags(char *, int, PyObject *, PyObject *, PyCompilerFlags *); ! PyAPI_FUNC(PyObject *) PyRun_FileFlags(FILE *, char *, int, PyObject *, PyObject *, PyCompilerFlags *); ! PyAPI_FUNC(PyObject *) PyRun_FileExFlags(FILE *, char *, int, PyObject *, PyObject *, int, PyCompilerFlags *); ! PyAPI_FUNC(PyObject *) Py_CompileString(char *, char *, int); ! PyAPI_FUNC(PyObject *) Py_CompileStringFlags(char *, char *, int, PyCompilerFlags *); ! PyAPI_FUNC(struct symtable *) Py_SymtableString(char *, char *, int); PyAPI_FUNC(void) PyErr_Print(void); --- 27,71 ---- PyAPI_FUNC(void) Py_EndInterpreter(PyThreadState *); ! PyAPI_FUNC(int) PyRun_AnyFile(FILE *, const char *); ! PyAPI_FUNC(int) PyRun_AnyFileEx(FILE *, const char *, int); ! PyAPI_FUNC(int) PyRun_AnyFileFlags(FILE *, const char *, PyCompilerFlags *); ! PyAPI_FUNC(int) PyRun_AnyFileExFlags(FILE *, const char *, int, PyCompilerFlags *); ! PyAPI_FUNC(int) PyRun_SimpleString(const char *); ! PyAPI_FUNC(int) PyRun_SimpleStringFlags(const char *, PyCompilerFlags *); ! PyAPI_FUNC(int) PyRun_SimpleFile(FILE *, const char *); ! PyAPI_FUNC(int) PyRun_SimpleFileEx(FILE *, const char *, int); ! PyAPI_FUNC(int) PyRun_SimpleFileExFlags(FILE *, const char *, int, PyCompilerFlags *); ! PyAPI_FUNC(int) PyRun_InteractiveOne(FILE *, const char *); ! PyAPI_FUNC(int) PyRun_InteractiveOneFlags(FILE *, const char *, PyCompilerFlags *); ! PyAPI_FUNC(int) PyRun_InteractiveLoop(FILE *, const char *); ! PyAPI_FUNC(int) PyRun_InteractiveLoopFlags(FILE *, const char *, PyCompilerFlags *); ! PyAPI_FUNC(struct _node *) PyParser_SimpleParseString(const char *, int); ! PyAPI_FUNC(struct _node *) PyParser_SimpleParseFile(FILE *, const char *, int); ! PyAPI_FUNC(struct _node *) PyParser_SimpleParseStringFlags(const char *, int, int); ! PyAPI_FUNC(struct _node *) PyParser_SimpleParseStringFlagsFilename(const char *, ! const char *, int, int); ! PyAPI_FUNC(struct _node *) PyParser_SimpleParseFileFlags(FILE *, const char *, int, int); ! PyAPI_FUNC(PyObject *) PyRun_String(const char *, int, PyObject *, PyObject *); ! PyAPI_FUNC(PyObject *) PyRun_File(FILE *, const char *, int, PyObject *, PyObject *); ! PyAPI_FUNC(PyObject *) PyRun_FileEx(FILE *, const char *, int, PyObject *, PyObject *, int); ! PyAPI_FUNC(PyObject *) PyRun_StringFlags(const char *, int, PyObject *, PyObject *, PyCompilerFlags *); ! PyAPI_FUNC(PyObject *) PyRun_FileFlags(FILE *, const char *, int, PyObject *, PyObject *, PyCompilerFlags *); ! PyAPI_FUNC(PyObject *) PyRun_FileExFlags(FILE *, const char *, int, PyObject *, PyObject *, int, PyCompilerFlags *); ! PyAPI_FUNC(PyObject *) Py_CompileString(const char *, const char *, int); ! PyAPI_FUNC(PyObject *) Py_CompileStringFlags(const char *, const char *, int, PyCompilerFlags *); ! PyAPI_FUNC(struct symtable *) Py_SymtableString(const char *, const char *, int); PyAPI_FUNC(void) PyErr_Print(void); *************** *** 77,81 **** PyAPI_FUNC(void) Py_Exit(int); ! PyAPI_FUNC(int) Py_FdIsInteractive(FILE *, char *); /* Bootstrap */ --- 77,81 ---- PyAPI_FUNC(void) Py_Exit(int); ! PyAPI_FUNC(int) Py_FdIsInteractive(FILE *, const char *); /* Bootstrap */ Index: symtable.h =================================================================== RCS file: /cvsroot/python/python/dist/src/Include/symtable.h,v retrieving revision 2.10 retrieving revision 2.11 diff -C2 -d -r2.10 -r2.11 *** symtable.h 12 Aug 2002 07:21:57 -0000 2.10 --- symtable.h 11 Dec 2002 14:04:58 -0000 2.11 *************** *** 21,25 **** struct symtable { int st_pass; /* pass == 1 or 2 */ ! char *st_filename; /* name of file being compiled */ struct _symtable_entry *st_cur; /* current symbol table entry */ PyObject *st_symbols; /* dictionary of symbol table entries */ --- 21,25 ---- struct symtable { int st_pass; /* pass == 1 or 2 */ ! const char *st_filename; /* name of file being compiled */ struct _symtable_entry *st_cur; /* current symbol table entry */ PyObject *st_symbols; /* dictionary of symbol table entries */ *************** *** 58,62 **** char *, int, int); ! PyAPI_FUNC(struct symtable *) PyNode_CompileSymtable(struct _node *, char *); PyAPI_FUNC(void) PySymtable_Free(struct symtable *); --- 58,62 ---- char *, int, int); ! PyAPI_FUNC(struct symtable *) PyNode_CompileSymtable(struct _node *, const char *); PyAPI_FUNC(void) PySymtable_Free(struct symtable *); From gward@users.sourceforge.net Wed Dec 11 14:43:16 2002 From: gward@users.sourceforge.net (gward@users.sourceforge.net) Date: Wed, 11 Dec 2002 06:43:16 -0800 Subject: [Python-checkins] python/dist/src/Modules ossaudiodev.c,1.5,1.6 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv31453 Modified Files: ossaudiodev.c Log Message: Finish expunging the 'linuxaudiodev' name: * rename oss_t to lad_t, Ladtype to OSSType, * rename lad_*() methods to oss_*() * rename lad_methods list to oss_methods Patch and impetus supplied by Nicholas FitzRoy-Dale . Index: ossaudiodev.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/ossaudiodev.c,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** ossaudiodev.c 30 Nov 2002 23:20:09 -0000 1.5 --- ossaudiodev.c 11 Dec 2002 14:43:13 -0000 1.6 *************** *** 52,56 **** int x_ocount; /* Output count */ uint32_t x_afmts; /* Audio formats supported by hardware*/ ! } lad_t; /* XXX several format defined in soundcard.h are not supported, --- 52,56 ---- int x_ocount; /* Output count */ uint32_t x_afmts; /* Audio formats supported by hardware*/ ! } oss_t; /* XXX several format defined in soundcard.h are not supported, *************** *** 76,87 **** static int n_audio_types = sizeof(audio_types) / sizeof(audio_types[0]); ! static PyTypeObject Ladtype; static PyObject *OSSAudioError; ! static lad_t * ! newladobject(PyObject *arg) { ! lad_t *xp; int fd, afmts, imode; char *basedev = NULL; --- 76,87 ---- static int n_audio_types = sizeof(audio_types) / sizeof(audio_types[0]); ! static PyTypeObject OSSType; static PyObject *OSSAudioError; ! static oss_t * ! newossobject(PyObject *arg) { ! oss_t *xp; int fd, afmts, imode; char *basedev = NULL; *************** *** 135,139 **** } /* Create and initialize the object */ ! if ((xp = PyObject_New(lad_t, &Ladtype)) == NULL) { close(fd); return NULL; --- 135,139 ---- } /* Create and initialize the object */ ! if ((xp = PyObject_New(oss_t, &OSSType)) == NULL) { close(fd); return NULL; *************** *** 147,151 **** static void ! lad_dealloc(lad_t *xp) { /* if already closed, don't reclose it */ --- 147,151 ---- static void ! oss_dealloc(oss_t *xp) { /* if already closed, don't reclose it */ *************** *** 174,178 **** */ static PyObject * ! _do_ioctl_1(lad_t *self, PyObject *args, char *fname, int cmd) { char argfmt[13] = "i:"; --- 174,178 ---- */ static PyObject * ! _do_ioctl_1(oss_t *self, PyObject *args, char *fname, int cmd) { char argfmt[13] = "i:"; *************** *** 192,196 **** SNDCTL_DSP_{SYNC,RESET,POST}. */ static PyObject * ! _do_ioctl_0(lad_t *self, PyObject *args, char *fname, int cmd) { char argfmt[12] = ":"; --- 192,196 ---- SNDCTL_DSP_{SYNC,RESET,POST}. */ static PyObject * ! _do_ioctl_0(oss_t *self, PyObject *args, char *fname, int cmd) { char argfmt[12] = ":"; *************** *** 209,213 **** static PyObject * ! lad_nonblock(lad_t *self, PyObject *args) { /* Hmmm: it doesn't appear to be possible to return to blocking --- 209,213 ---- static PyObject * ! oss_nonblock(oss_t *self, PyObject *args) { /* Hmmm: it doesn't appear to be possible to return to blocking *************** *** 222,226 **** static PyObject * ! lad_setfmt(lad_t *self, PyObject *args) { return _do_ioctl_1(self, args, "setfmt", SNDCTL_DSP_SETFMT); --- 222,226 ---- static PyObject * ! oss_setfmt(oss_t *self, PyObject *args) { return _do_ioctl_1(self, args, "setfmt", SNDCTL_DSP_SETFMT); *************** *** 228,232 **** static PyObject * ! lad_getfmts(lad_t *self, PyObject *args) { int mask; --- 228,232 ---- static PyObject * ! oss_getfmts(oss_t *self, PyObject *args) { int mask; *************** *** 239,243 **** static PyObject * ! lad_channels(lad_t *self, PyObject *args) { return _do_ioctl_1(self, args, "channels", SNDCTL_DSP_CHANNELS); --- 239,243 ---- static PyObject * ! oss_channels(oss_t *self, PyObject *args) { return _do_ioctl_1(self, args, "channels", SNDCTL_DSP_CHANNELS); *************** *** 245,249 **** static PyObject * ! lad_speed(lad_t *self, PyObject *args) { return _do_ioctl_1(self, args, "speed", SNDCTL_DSP_SPEED); --- 245,249 ---- static PyObject * ! oss_speed(oss_t *self, PyObject *args) { return _do_ioctl_1(self, args, "speed", SNDCTL_DSP_SPEED); *************** *** 251,255 **** static PyObject * ! lad_sync(lad_t *self, PyObject *args) { return _do_ioctl_0(self, args, "sync", SNDCTL_DSP_SYNC); --- 251,255 ---- static PyObject * ! oss_sync(oss_t *self, PyObject *args) { return _do_ioctl_0(self, args, "sync", SNDCTL_DSP_SYNC); *************** *** 257,261 **** static PyObject * ! lad_reset(lad_t *self, PyObject *args) { return _do_ioctl_0(self, args, "reset", SNDCTL_DSP_RESET); --- 257,261 ---- static PyObject * ! oss_reset(oss_t *self, PyObject *args) { return _do_ioctl_0(self, args, "reset", SNDCTL_DSP_RESET); *************** *** 263,267 **** static PyObject * ! lad_post(lad_t *self, PyObject *args) { return _do_ioctl_0(self, args, "post", SNDCTL_DSP_POST); --- 263,267 ---- static PyObject * ! oss_post(oss_t *self, PyObject *args) { return _do_ioctl_0(self, args, "post", SNDCTL_DSP_POST); *************** *** 273,277 **** static PyObject * ! lad_read(lad_t *self, PyObject *args) { int size, count; --- 273,277 ---- static PyObject * ! oss_read(oss_t *self, PyObject *args) { int size, count; *************** *** 296,300 **** static PyObject * ! lad_write(lad_t *self, PyObject *args) { char *cp; --- 296,300 ---- static PyObject * ! oss_write(oss_t *self, PyObject *args) { char *cp; *************** *** 313,317 **** static PyObject * ! lad_writeall(lad_t *self, PyObject *args) { char *cp; --- 313,317 ---- static PyObject * ! oss_writeall(oss_t *self, PyObject *args) { char *cp; *************** *** 358,362 **** static PyObject * ! lad_close(lad_t *self, PyObject *args) { if (!PyArg_ParseTuple(args, ":close")) --- 358,362 ---- static PyObject * ! oss_close(oss_t *self, PyObject *args) { if (!PyArg_ParseTuple(args, ":close")) *************** *** 372,376 **** static PyObject * ! lad_fileno(lad_t *self, PyObject *args) { if (!PyArg_ParseTuple(args, ":fileno")) --- 372,376 ---- static PyObject * ! oss_fileno(oss_t *self, PyObject *args) { if (!PyArg_ParseTuple(args, ":fileno")) *************** *** 384,388 **** static PyObject * ! lad_setparameters(lad_t *self, PyObject *args) { int rate, ssize, nchannels, n, fmt, emulate=0; --- 384,388 ---- static PyObject * ! oss_setparameters(oss_t *self, PyObject *args) { int rate, ssize, nchannels, n, fmt, emulate=0; *************** *** 449,453 **** static int ! _ssize(lad_t *self, int *nchannels, int *ssize) { int fmt; --- 449,453 ---- static int ! _ssize(oss_t *self, int *nchannels, int *ssize) { int fmt; *************** *** 485,489 **** of samples */ static PyObject * ! lad_bufsize(lad_t *self, PyObject *args) { audio_buf_info ai; --- 485,489 ---- of samples */ static PyObject * ! oss_bufsize(oss_t *self, PyObject *args) { audio_buf_info ai; *************** *** 506,510 **** hardware for playing */ static PyObject * ! lad_obufcount(lad_t *self, PyObject *args) { audio_buf_info ai; --- 506,510 ---- hardware for playing */ static PyObject * ! oss_obufcount(oss_t *self, PyObject *args) { audio_buf_info ai; *************** *** 529,533 **** blocking */ static PyObject * ! lad_obuffree(lad_t *self, PyObject *args) { audio_buf_info ai; --- 529,533 ---- blocking */ static PyObject * ! oss_obuffree(oss_t *self, PyObject *args) { audio_buf_info ai; *************** *** 549,553 **** static PyObject * ! lad_getptr(lad_t *self, PyObject *args) { count_info info; --- 549,553 ---- static PyObject * ! oss_getptr(oss_t *self, PyObject *args) { count_info info; *************** *** 568,598 **** } ! static PyMethodDef lad_methods[] = { /* Regular file methods */ ! { "read", (PyCFunction)lad_read, METH_VARARGS }, ! { "write", (PyCFunction)lad_write, METH_VARARGS }, ! { "writeall", (PyCFunction)lad_writeall, METH_VARARGS }, ! { "close", (PyCFunction)lad_close, METH_VARARGS }, ! { "fileno", (PyCFunction)lad_fileno, METH_VARARGS }, /* Simple ioctl wrappers */ ! { "nonblock", (PyCFunction)lad_nonblock, METH_VARARGS }, ! { "setfmt", (PyCFunction)lad_setfmt, METH_VARARGS }, ! { "getfmts", (PyCFunction)lad_getfmts, METH_VARARGS }, ! { "channels", (PyCFunction)lad_channels, METH_VARARGS }, ! { "speed", (PyCFunction)lad_speed, METH_VARARGS }, ! { "sync", (PyCFunction)lad_sync, METH_VARARGS }, ! { "reset", (PyCFunction)lad_reset, METH_VARARGS }, ! { "post", (PyCFunction)lad_post, METH_VARARGS }, /* Convenience methods -- wrap a couple of ioctls together */ ! { "setparameters", (PyCFunction)lad_setparameters, METH_VARARGS }, ! { "bufsize", (PyCFunction)lad_bufsize, METH_VARARGS }, ! { "obufcount", (PyCFunction)lad_obufcount, METH_VARARGS }, ! { "obuffree", (PyCFunction)lad_obuffree, METH_VARARGS }, ! { "getptr", (PyCFunction)lad_getptr, METH_VARARGS }, /* Aliases for backwards compatibility */ ! { "flush", (PyCFunction)lad_sync, METH_VARARGS }, { NULL, NULL} /* sentinel */ --- 568,598 ---- } ! static PyMethodDef oss_methods[] = { /* Regular file methods */ ! { "read", (PyCFunction)oss_read, METH_VARARGS }, ! { "write", (PyCFunction)oss_write, METH_VARARGS }, ! { "writeall", (PyCFunction)oss_writeall, METH_VARARGS }, ! { "close", (PyCFunction)oss_close, METH_VARARGS }, ! { "fileno", (PyCFunction)oss_fileno, METH_VARARGS }, /* Simple ioctl wrappers */ ! { "nonblock", (PyCFunction)oss_nonblock, METH_VARARGS }, ! { "setfmt", (PyCFunction)oss_setfmt, METH_VARARGS }, ! { "getfmts", (PyCFunction)oss_getfmts, METH_VARARGS }, ! { "channels", (PyCFunction)oss_channels, METH_VARARGS }, ! { "speed", (PyCFunction)oss_speed, METH_VARARGS }, ! { "sync", (PyCFunction)oss_sync, METH_VARARGS }, ! { "reset", (PyCFunction)oss_reset, METH_VARARGS }, ! { "post", (PyCFunction)oss_post, METH_VARARGS }, /* Convenience methods -- wrap a couple of ioctls together */ ! { "setparameters", (PyCFunction)oss_setparameters, METH_VARARGS }, ! { "bufsize", (PyCFunction)oss_bufsize, METH_VARARGS }, ! { "obufcount", (PyCFunction)oss_obufcount, METH_VARARGS }, ! { "obuffree", (PyCFunction)oss_obuffree, METH_VARARGS }, ! { "getptr", (PyCFunction)oss_getptr, METH_VARARGS }, /* Aliases for backwards compatibility */ ! { "flush", (PyCFunction)oss_sync, METH_VARARGS }, { NULL, NULL} /* sentinel */ *************** *** 600,618 **** static PyObject * ! lad_getattr(lad_t *xp, char *name) { ! return Py_FindMethod(lad_methods, (PyObject *)xp, name); } ! static PyTypeObject Ladtype = { PyObject_HEAD_INIT(&PyType_Type) 0, /*ob_size*/ "ossaudiodev.oss_audio_device", /*tp_name*/ ! sizeof(lad_t), /*tp_size*/ 0, /*tp_itemsize*/ /* methods */ ! (destructor)lad_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ ! (getattrfunc)lad_getattr, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ --- 600,618 ---- static PyObject * ! oss_getattr(oss_t *xp, char *name) { ! return Py_FindMethod(oss_methods, (PyObject *)xp, name); } ! static PyTypeObject OSSType = { PyObject_HEAD_INIT(&PyType_Type) 0, /*ob_size*/ "ossaudiodev.oss_audio_device", /*tp_name*/ ! sizeof(oss_t), /*tp_size*/ 0, /*tp_itemsize*/ /* methods */ ! (destructor)oss_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ ! (getattrfunc)oss_getattr, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ *************** *** 623,627 **** ossopen(PyObject *self, PyObject *args) { ! return (PyObject *)newladobject(args); } --- 623,627 ---- ossopen(PyObject *self, PyObject *args) { ! return (PyObject *)newossobject(args); } From gward@users.sourceforge.net Wed Dec 11 14:50:02 2002 From: gward@users.sourceforge.net (gward@users.sourceforge.net) Date: Wed, 11 Dec 2002 06:50:02 -0800 Subject: [Python-checkins] python/dist/src/Modules ossaudiodev.c,1.6,1.7 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv1658 Modified Files: ossaudiodev.c Log Message: Prepare for the coming mixer support patch: change _do_ioctl_0() and _do_ioctl_1() so they take a file descriptor rather than an oss_t pointer. Index: ossaudiodev.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/ossaudiodev.c,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** ossaudiodev.c 11 Dec 2002 14:43:13 -0000 1.6 --- ossaudiodev.c 11 Dec 2002 14:49:59 -0000 1.7 *************** *** 174,188 **** */ static PyObject * ! _do_ioctl_1(oss_t *self, PyObject *args, char *fname, int cmd) { ! char argfmt[13] = "i:"; int arg; ! assert(strlen(fname) <= 10); strcat(argfmt, fname); if (!PyArg_ParseTuple(args, argfmt, &arg)) return NULL; ! if (ioctl(self->x_fd, cmd, &arg) == -1) return PyErr_SetFromErrno(PyExc_IOError); return PyInt_FromLong(arg); --- 174,188 ---- */ static PyObject * ! _do_ioctl_1(int fd, PyObject *args, char *fname, int cmd) { ! char argfmt[33] = "i:"; int arg; ! assert(strlen(fname) <= 30); strcat(argfmt, fname); if (!PyArg_ParseTuple(args, argfmt, &arg)) return NULL; ! if (ioctl(fd, cmd, &arg) == -1) return PyErr_SetFromErrno(PyExc_IOError); return PyInt_FromLong(arg); *************** *** 192,205 **** SNDCTL_DSP_{SYNC,RESET,POST}. */ static PyObject * ! _do_ioctl_0(oss_t *self, PyObject *args, char *fname, int cmd) { ! char argfmt[12] = ":"; ! assert(strlen(fname) <= 10); strcat(argfmt, fname); if (!PyArg_ParseTuple(args, argfmt)) return NULL; ! if (ioctl(self->x_fd, cmd, 0) == -1) return PyErr_SetFromErrno(PyExc_IOError); Py_INCREF(Py_None); --- 192,205 ---- SNDCTL_DSP_{SYNC,RESET,POST}. */ static PyObject * ! _do_ioctl_0(int fd, PyObject *args, char *fname, int cmd) { ! char argfmt[32] = ":"; ! assert(strlen(fname) <= 30); strcat(argfmt, fname); if (!PyArg_ParseTuple(args, argfmt)) return NULL; ! if (ioctl(fd, cmd, 0) == -1) return PyErr_SetFromErrno(PyExc_IOError); Py_INCREF(Py_None); *************** *** 224,228 **** oss_setfmt(oss_t *self, PyObject *args) { ! return _do_ioctl_1(self, args, "setfmt", SNDCTL_DSP_SETFMT); } --- 224,228 ---- oss_setfmt(oss_t *self, PyObject *args) { ! return _do_ioctl_1(self->x_fd, args, "setfmt", SNDCTL_DSP_SETFMT); } *************** *** 241,245 **** oss_channels(oss_t *self, PyObject *args) { ! return _do_ioctl_1(self, args, "channels", SNDCTL_DSP_CHANNELS); } --- 241,245 ---- oss_channels(oss_t *self, PyObject *args) { ! return _do_ioctl_1(self->x_fd, args, "channels", SNDCTL_DSP_CHANNELS); } *************** *** 247,251 **** oss_speed(oss_t *self, PyObject *args) { ! return _do_ioctl_1(self, args, "speed", SNDCTL_DSP_SPEED); } --- 247,251 ---- oss_speed(oss_t *self, PyObject *args) { ! return _do_ioctl_1(self->x_fd, args, "speed", SNDCTL_DSP_SPEED); } *************** *** 253,257 **** oss_sync(oss_t *self, PyObject *args) { ! return _do_ioctl_0(self, args, "sync", SNDCTL_DSP_SYNC); } --- 253,257 ---- oss_sync(oss_t *self, PyObject *args) { ! return _do_ioctl_0(self->x_fd, args, "sync", SNDCTL_DSP_SYNC); } *************** *** 259,263 **** oss_reset(oss_t *self, PyObject *args) { ! return _do_ioctl_0(self, args, "reset", SNDCTL_DSP_RESET); } --- 259,263 ---- oss_reset(oss_t *self, PyObject *args) { ! return _do_ioctl_0(self->x_fd, args, "reset", SNDCTL_DSP_RESET); } *************** *** 265,269 **** oss_post(oss_t *self, PyObject *args) { ! return _do_ioctl_0(self, args, "post", SNDCTL_DSP_POST); } --- 265,269 ---- oss_post(oss_t *self, PyObject *args) { ! return _do_ioctl_0(self->x_fd, args, "post", SNDCTL_DSP_POST); } From akuchling@users.sourceforge.net Wed Dec 11 15:03:58 2002 From: akuchling@users.sourceforge.net (akuchling@users.sourceforge.net) Date: Wed, 11 Dec 2002 07:03:58 -0800 Subject: [Python-checkins] python/dist/src/Doc/whatsnew whatsnew23.tex,1.84,1.85 Message-ID: Update of /cvsroot/python/python/dist/src/Doc/whatsnew In directory sc8-pr-cvs1:/tmp/cvs-serv7669 Modified Files: whatsnew23.tex Log Message: Various additions and changes suggested by Raymond Hettinger Index: whatsnew23.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/whatsnew/whatsnew23.tex,v retrieving revision 1.84 retrieving revision 1.85 diff -C2 -d -r1.84 -r1.85 *** whatsnew23.tex 10 Dec 2002 21:04:25 -0000 1.84 --- whatsnew23.tex 11 Dec 2002 15:03:51 -0000 1.85 *************** *** 834,837 **** --- 834,847 ---- (Patches contributed by Raymond Hettinger.) + The dict() constructor now also accepts keyword arguments to simplify + creating small dictionaries: + + \begin{verbatim} + >>> dict(red=1, blue=2, green=3, black=4) + {'blue': 2, 'black': 4, 'green': 3, 'red': 1} + \end{verbatim} + + (Contributed by Just van Rossum.) + \item The \keyword{assert} statement no longer checks the \code{__debug__} flag, so you can no longer disable assertions by assigning to \code{__debug__}. *************** *** 1015,1018 **** --- 1025,1032 ---- (Removed by Michael Hudson.) + \item \function{xrange()} objects now have their own iterator, making + \code{for i in xrange(n)} slightly faster than + \code{for i in range(n)}. (Patch by Raymond Hettinger.) + \item A number of small rearrangements have been made in various hotspots to improve performance, inlining a function here, removing *************** *** 1178,1182 **** \item The \function{sample(\var{population}, \var{k})} function was added to the \module{random} module. \var{population} is a sequence ! containing the elements of a population, and \function{sample()} chooses \var{k} elements from the population without replacing chosen elements. \var{k} can be any value up to \code{len(\var{population})}. --- 1192,1196 ---- \item The \function{sample(\var{population}, \var{k})} function was added to the \module{random} module. \var{population} is a sequence ! or \code{xrange} object containing the elements of a population, and \function{sample()} chooses \var{k} elements from the population without replacing chosen elements. \var{k} can be any value up to \code{len(\var{population})}. *************** *** 1184,1203 **** \begin{verbatim} ! >>> pop = range(6) ; pop ! [0, 1, 2, 3, 4, 5] ! >>> random.sample(pop, 3) # Choose three elements ! [0, 4, 3] ! >>> random.sample(pop, 6) # Choose all six elements ! [4, 5, 0, 3, 2, 1] ! >>> random.sample(pop, 6) # Choose six again ! [4, 2, 3, 0, 5, 1] ! >>> random.sample(pop, 7) # Can't choose more than six Traceback (most recent call last): File "", line 1, in ? ! File "random.py", line 396, in sample ! raise ValueError, "sample larger than population" ValueError: sample larger than population ! >>> \end{verbatim} \item The \module{readline} module also gained a number of new --- 1198,1219 ---- \begin{verbatim} ! >>> days = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'St', 'Sn'] ! >>> random.sample(days, 3) # Choose 3 elements ! ['St', 'Sn', 'Th'] ! >>> random.sample(days, 7) # Choose 7 elements ! ['Tu', 'Th', 'Mo', 'We', 'St', 'Fr', 'Sn'] ! >>> random.sample(days, 7) # Choose 7 again ! ['We', 'Mo', 'Sn', 'Fr', 'Tu', 'St', 'Th'] ! >>> random.sample(days, 8) # Can't choose eight Traceback (most recent call last): File "", line 1, in ? ! File "random.py", line 414, in sample ! raise ValueError, "sample larger than population" ValueError: sample larger than population ! >>> random.sample(xrange(1,10000,2), 10) # Choose ten odds under 10000 ! [3407, 3805, 1505, 7023, 2401, 2267, 9733, 3151, 8083, 9195] \end{verbatim} + + (Contributed by Raymond Hettinger.) \item The \module{readline} module also gained a number of new *************** *** 1271,1274 **** --- 1287,1342 ---- identically on all platforms. + \item The \module{UserDict) has a new \class{DictMixin} class which + defines all dictionary methods for classes that already have a minimum + mapping interface. This greatly simplifies writing classes that need + to be substitutable for dictionaries, such as the classes in + the \module{shelve} module. + + Adding the mixin as a superclass provides the full dictionary + interface whenever the class defines \method{__getitem__}, + \method{__setitem__}, \method{__delitem__), and \method{keys}. + For example: + + \begin{verbatim} + >>> import UserDict + >>> class SeqDict(UserDict.DictMixin): + """Dictionary lookalike implemented with lists.""" + def __init__(self): + self.keylist = [] + self.valuelist = [] + def __getitem__(self, key): + try: + i = self.keylist.index(key) + except ValueError: + raise KeyError + return self.valuelist[i] + def __setitem__(self, key, value): + try: + i = self.keylist.index(key) + self.valuelist[i] = value + except ValueError: + self.keylist.append(key) + self.valuelist.append(value) + def __delitem__(self, key): + try: + i = self.keylist.index(key) + except ValueError: + raise KeyError + self.keylist.pop(i) + self.valuelist.pop(i) + def keys(self): + return list(self.keylist) + + >>> s = SeqDict() + >>> dir(s) # See that other dictionary methods are implemented + ['__cmp__', '__contains__', '__delitem__', '__doc__', '__getitem__', + '__init__', '__iter__', '__len__', '__module__', '__repr__', + '__setitem__', 'clear', 'get', 'has_key', 'items', 'iteritems', + 'iterkeys', 'itervalues', 'keylist', 'keys', 'pop', 'popitem', + 'setdefault', 'update', 'valuelist', 'values'] + \end {verbatim} + + (Contributed by Raymond Hettinger.) + \item The DOM implementation in \module{xml.dom.minidom} can now generate XML output in a *************** *** 1712,1718 **** suggestions, corrections and assistance with various drafts of this article: Simon Brunning, Michael Chermside, Scott David Daniels, ! Fred~L. Drake, Jr., Michael Hudson, Detlef Lannert, Martin von ! L\"owis, Andrew MacIntyre, Lalo Martins, Gustavo Niemeyer, Neal ! Norwitz, Chris Reedy, Vinay Sajip, Neil Schemenauer, Jason Tishler. \end{document} --- 1780,1787 ---- suggestions, corrections and assistance with various drafts of this article: Simon Brunning, Michael Chermside, Scott David Daniels, ! Fred~L. Drake, Jr., Raymond Hettinger, Michael Hudson, Detlef Lannert, ! Martin von L\"owis, Andrew MacIntyre, Lalo Martins, Gustavo Niemeyer, ! Neal Norwitz, Chris Reedy, Vinay Sajip, Neil Schemenauer, Jason ! Tishler. \end{document} From gward@users.sourceforge.net Wed Dec 11 15:12:04 2002 From: gward@users.sourceforge.net (gward@users.sourceforge.net) Date: Wed, 11 Dec 2002 07:12:04 -0800 Subject: [Python-checkins] python/dist/src/Modules ossaudiodev.c,1.7,1.8 Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv9539/Modules Modified Files: ossaudiodev.c Log Message: Add OSS mixer interface (from Nicholas FitzRoy-Dale ): * add oss_mixer_t and OSSMixerType * add newossmixerobject(), oss_mixer_dealloc(), ossopenmixer() * add _do_ioctl_1_internal() to support mixer ioctls * add mixer methods: oss_mixer_{close,fileno,channels,stereo_channels, rec_channels,getvol,setvol,getrecsrc,setrecsrc}() * add oss_mixer_methods list * add oss_mixer_getattr() (why?!) * export SOUND_MIXER_* constants from soundcard.h Index: ossaudiodev.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Modules/ossaudiodev.c,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** ossaudiodev.c 11 Dec 2002 14:49:59 -0000 1.7 --- ossaudiodev.c 11 Dec 2002 15:12:01 -0000 1.8 *************** *** 9,12 **** --- 9,13 ---- * Renamed to ossaudiodev and rearranged/revised/hacked up * by Greg Ward , November 2002. + * Mixer interface by Nicholas FitzRoy-Dale , Dec 2002. * * (c) 2000 Peter Bosch. All Rights Reserved. *************** *** 54,57 **** --- 55,63 ---- } oss_t; + typedef struct { + PyObject_HEAD; + int x_fd; /* The open mixer device */ + } oss_mixer_t; + /* XXX several format defined in soundcard.h are not supported, including _NE (native endian) options and S32 options *************** *** 77,80 **** --- 83,87 ---- static PyTypeObject OSSType; + static PyTypeObject OSSMixerType; static PyObject *OSSAudioError; *************** *** 155,158 **** --- 162,217 ---- } + static oss_mixer_t * + newossmixerobject(PyObject *arg) + { + char *basedev = NULL, *mode = NULL; + int fd, imode; + oss_mixer_t *xp; + + if (!PyArg_ParseTuple (arg, "|ss", &basedev, &mode)) { + return NULL; + } + + if (basedev == NULL) { + basedev = getenv("MIXERDEV"); + if (basedev == NULL) /* MIXERDEV not set */ + basedev = "/dev/mixer"; + } + + if (mode == NULL || strcmp(mode, "r") == 0) + imode = O_RDONLY; + else if (strcmp(mode, "w") == 0) + imode = O_WRONLY; + else if (strcmp(mode, "rw") == 0) + imode = O_RDWR; + else { + PyErr_SetString(OSSAudioError, "mode must be 'r', 'w', or 'rw'"); + return NULL; + } + + if ((fd = open (basedev, imode)) == -1) { + PyErr_SetFromErrnoWithFilename(PyExc_IOError, basedev); + return NULL; + } + + if ((xp = PyObject_New(oss_mixer_t, &OSSMixerType)) == NULL) { + close(fd); + return NULL; + } + + xp->x_fd = fd; + + return xp; + } + + static void + oss_mixer_dealloc(oss_mixer_t *xp) + { + /* if already closed, don't reclose it */ + if (xp->x_fd != -1) + close(xp->x_fd); + PyObject_Del(xp); + } + /* Methods to wrap the OSS ioctls. The calling convention is pretty *************** *** 189,192 **** --- 248,278 ---- } + /* _do_ioctl_1_internal() is a wrapper for ioctls that take no inputs + but return an output -- ie. we need to pass a pointer to a local C + variable so the driver can write its output there, but from Python + all we see is the return value. For example, + SOUND_MIXER_READ_DEVMASK returns a bitmask of available mixer + devices, but does not use the value of the parameter passed-in in any + way. + */ + + static PyObject * + _do_ioctl_1_internal(int fd, PyObject *args, char *fname, int cmd) + { + char argfmt[32] = ":"; + int arg = 0; + + assert(strlen(fname) <= 30); + strcat(argfmt, fname); + if (!PyArg_ParseTuple(args, argfmt, &arg)) + return NULL; + + if (ioctl(fd, cmd, &arg) == -1) + return PyErr_SetFromErrno(PyExc_IOError); + return PyInt_FromLong(arg); + } + + + /* _do_ioctl_0() is a private helper for the no-argument ioctls: SNDCTL_DSP_{SYNC,RESET,POST}. */ *************** *** 568,571 **** --- 654,765 ---- } + /* Mixer methods */ + static PyObject * + oss_mixer_close(oss_mixer_t *self, PyObject *args) + { + if (!PyArg_ParseTuple(args, ":close")) + return NULL; + + if (self->x_fd >= 0) { + close(self->x_fd); + self->x_fd = -1; + } + Py_INCREF(Py_None); + return Py_None; + } + + static PyObject * + oss_mixer_fileno(oss_mixer_t *self, PyObject *args) + { + if (!PyArg_ParseTuple(args, ":fileno")) + return NULL; + return PyInt_FromLong(self->x_fd); + } + + /* Simple mixer interface methods */ + + static PyObject * + oss_mixer_channels (oss_mixer_t *self, PyObject *args) + { + return _do_ioctl_1_internal(self->x_fd, args, "channels", + SOUND_MIXER_READ_DEVMASK); + } + + static PyObject * + oss_mixer_stereo_channels (oss_mixer_t *self, PyObject *args) + { + return _do_ioctl_1_internal(self->x_fd, args, "stereochannels", + SOUND_MIXER_READ_STEREODEVS); + } + + static PyObject * + oss_mixer_rec_channels (oss_mixer_t *self, PyObject *args) + { + return _do_ioctl_1_internal(self->x_fd, args, "recchannels", + SOUND_MIXER_READ_STEREODEVS); + } + + static PyObject * + oss_mixer_getvol (oss_mixer_t *self, PyObject *args) + { + int channel, volume; + + /* Can't use _do_ioctl_1 because of encoded arg thingy. */ + if (!PyArg_ParseTuple (args, "i:getvol", &channel)) + return NULL; + + if (channel < 0 || channel > SOUND_MIXER_NRDEVICES) { + PyErr_SetString (OSSAudioError, "Invalid mixer channel specified."); + return NULL; + } + + if (ioctl (self->x_fd, MIXER_READ(channel), &volume) == -1) + return PyErr_SetFromErrno(PyExc_IOError); + + return Py_BuildValue ("(ii)", volume & 0xff, (volume & 0xff00) >> 8); + } + + static PyObject * + oss_mixer_setvol (oss_mixer_t *self, PyObject *args) + { + int channel, volume, leftVol, rightVol; + + /* Can't use _do_ioctl_1 because of encoded arg thingy. */ + if (!PyArg_ParseTuple (args, "i(ii):setvol", &channel, &leftVol, &rightVol)) + return NULL; + + if (channel < 0 || channel > SOUND_MIXER_NRDEVICES) { + PyErr_SetString (OSSAudioError, "Invalid mixer channel specified."); + return NULL; + } + + if (leftVol < 0 || rightVol < 0 || leftVol > 100 || rightVol > 100) { + PyErr_SetString (OSSAudioError, "Volumes must be between 0 and 100."); + return NULL; + } + + volume = (rightVol << 8) | leftVol; + + if (ioctl (self->x_fd, MIXER_WRITE(channel), &volume) == -1) + return PyErr_SetFromErrno(PyExc_IOError); + + return Py_BuildValue ("(ii)", volume & 0xff, (volume & 0xff00) >> 8); + } + + static PyObject * + oss_mixer_getrecsrc (oss_mixer_t *self, PyObject *args) + { + return _do_ioctl_1_internal(self->x_fd, args, "getrecsrc", + SOUND_MIXER_READ_RECSRC); + } + + static PyObject * + oss_mixer_setrecsrc (oss_mixer_t *self, PyObject *args) + { + return _do_ioctl_1(self->x_fd, args, "setrecsrc", + SOUND_MIXER_WRITE_RECSRC); + } + + static PyMethodDef oss_methods[] = { /* Regular file methods */ *************** *** 599,602 **** --- 793,813 ---- }; + static PyMethodDef oss_mixer_methods[] = { + /* Regular file method - OSS mixers are ioctl-only interface */ + { "close", (PyCFunction)oss_mixer_close, METH_VARARGS }, + { "fileno", (PyCFunction)oss_mixer_fileno, METH_VARARGS }, + + /* Simple ioctl wrappers */ + { "channels", (PyCFunction)oss_mixer_channels, METH_VARARGS }, + { "stereochannels", (PyCFunction)oss_mixer_stereo_channels, METH_VARARGS}, + { "recchannels", (PyCFunction)oss_mixer_rec_channels, METH_VARARGS}, + { "getvol", (PyCFunction)oss_mixer_getvol, METH_VARARGS }, + { "setvol", (PyCFunction)oss_mixer_setvol, METH_VARARGS }, + { "getrecsrc", (PyCFunction)oss_mixer_getrecsrc, METH_VARARGS }, + { "setrecsrc", (PyCFunction)oss_mixer_setrecsrc, METH_VARARGS }, + + { NULL, NULL} + }; + static PyObject * oss_getattr(oss_t *xp, char *name) *************** *** 605,608 **** --- 816,825 ---- } + static PyObject * + oss_mixer_getattr(oss_mixer_t *xp, char *name) + { + return Py_FindMethod(oss_mixer_methods, (PyObject *)xp, name); + } + static PyTypeObject OSSType = { PyObject_HEAD_INIT(&PyType_Type) *************** *** 620,623 **** --- 837,856 ---- }; + static PyTypeObject OSSMixerType = { + PyObject_HEAD_INIT(&PyType_Type) + 0, /*ob_size*/ + "ossaudiodev.oss_mixer_device", /*tp_name*/ + sizeof(oss_mixer_t), /*tp_size*/ + 0, /*tp_itemsize*/ + /* methods */ + (destructor)oss_mixer_dealloc, /*tp_dealloc*/ + 0, /*tp_print*/ + (getattrfunc)oss_mixer_getattr, /*tp_getattr*/ + 0, /*tp_setattr*/ + 0, /*tp_compare*/ + 0, /*tp_repr*/ + }; + + static PyObject * ossopen(PyObject *self, PyObject *args) *************** *** 626,631 **** --- 859,871 ---- } + static PyObject * + ossopenmixer(PyObject *self, PyObject *args) + { + return (PyObject *)newossmixerobject(args); + } + static PyMethodDef ossaudiodev_methods[] = { { "open", ossopen, METH_VARARGS }, + { "openmixer", ossopenmixer, METH_VARARGS }, { 0, 0 }, }; *************** *** 660,663 **** --- 900,930 ---- _EXPORT_INT(m, AFMT_AC3); _EXPORT_INT(m, AFMT_S16_NE); + + /* Expose the sound mixer channels. */ + _EXPORT_INT(m, SOUND_MIXER_VOLUME); + _EXPORT_INT(m, SOUND_MIXER_BASS); + _EXPORT_INT(m, SOUND_MIXER_TREBLE); + _EXPORT_INT(m, SOUND_MIXER_SYNTH); + _EXPORT_INT(m, SOUND_MIXER_PCM); + _EXPORT_INT(m, SOUND_MIXER_SPEAKER); + _EXPORT_INT(m, SOUND_MIXER_LINE); + _EXPORT_INT(m, SOUND_MIXER_MIC); + _EXPORT_INT(m, SOUND_MIXER_CD); + _EXPORT_INT(m, SOUND_MIXER_IMIX); + _EXPORT_INT(m, SOUND_MIXER_ALTPCM); + _EXPORT_INT(m, SOUND_MIXER_RECLEV); + _EXPORT_INT(m, SOUND_MIXER_IGAIN); + _EXPORT_INT(m, SOUND_MIXER_OGAIN); + _EXPORT_INT(m, SOUND_MIXER_LINE1); + _EXPORT_INT(m, SOUND_MIXER_LINE2); + _EXPORT_INT(m, SOUND_MIXER_LINE3); + _EXPORT_INT(m, SOUND_MIXER_DIGITAL1); + _EXPORT_INT(m, SOUND_MIXER_DIGITAL2); + _EXPORT_INT(m, SOUND_MIXER_DIGITAL3); + _EXPORT_INT(m, SOUND_MIXER_PHONEIN); + _EXPORT_INT(m, SOUND_MIXER_PHONEOUT); + _EXPORT_INT(m, SOUND_MIXER_VIDEO); + _EXPORT_INT(m, SOUND_MIXER_RADIO); + _EXPORT_INT(m, SOUND_MIXER_MONITOR); /* Expose all the ioctl numbers for masochists who like to do this From tim_one@users.sourceforge.net Wed Dec 11 17:50:26 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 11 Dec 2002 09:50:26 -0800 Subject: [Python-checkins] python/dist/src/PCbuild pcbuild.dsw,1.31,1.32 Message-ID: Update of /cvsroot/python/python/dist/src/PCbuild In directory sc8-pr-cvs1:/tmp/cvs-serv9558/python/PCbuild Modified Files: pcbuild.dsw Log Message: Made the _ssl subproject depend on the w9xpopen subproject, because build_ssl.py requires os.popen(). Index: pcbuild.dsw =================================================================== RCS file: /cvsroot/python/python/dist/src/PCbuild/pcbuild.dsw,v retrieving revision 1.31 retrieving revision 1.32 diff -C2 -d -r1.31 -r1.32 *** pcbuild.dsw 3 Dec 2002 05:47:26 -0000 1.31 --- pcbuild.dsw 11 Dec 2002 17:50:24 -0000 1.32 *************** *** 4,8 **** ############################################################################### ! Project: "_bsddb"=".\_bsddb.dsp" - Package Owner=<4> Package=<5> --- 4,8 ---- ############################################################################### ! Project: "_bsddb"=.\_bsddb.dsp - Package Owner=<4> Package=<5> *************** *** 19,23 **** ############################################################################### ! Project: "_socket"=".\_socket.dsp" - Package Owner=<4> Package=<5> --- 19,23 ---- ############################################################################### ! Project: "_socket"=.\_socket.dsp - Package Owner=<4> Package=<5> *************** *** 34,38 **** ############################################################################### ! Project: "_sre"=".\_sre.dsp" - Package Owner=<4> Package=<5> --- 34,38 ---- ############################################################################### ! Project: "_sre"=.\_sre.dsp - Package Owner=<4> Package=<5> *************** *** 49,53 **** ############################################################################### ! Project: "_ssl"=".\_ssl.dsp" - Package Owner=<4> Package=<5> --- 49,53 ---- ############################################################################### ! Project: "_ssl"=.\_ssl.dsp - Package Owner=<4> Package=<5> *************** *** 66,74 **** Project_Dep_Name python End Project Dependency }}} ############################################################################### ! Project: "_symtable"=".\_symtable.dsp" - Package Owner=<4> Package=<5> --- 66,77 ---- Project_Dep_Name python End Project Dependency + Begin Project Dependency + Project_Dep_Name w9xpopen + End Project Dependency }}} ############################################################################### ! Project: "_symtable"=.\_symtable.dsp - Package Owner=<4> Package=<5> *************** *** 85,89 **** ############################################################################### ! Project: "_testcapi"=".\_testcapi.dsp" - Package Owner=<4> Package=<5> --- 88,92 ---- ############################################################################### ! Project: "_testcapi"=.\_testcapi.dsp - Package Owner=<4> Package=<5> *************** *** 100,104 **** ############################################################################### ! Project: "_tkinter"=".\_tkinter.dsp" - Package Owner=<4> Package=<5> --- 103,107 ---- ############################################################################### ! Project: "_tkinter"=.\_tkinter.dsp - Package Owner=<4> Package=<5> *************** *** 115,119 **** ############################################################################### ! Project: "bz2"=".\bz2.dsp" - Package Owner=<4> Package=<5> --- 118,122 ---- ############################################################################### ! Project: "bz2"=.\bz2.dsp - Package Owner=<4> Package=<5> *************** *** 127,131 **** ############################################################################### ! Project: "mmap"=".\mmap.dsp" - Package Owner=<4> Package=<5> --- 130,134 ---- ############################################################################### ! Project: "mmap"=.\mmap.dsp - Package Owner=<4> Package=<5> *************** *** 142,146 **** ############################################################################### ! Project: "parser"=".\parser.dsp" - Package Owner=<4> Package=<5> --- 145,149 ---- ############################################################################### ! Project: "parser"=.\parser.dsp - Package Owner=<4> Package=<5> *************** *** 157,161 **** ############################################################################### ! Project: "pyexpat"=".\pyexpat.dsp" - Package Owner=<4> Package=<5> --- 160,164 ---- ############################################################################### ! Project: "pyexpat"=.\pyexpat.dsp - Package Owner=<4> Package=<5> *************** *** 172,176 **** ############################################################################### ! Project: "python"=".\python.dsp" - Package Owner=<4> Package=<5> --- 175,179 ---- ############################################################################### ! Project: "python"=.\python.dsp - Package Owner=<4> Package=<5> *************** *** 187,191 **** ############################################################################### ! Project: "pythoncore"=".\pythoncore.dsp" - Package Owner=<4> Package=<5> --- 190,194 ---- ############################################################################### ! Project: "pythoncore"=.\pythoncore.dsp - Package Owner=<4> Package=<5> *************** *** 199,203 **** ############################################################################### ! Project: "pythonw"=".\pythonw.dsp" - Package Owner=<4> Package=<5> --- 202,206 ---- ############################################################################### ! Project: "pythonw"=.\pythonw.dsp - Package Owner=<4> Package=<5> *************** *** 214,218 **** ############################################################################### ! Project: "select"=".\select.dsp" - Package Owner=<4> Package=<5> --- 217,221 ---- ############################################################################### ! Project: "select"=.\select.dsp - Package Owner=<4> Package=<5> *************** *** 229,233 **** ############################################################################### ! Project: "unicodedata"=".\unicodedata.dsp" - Package Owner=<4> Package=<5> --- 232,236 ---- ############################################################################### ! Project: "unicodedata"=.\unicodedata.dsp - Package Owner=<4> Package=<5> *************** *** 244,248 **** ############################################################################### ! Project: "w9xpopen"=".\w9xpopen.dsp" - Package Owner=<4> Package=<5> --- 247,251 ---- ############################################################################### ! Project: "w9xpopen"=.\w9xpopen.dsp - Package Owner=<4> Package=<5> *************** *** 256,260 **** ############################################################################### ! Project: "winreg"=".\winreg.dsp" - Package Owner=<4> Package=<5> --- 259,263 ---- ############################################################################### ! Project: "winreg"=.\winreg.dsp - Package Owner=<4> Package=<5> *************** *** 271,275 **** ############################################################################### ! Project: "winsound"=".\winsound.dsp" - Package Owner=<4> Package=<5> --- 274,278 ---- ############################################################################### ! Project: "winsound"=.\winsound.dsp - Package Owner=<4> Package=<5> *************** *** 286,290 **** ############################################################################### ! Project: "zlib"=".\zlib.dsp" - Package Owner=<4> Package=<5> --- 289,293 ---- ############################################################################### ! Project: "zlib"=.\zlib.dsp - Package Owner=<4> Package=<5> From tim.one@comcast.net Wed Dec 11 18:01:23 2002 From: tim.one@comcast.net (Tim Peters) Date: Wed, 11 Dec 2002 13:01:23 -0500 Subject: [Python-checkins] python/dist/src/PCbuild pcbuild.dsw,1.31,1.32 In-Reply-To: Message-ID: [Tim] > Modified Files: > pcbuild.dsw > Log Message: > Made the _ssl subproject depend on the w9xpopen subproject, because > build_ssl.py requires os.popen(). > > > Index: pcbuild.dsw > =================================================================== > RCS file: /cvsroot/python/python/dist/src/PCbuild/pcbuild.dsw,v > retrieving revision 1.31 > retrieving revision 1.32 > diff -C2 -d -r1.31 -r1.32 > *** pcbuild.dsw 3 Dec 2002 05:47:26 -0000 1.31 > --- pcbuild.dsw 11 Dec 2002 17:50:24 -0000 1.32 > *************** > *** 4,8 **** > > ################################################################## > ############# > > ! Project: "_bsddb"=".\_bsddb.dsp" - Package Owner=<4> > > Package=<5> > --- 4,8 ---- > > ################################################################## > ############# > > ! Project: "_bsddb"=.\_bsddb.dsp - Package Owner=<4> > > Package=<5> Etc. Oops! If someone went out of their way to stuff quotes into the filepaths, I'm afraid MSCV6 just ripped them out again. I didn't do anything to try to make this happen, I only tried to change this part: > + Begin Project Dependency > + Project_Dep_Name w9xpopen > + End Project Dependency From guido@python.org Wed Dec 11 18:10:57 2002 From: guido@python.org (Guido van Rossum) Date: Wed, 11 Dec 2002 13:10:57 -0500 Subject: [Python-checkins] python/dist/src/PCbuild pcbuild.dsw,1.31,1.32 In-Reply-To: Your message of "Wed, 11 Dec 2002 13:01:23 EST." References: Message-ID: <200212111810.gBBIAv217924@pcp02138704pcs.reston01.va.comcast.net> > > *************** > > *** 4,8 **** > > > > ################################################################## > > ############# > > > > ! Project: "_bsddb"=".\_bsddb.dsp" - Package Owner=<4> > > > > Package=<5> > > --- 4,8 ---- > > > > ################################################################## > > ############# > > > > ! Project: "_bsddb"=.\_bsddb.dsp - Package Owner=<4> > > > > Package=<5> > > Etc. Oops! If someone went out of their way to stuff quotes into the > filepaths, I'm afraid MSCV6 just ripped them out again. Could it be that you're using a different service pack or patch level of MSV6 at home than at work? I've seen things like this (seemingly random changes to project file details) in the past too and always ignored them. --Guido van Rossum (home page: http://www.python.org/~guido/) From tim_one@users.sourceforge.net Wed Dec 11 18:54:13 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 11 Dec 2002 10:54:13 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.c,1.54,1.55 datetime.h,1.14,1.15 doc.txt,1.43,1.44 obj_time.c,1.6,1.7 obj_timetz.c,1.2,1.3 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv5073 Modified Files: datetime.c datetime.h doc.txt obj_time.c obj_timetz.c Log Message: Moving timetz a little closer to being usable. Index: datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.c,v retrieving revision 1.54 retrieving revision 1.55 diff -C2 -d -r1.54 -r1.55 *** datetime.c 11 Dec 2002 01:47:20 -0000 1.54 --- datetime.c 11 Dec 2002 18:54:10 -0000 1.55 *************** *** 548,551 **** --- 548,592 ---- static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */ + /* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not + * raise TypeError and return -1. + */ + static int + check_tzinfo_subclass(PyObject *p, const char *msg) + { + if (p == Py_None || PyTZInfo_Check(p)) + return 0; + PyErr_Format(PyExc_TypeError, + "%s must be None or of a tzinfo subclass, " + "not type '%s'", + msg, p->ob_type->tp_name); + return -1; + } + + /* For obscure 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. + */ + static PyObject * + diff_to_bool(long diff, int op) + { + PyObject *result; + int istrue; + + switch (op) { + case Py_EQ: istrue = diff == 0; break; + case Py_NE: istrue = diff != 0; break; + case Py_LE: istrue = diff <= 0; break; + case Py_GE: istrue = diff >= 0; break; + case Py_LT: istrue = diff < 0; break; + case Py_GT: istrue = diff > 0; break; + default: + assert(! "op unknown"); + istrue = 0; /* To shut up compiler */ + } + result = istrue ? Py_True : Py_False; + Py_INCREF(result); + return result; + } + /* Create a date instance with no range checking. */ static PyObject * *************** *** 585,588 **** --- 626,639 ---- } + static void + set_time_fields(PyDateTime_Time *self, int h, int m, int s, int us) + { + self->hashcode = -1; + TIME_SET_HOUR(self, h); + TIME_SET_MINUTE(self, m); + TIME_SET_SECOND(self, s); + TIME_SET_MICROSECOND(self, us); + } + /* Create a time instance with no range checking. */ static PyObject * *************** *** 592,601 **** self = PyObject_New(PyDateTime_Time, &PyDateTime_TimeType); if (self != NULL) { ! self->hashcode = -1; ! TIME_SET_HOUR(self, hour); ! TIME_SET_MINUTE(self, minute); ! TIME_SET_SECOND(self, second); ! TIME_SET_MICROSECOND(self, usecond); } return (PyObject *) self; --- 643,663 ---- self = PyObject_New(PyDateTime_Time, &PyDateTime_TimeType); + if (self != NULL) + set_time_fields(self, hour, minute, second, usecond); + return (PyObject *) self; + } + + /* Create a timetz instance with no range checking. */ + static PyObject * + new_timetz(int hour, int minute, int second, int usecond, PyObject *tzinfo) + { + PyDateTime_TimeTZ *self; + + self = PyObject_New(PyDateTime_TimeTZ, &PyDateTime_TimeTZType); if (self != NULL) { ! set_time_fields((PyDateTime_Time *)self, ! hour, minute, second, usecond); ! Py_INCREF(tzinfo); ! self->tzinfo = tzinfo; } return (PyObject *) self; *************** *** 635,664 **** static PyObject *time_unpickler_object = NULL; static PyObject *timetz_unpickler_object = NULL; - - /* For obscure 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. - */ - static PyObject * - diff_to_bool(long diff, int op) - { - PyObject *result; - int istrue; - - switch (op) { - case Py_EQ: istrue = diff == 0; break; - case Py_NE: istrue = diff != 0; break; - case Py_LE: istrue = diff <= 0; break; - case Py_GE: istrue = diff >= 0; break; - case Py_LT: istrue = diff < 0; break; - case Py_GT: istrue = diff > 0; break; - default: - assert(! "op unknown"); - istrue = 0; /* To shut up compiler */ - } - result = istrue ? Py_True : Py_False; - Py_INCREF(result); - return result; - } #include "obj_delta.c" --- 697,700 ---- Index: datetime.h =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.h,v retrieving revision 1.14 retrieving revision 1.15 diff -C2 -d -r1.14 -r1.15 *** datetime.h 11 Dec 2002 01:47:20 -0000 1.14 --- datetime.h 11 Dec 2002 18:54:10 -0000 1.15 *************** *** 96,98 **** --- 96,100 ---- ((PyDateTime_Time*)o)->data[5]) + #define PyTZInfo_Check(op) PyObject_TypeCheck(op, &PyDateTime_TZInfoType) + #endif Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.43 retrieving revision 1.44 diff -C2 -d -r1.43 -r1.44 *** doc.txt 11 Dec 2002 01:47:20 -0000 1.43 --- doc.txt 11 Dec 2002 18:54:10 -0000 1.44 *************** *** 68,75 **** ! Docs ! ==== The datetime module supplies a number of classes for manipulating dates ! and times, in both simple and complex ways. class date --- 68,77 ---- ! Overview ! ======== The datetime module supplies a number of classes for manipulating dates ! and times, in both simple and complex ways. While date and time ! arithmetic is supported, the focus of the implementation is on efficient ! field extraction, for output formatting and manipulation. class date *************** *** 772,773 **** --- 774,780 ---- PyDateTime_TIME_GET_SECOND(o) PyDateTime_TIME_GET_MICROSECOND(o) + + For checking whether an object is a tzinfo instance; however, + note that Py_None is almost always allowed when a tzinfo argument + is expected: + PyTZInfo_Check(op) Index: obj_time.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_time.c,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** obj_time.c 9 Dec 2002 19:50:33 -0000 1.6 --- obj_time.c 11 Dec 2002 18:54:10 -0000 1.7 *************** *** 39,50 **** /* Constructors. */ static PyObject * time_new(PyTypeObject *type, PyObject *args, PyObject *kw) { PyObject *self = NULL; ! long hour = 0; ! long minute = 0; ! long second = 0; ! long usecond = 0; static char *keywords[] = { --- 39,79 ---- /* Constructors. */ + /* Check that time arguments are in range. Return 0 if they are. If they + * aren't, raise ValueError and return -1. + */ + static int + time_check_time_args(int h, int m, int s, int us) + { + if (h < 0 || h > 23) { + PyErr_SetString(PyExc_ValueError, + "hour must be in 0..23"); + return -1; + } + if (m < 0 || m > 59) { + PyErr_SetString(PyExc_ValueError, + "minute must be in 0..59"); + return -1; + } + if (s < 0 || s > 59) { + PyErr_SetString(PyExc_ValueError, + "second must be in 0..59"); + return -1; + } + if (us < 0 || us > 999999) { + PyErr_SetString(PyExc_ValueError, + "microsecond must be in 0..999999"); + return -1; + } + return 0; + } + static PyObject * time_new(PyTypeObject *type, PyObject *args, PyObject *kw) { PyObject *self = NULL; ! int hour = 0; ! int minute = 0; ! int second = 0; ! int usecond = 0; static char *keywords[] = { *************** *** 52,77 **** }; ! if (PyArg_ParseTupleAndKeywords(args, kw, "|llll", keywords, &hour, &minute, &second, &usecond)) { ! if (hour < 0 || hour > 23) { ! PyErr_SetString(PyExc_ValueError, ! "hour must be in 0..23"); ! return NULL; ! } ! if (minute < 0 || minute > 59) { ! PyErr_SetString(PyExc_ValueError, ! "minute must be in 0..59"); ! return NULL; ! } ! if (second < 0 || second > 59) { ! PyErr_SetString(PyExc_ValueError, ! "second must be in 0..59"); ! return NULL; ! } ! if (usecond < 0 || usecond > 999999) { ! PyErr_SetString(PyExc_ValueError, ! "microsecond must be in 0..999999"); return NULL; - } self = new_time(hour, minute, second, usecond); } --- 81,88 ---- }; ! if (PyArg_ParseTupleAndKeywords(args, kw, "|iiii", keywords, &hour, &minute, &second, &usecond)) { ! if (time_check_time_args(hour, minute, second, usecond) < 0) return NULL; self = new_time(hour, minute, second, usecond); } Index: obj_timetz.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_timetz.c,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** obj_timetz.c 11 Dec 2002 00:11:15 -0000 1.2 --- obj_timetz.c 11 Dec 2002 18:54:10 -0000 1.3 *************** *** 47,82 **** { PyObject *self = NULL; ! long hour = 0; ! long minute = 0; ! long second = 0; ! long usecond = 0; static char *keywords[] = { ! "hour", "minute", "second", "microsecond", NULL }; ! if (PyArg_ParseTupleAndKeywords(args, kw, "|llll", keywords, ! &hour, &minute, &second, &usecond)) { ! if (hour < 0 || hour > 23) { ! PyErr_SetString(PyExc_ValueError, ! "hour must be in 0..23"); ! return NULL; ! } ! if (minute < 0 || minute > 59) { ! PyErr_SetString(PyExc_ValueError, ! "minute must be in 0..59"); ! return NULL; ! } ! if (second < 0 || second > 59) { ! PyErr_SetString(PyExc_ValueError, ! "second must be in 0..59"); return NULL; ! } ! if (usecond < 0 || usecond > 999999) { ! PyErr_SetString(PyExc_ValueError, ! "microsecond must be in 0..999999"); return NULL; ! } ! self = new_time(hour, minute, second, usecond); } return self; --- 47,68 ---- { PyObject *self = NULL; ! int hour = 0; ! int minute = 0; ! int second = 0; ! int usecond = 0; ! PyObject *tzinfo = Py_None; static char *keywords[] = { ! "hour", "minute", "second", "microsecond", "tzinfo", NULL }; ! if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", keywords, ! &hour, &minute, &second, &usecond, ! &tzinfo)) { ! if (time_check_time_args(hour, minute, second, usecond) < 0) return NULL; ! if (check_tzinfo_subclass(tzinfo, "tzinfo argument") < 0) return NULL; ! self = new_timetz(hour, minute, second, usecond, tzinfo); } return self; From tim.one@comcast.net Wed Dec 11 19:03:43 2002 From: tim.one@comcast.net (Tim Peters) Date: Wed, 11 Dec 2002 14:03:43 -0500 Subject: [Python-checkins] python/dist/src/PCbuild pcbuild.dsw,1.31,1.32 In-Reply-To: <200212111810.gBBIAv217924@pcp02138704pcs.reston01.va.comcast.net> Message-ID: [MSVC stripped a bunch of quotes around filepaths in the WIndows Python project file] [Guido] > Could it be that you're using a different service pack or patch level > of MSV6 at home than at work? No, they're in synch. > I've seen things like this (seemingly random changes to project file > details) in the past too and always ignored them. That's especially true of the .wse installer script, but that's a different issue. In this case, I have a vague memory of someone deliberately adding quotes around the filepaths "by hand", so wanted to alter them I had just destroyed that. I suppose "someone" must be Mark Hammond, in which case he knows my address anyway . Maybe it's a VC7 versus VC6 thing. From tim_one@users.sourceforge.net Wed Dec 11 19:29:29 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 11 Dec 2002 11:29:29 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_timetz.c,1.3,1.4 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv21051 Modified Files: obj_timetz.c Log Message: Moving timetz a teensy bit closer to usefulness. Index: obj_timetz.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_timetz.c,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** obj_timetz.c 11 Dec 2002 18:54:10 -0000 1.3 --- obj_timetz.c 11 Dec 2002 19:29:26 -0000 1.4 *************** *** 2,5 **** --- 2,6 ---- * XXX This is a copy and very light edit of obj_time.c. * XXX The tzinfo base clase has to get implemented first. + * XXX OK, that part got done. This is slowly becoming functional now. */ /* *************** *** 7,41 **** */ ! /* Accessor properties. */ ! ! static PyObject * ! timetz_hour(PyDateTime_TimeTZ *self, void *unused) ! { ! return PyInt_FromLong(TIME_GET_HOUR(self)); ! } ! ! static PyObject * ! timetz_minute(PyDateTime_TimeTZ *self, void *unused) ! { ! return PyInt_FromLong(TIME_GET_MINUTE(self)); ! } ! ! static PyObject * ! timetz_second(PyDateTime_TimeTZ *self, void *unused) ! { ! return PyInt_FromLong(TIME_GET_SECOND(self)); ! } static PyObject * ! timetz_microsecond(PyDateTime_TimeTZ *self, void *unused) { ! return PyInt_FromLong(TIME_GET_MICROSECOND(self)); } static PyGetSetDef timetz_getset[] = { ! {"hour", (getter)timetz_hour}, ! {"minute", (getter)timetz_minute}, ! {"second", (getter)timetz_second}, ! {"microsecond", (getter)timetz_microsecond}, {NULL} }; --- 8,24 ---- */ ! /* Accessor properties. Properties for hour, minute, second and microsecond ! * are inherited from time. ! */ static PyObject * ! timetz_tzinfo(PyDateTime_TimeTZ *self, void *unused) { ! Py_INCREF(self->tzinfo); ! return self->tzinfo; } static PyGetSetDef timetz_getset[] = { ! {"tzinfo", (getter)timetz_tzinfo}, {NULL} }; *************** *** 286,290 **** 0, /* ob_size */ /* XXX When this module is renamed to datetime, change tp_name. */ ! "_datetime.time", /* tp_name */ sizeof(PyDateTime_TimeTZ), /* tp_basicsize */ 0, /* tp_itemsize */ --- 269,273 ---- 0, /* ob_size */ /* XXX When this module is renamed to datetime, change tp_name. */ ! "_datetime.timetz", /* tp_name */ sizeof(PyDateTime_TimeTZ), /* tp_basicsize */ 0, /* tp_itemsize */ *************** *** 313,319 **** 0, /* tp_iter */ 0, /* tp_iternext */ ! time_methods, /* tp_methods */ 0, /* tp_members */ ! time_getset, /* tp_getset */ &PyDateTime_TimeType, /* tp_base */ 0, /* tp_dict */ --- 296,302 ---- 0, /* tp_iter */ 0, /* tp_iternext */ ! timetz_methods, /* tp_methods */ 0, /* tp_members */ ! timetz_getset, /* tp_getset */ &PyDateTime_TimeType, /* tp_base */ 0, /* tp_dict */ From loewis@users.sourceforge.net Wed Dec 11 19:55:51 2002 From: loewis@users.sourceforge.net (loewis@users.sourceforge.net) Date: Wed, 11 Dec 2002 11:55:51 -0800 Subject: [Python-checkins] python/dist/src/Modules license.terms,2.1,NONE tclNotify.c,2.3,NONE Message-ID: Update of /cvsroot/python/python/dist/src/Modules In directory sc8-pr-cvs1:/tmp/cvs-serv30101 Removed Files: license.terms tclNotify.c Log Message: This is not used anymore. --- license.terms DELETED --- --- tclNotify.c DELETED --- From tim_one@users.sourceforge.net Wed Dec 11 20:58:00 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 11 Dec 2002 12:58:00 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.c,1.55,1.56 doc.txt,1.44,1.45 obj_timetz.c,1.4,1.5 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv21360 Modified Files: datetime.c doc.txt obj_timetz.c Log Message: Brrrrrrrrrr. Index: datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.c,v retrieving revision 1.55 retrieving revision 1.56 diff -C2 -d -r1.55 -r1.56 *** datetime.c 11 Dec 2002 18:54:10 -0000 1.55 --- datetime.c 11 Dec 2002 20:57:57 -0000 1.56 *************** *** 693,696 **** --- 693,779 ---- } + /* Helpers for dealing with calling tzinfo methods. */ + + /* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the + * result. tzinfo must be an instance of the tzinfo class. If utcoffset() + * returns None, get_utcoffset returns 0. If uctoffset() doesn't return + * a Python int or long, TypeError is raised and this returns -1. If + * utcoffset() returns an int outside the legitimate range for a UTC offset, + * ValueError is raised and this returns -1. + */ + static long + get_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg) + { + PyObject *u; + long result = -1; + + assert(tzinfo != NULL); + assert(PyTZInfo_Check(tzinfo)); + assert(tzinfoarg != NULL); + + u = PyObject_CallMethod(tzinfo, "utcoffset", "O", tzinfoarg); + if (u == NULL) + return -1; + + if (u == Py_None) { + result = 0; + goto Done; + } + + if (PyInt_Check(u)) + result = PyInt_AS_LONG(u); + else if (PyLong_Check(u)) + result = PyLong_AsLong(u); + else { + PyErr_SetString(PyExc_TypeError, + "utcoffset() must return None or int or long"); + goto Done; + } + + if (result < -1439 || result > 1439) { + PyErr_Format(PyExc_ValueError, + "utcoffset() returned %ld; must be in " + "-1439 .. 1439", + result); + result = -1; + } + + Done: + Py_DECREF(u); + return result; + } + + /* Add an hours & minutes UTC offset string to buf. buf has no more than + * buflen bytes remaining. The UTC offset is gotten by calling + * tzinfo.uctoffset(tzinfoarg). If that returns None, nothing is done. + * Else the returned value is checked for sanity (an integer in range), + * and if that's OK it's converted to an hours & minutes string of the + * form + * sign HH sep MM + * Returns 0 if everything is OK. If the return value from utcoffset() is + * bogus, an appropriate exception is set and -1 is returned. + */ + static int + format_timezone(char *buf, int buflen, const char *sep, + PyObject *tzinfo, PyObject *tzinfoarg) + { + long offset; + long hours; + long minutes; + char sign; + + offset = get_utcoffset(tzinfo, tzinfoarg); + if (offset == -1 && PyErr_Occurred()) + return -1; + sign = '+'; + if (offset < 0) { + sign = '-'; + offset = - offset; + } + hours = divmod(offset, 60, &minutes); + PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes); + return 0; + } + static PyObject *date_unpickler_object = NULL; static PyObject *datetime_unpickler_object = NULL; Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.44 retrieving revision 1.45 diff -C2 -d -r1.44 -r1.45 *** doc.txt 11 Dec 2002 18:54:10 -0000 1.44 --- doc.txt 11 Dec 2002 20:57:58 -0000 1.45 *************** *** 712,717 **** is intended to be the total offset from UTC; for example, if a tzinfo object represents both time zone and DST adjustments, ! utcoffset() should return their sum. Return None if the UTC offset ! isn't known. - tzname(dt) --- 712,719 ---- is intended to be the total offset from UTC; for example, if a tzinfo object represents both time zone and DST adjustments, ! utcoffset() should return their sum. If the UTC offset isn't known, ! return None. Else the value returned must be an int (or long), in ! the range -1439 to 1439 inclusive (1440 = 24*60; the magnitude of ! the offset must be less than one day). - tzname(dt) Index: obj_timetz.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_timetz.c,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** obj_timetz.c 11 Dec 2002 19:29:26 -0000 1.4 --- obj_timetz.c 11 Dec 2002 20:57:58 -0000 1.5 *************** *** 57,78 **** timetz_repr(PyDateTime_TimeTZ *self) { ! char buffer[100]; ! char *typename = self->ob_type->tp_name; ! int h = TIME_GET_HOUR(self); ! int m = TIME_GET_MINUTE(self); ! int s = TIME_GET_SECOND(self); ! int us = TIME_GET_MICROSECOND(self); ! if (us) ! PyOS_snprintf(buffer, sizeof(buffer), ! "%s(%d, %d, %d, %d)", typename, h, m, s, us); ! else if (s) ! PyOS_snprintf(buffer, sizeof(buffer), ! "%s(%d, %d, %d)", typename, h, m, s); ! else ! PyOS_snprintf(buffer, sizeof(buffer), ! "%s(%d, %d)", typename, h, m); ! return PyString_FromString(buffer); ! } static PyObject * --- 57,102 ---- timetz_repr(PyDateTime_TimeTZ *self) { ! PyObject *r; ! PyObject *result = time_repr((PyDateTime_Time *)self); ! if (result == NULL) ! return NULL; ! if (self->tzinfo == Py_None) ! return result; ! /* We have to append tzinfo=repr(tzinfo). */ ! /* Get rid of the trailing ')'. */ ! assert(PyString_AsString(result)[PyString_Size(result)-1] == ')'); ! r = PyString_FromStringAndSize(PyString_AsString(result), ! PyString_Size(result) - 1); ! Py_DECREF(result); ! if (r == NULL) ! return NULL; ! result = r; ! ! /* Append ", tzinfo=". */ ! r = PyString_FromString(", tzinfo="); ! if (r == NULL) { ! Py_DECREF(result); ! return NULL; ! } ! PyString_ConcatAndDel(&result, r); ! ! /* Append repr(tzinfo). */ ! r = PyObject_Repr(self->tzinfo); ! if (r == NULL) { ! Py_DECREF(result); ! return NULL; ! } ! PyString_ConcatAndDel(&result, r); ! ! /* Add a closing paren. */ ! r = PyString_FromString(")"); ! if (r == NULL) { ! Py_DECREF(result); ! return NULL; ! } ! PyString_ConcatAndDel(&result, r); ! return result; ! } static PyObject * From jhylton@users.sourceforge.net Wed Dec 11 21:28:34 2002 From: jhylton@users.sourceforge.net (jhylton@users.sourceforge.net) Date: Wed, 11 Dec 2002 13:28:34 -0800 Subject: [Python-checkins] python/dist/src/Tools/scripts trace.py,1.10,1.11 Message-ID: Update of /cvsroot/python/python/dist/src/Tools/scripts In directory sc8-pr-cvs1:/tmp/cvs-serv1182 Modified Files: trace.py Log Message: Fix one bug and reformat lots of code. The bug is a reference to co_first_lineno that should be co_firstlineno. The only other substantial change is to speed up localtrace_count() by avoiding *costly* calls to inspect module. It's trivial to get the filename and lineno directly from the frame. Otherwise, delete commented out debug code and reflow very long lines. Index: trace.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Tools/scripts/trace.py,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** trace.py 22 Nov 2002 09:10:33 -0000 1.10 --- trace.py 11 Dec 2002 21:28:32 -0000 1.11 *************** *** 28,34 **** # distribution of the software without specific, written prior permission. # ! ! """ ! program/module to trace Python program or function execution Sample use, command line: --- 28,32 ---- # distribution of the software without specific, written prior permission. # ! """program/module to trace Python program or function execution Sample use, command line: *************** *** 37,43 **** Sample use, programmatically ! # create a Trace object, telling it what to ignore, and whether to do tracing ! # or line-counting or both. ! trace = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,], trace=0, count=1) # run the new command using the given trace trace.run(coverage.globaltrace, 'main()') --- 35,42 ---- Sample use, programmatically ! # create a Trace object, telling it what to ignore, and whether to ! # do tracing or line-counting or both. ! trace = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix,], trace=0, ! count=1) # run the new command using the given trace trace.run(coverage.globaltrace, 'main()') *************** *** 168,174 **** self.update(self.__class__(thingie)) elif type(thingie) is types.TupleType and len(thingie) == 2: ! (counts, calledfuncs,) = thingie self.update(self.__class__(counts, calledfuncs)) ! except (IOError, EOFError,): pass except pickle.UnpicklingError: --- 167,173 ---- self.update(self.__class__(thingie)) elif type(thingie) is types.TupleType and len(thingie) == 2: ! counts, calledfuncs = thingie self.update(self.__class__(counts, calledfuncs)) ! except (IOError, EOFError): pass except pickle.UnpicklingError: *************** *** 194,199 **** @param coverdir """ ! for (filename, modulename, funcname,) in self.calledfuncs.keys(): ! print "filename: %s, modulename: %s, funcname: %s" % (filename, modulename, funcname,) import re --- 193,199 ---- @param coverdir """ ! for filename, modulename, funcname in self.calledfuncs.keys(): ! print ("filename: %s, modulename: %s, funcname: %s" ! % (filename, modulename, funcname)) import re *************** *** 202,207 **** per_file = {} for thingie in self.counts.keys(): ! if thingie != "calledfuncs": # backwards compatibility for abortive attempt to stuff calledfuncs into self.counts, by Zooko --Zooko 2001-10-24 ! (filename, lineno,) = thingie lines_hit = per_file[filename] = per_file.get(filename, {}) lines_hit[lineno] = self.counts[(filename, lineno)] --- 202,210 ---- per_file = {} for thingie in self.counts.keys(): ! if thingie != "calledfuncs": ! # backwards compatibility for abortive attempt to ! # stuff calledfuncs into self.counts, by Zooko --Zooko ! # 2001-10-24 ! filename, lineno = thingie lines_hit = per_file[filename] = per_file.get(filename, {}) lines_hit[lineno] = self.counts[(filename, lineno)] *************** *** 328,332 **** # try and store counts and module info into self.outfile try: ! pickle.dump((self.counts, self.calledfuncs,), open(self.outfile, 'w'), 1) except IOError, err: sys.stderr.write("cannot save counts files because %s" % err) --- 331,336 ---- # try and store counts and module info into self.outfile try: ! pickle.dump((self.counts, self.calledfuncs), ! open(self.outfile, 'w'), 1) except IOError, err: sys.stderr.write("cannot save counts files because %s" % err) *************** *** 340,344 **** table_length = len(line_increments) ! lineno = code.co_first_lineno for li in line_increments: --- 344,348 ---- table_length = len(line_increments) ! lineno = code.co_firstlineno for li in line_increments: *************** *** 466,470 **** """ if why == 'call': ! (filename, lineno, funcname, context, lineindex,) = inspect.getframeinfo(frame, 0) if filename: modulename = inspect.getmodulename(filename) --- 470,475 ---- """ if why == 'call': ! filename, lineno, funcname, context, lineindex = \ ! inspect.getframeinfo(frame, 0) if filename: modulename = inspect.getmodulename(filename) *************** *** 478,496 **** """ if why == 'call': ! (filename, lineno, funcname, context, lineindex,) = inspect.getframeinfo(frame, 0) ! # if DEBUG_MODE and not filename: ! # print "%s.globaltrace(frame: %s, why: %s, arg: %s): filename: %s, lineno: %s, funcname: %s, context: %s, lineindex: %s\n" % (self, frame, why, arg, filename, lineno, funcname, context, lineindex,) if filename: modulename = inspect.getmodulename(filename) if modulename is not None: ignore_it = self.ignore.names(filename, modulename) - # if DEBUG_MODE and not self.blabbed.has_key((filename, modulename,)): - # self.blabbed[(filename, modulename,)] = None - # print "%s.globaltrace(frame: %s, why: %s, arg: %s, filename: %s, modulename: %s, ignore_it: %s\n" % (self, frame, why, arg, filename, modulename, ignore_it,) if not ignore_it: if self.trace: ! print " --- modulename: %s, funcname: %s" % (modulename, funcname,) ! # if DEBUG_MODE: ! # print "%s.globaltrace(frame: %s, why: %s, arg: %s, filename: %s, modulename: %s, ignore_it: %s -- about to localtrace\n" % (self, frame, why, arg, filename, modulename, ignore_it,) return self.localtrace else: --- 483,496 ---- """ if why == 'call': ! filename, lineno, funcname, context, lineindex = \ ! inspect.getframeinfo(frame, 0) if filename: modulename = inspect.getmodulename(filename) if modulename is not None: ignore_it = self.ignore.names(filename, modulename) if not ignore_it: if self.trace: ! print (" --- modulename: %s, funcname: %s" ! % (modulename, funcname)) return self.localtrace else: *************** *** 501,517 **** if why == 'line': # record the file name and line number of every trace ! # XXX I wish inspect offered me an optimized `getfilename(frame)' to use in place of the presumably heavier `getframeinfo()'. --Zooko 2001-10-14 ! (filename, lineno, funcname, context, lineindex,) = inspect.getframeinfo(frame, 1) key = (filename, lineno,) self.counts[key] = self.counts.get(key, 0) + 1 ! # XXX not convinced that this memoizing is a performance win -- I don't know enough about Python guts to tell. --Zooko 2001-10-14 bname = self.pathtobasename.get(filename) if bname is None: ! # Using setdefault faster than two separate lines? --Zooko 2001-10-14 ! bname = self.pathtobasename.setdefault(filename, os.path.basename(filename)) try: ! print "%s(%d): %s" % (bname, lineno, context[lineindex],), except IndexError: ! # Uh.. sometimes getframeinfo gives me a context of length 1 and a lineindex of -2. Oh well. pass return self.localtrace --- 501,529 ---- if why == 'line': # record the file name and line number of every trace ! # XXX I wish inspect offered me an optimized ! # `getfilename(frame)' to use in place of the presumably ! # heavier `getframeinfo()'. --Zooko 2001-10-14 ! ! filename, lineno, funcname, context, lineindex = \ ! inspect.getframeinfo(frame, 1) key = (filename, lineno,) self.counts[key] = self.counts.get(key, 0) + 1 ! ! # XXX not convinced that this memoizing is a performance ! # win -- I don't know enough about Python guts to tell. ! # --Zooko 2001-10-14 ! bname = self.pathtobasename.get(filename) if bname is None: ! ! # Using setdefault faster than two separate lines? ! # --Zooko 2001-10-14 ! bname = self.pathtobasename.setdefault(filename, ! os.path.basename(filename)) try: ! print "%s(%d): %s" % (bname, lineno, context[lineindex]), except IndexError: ! # Uh.. sometimes getframeinfo gives me a context of ! # length 1 and a lineindex of -2. Oh well. pass return self.localtrace *************** *** 519,536 **** def localtrace_trace(self, frame, why, arg): if why == 'line': ! # XXX shouldn't do the count increment when arg is exception? But be careful to return self.localtrace when arg is exception! ? --Zooko 2001-10-14 ! # record the file name and line number of every trace ! # XXX I wish inspect offered me an optimized `getfilename(frame)' to use in place of the presumably heavier `getframeinfo()'. --Zooko 2001-10-14 ! (filename, lineno, funcname, context, lineindex,) = inspect.getframeinfo(frame) ! # if DEBUG_MODE: ! # print "%s.localtrace_trace(frame: %s, why: %s, arg: %s); filename: %s, lineno: %s, funcname: %s, context: %s, lineindex: %s\n" % (self, frame, why, arg, filename, lineno, funcname, context, lineindex,) ! # XXX not convinced that this memoizing is a performance win -- I don't know enough about Python guts to tell. --Zooko 2001-10-14 bname = self.pathtobasename.get(filename) if bname is None: ! # Using setdefault faster than two separate lines? --Zooko 2001-10-14 bname = self.pathtobasename.setdefault(filename, os.path.basename(filename)) if context is not None: try: ! print "%s(%d): %s" % (bname, lineno, context[lineindex],), except IndexError: # Uh.. sometimes getframeinfo gives me a context of length 1 and a lineindex of -2. Oh well. --- 531,556 ---- def localtrace_trace(self, frame, why, arg): if why == 'line': ! # XXX shouldn't do the count increment when arg is ! # exception? But be careful to return self.localtrace ! # when arg is exception! ? --Zooko 2001-10-14 ! ! # record the file name and line number of every trace XXX ! # I wish inspect offered me an optimized ! # `getfilename(frame)' to use in place of the presumably ! # heavier `getframeinfo()'. --Zooko 2001-10-14 ! filename, lineno, funcname, context, lineindex = \ ! inspect.getframeinfo(frame) ! ! # XXX not convinced that this memoizing is a performance ! # win -- I don't know enough about Python guts to tell. ! # --Zooko 2001-10-14 bname = self.pathtobasename.get(filename) if bname is None: ! # Using setdefault faster than two separate lines? ! # --Zooko 2001-10-14 bname = self.pathtobasename.setdefault(filename, os.path.basename(filename)) if context is not None: try: ! print "%s(%d): %s" % (bname, lineno, context[lineindex]), except IndexError: # Uh.. sometimes getframeinfo gives me a context of length 1 and a lineindex of -2. Oh well. *************** *** 542,555 **** def localtrace_count(self, frame, why, arg): if why == 'line': ! # XXX shouldn't do the count increment when arg is exception? But be careful to return self.localtrace when arg is exception! ? --Zooko 2001-10-14 ! # record the file name and line number of every trace ! # XXX I wish inspect offered me an optimized `getfilename(frame)' to use in place of the presumably heavier `getframeinfo()'. --Zooko 2001-10-14 ! (filename, lineno, funcname, context, lineindex,) = inspect.getframeinfo(frame) ! key = (filename, lineno,) self.counts[key] = self.counts.get(key, 0) + 1 return self.localtrace def results(self): ! return CoverageResults(self.counts, infile=self.infile, outfile=self.outfile, calledfuncs=self._calledfuncs) def _err_exit(msg): --- 562,575 ---- def localtrace_count(self, frame, why, arg): if why == 'line': ! filename = frame.f_code.co_filename ! lineno = frame.f_lineno ! key = filename, lineno self.counts[key] = self.counts.get(key, 0) + 1 return self.localtrace def results(self): ! return CoverageResults(self.counts, infile=self.infile, ! outfile=self.outfile, ! calledfuncs=self._calledfuncs) def _err_exit(msg): *************** *** 572,576 **** except getopt.error, msg: sys.stderr.write("%s: %s\n" % (sys.argv[0], msg)) ! sys.stderr.write("Try `%s --help' for more information\n" % sys.argv[0]) sys.exit(1) --- 592,597 ---- except getopt.error, msg: sys.stderr.write("%s: %s\n" % (sys.argv[0], msg)) ! sys.stderr.write("Try `%s --help' for more information\n" ! % sys.argv[0]) sys.exit(1) *************** *** 675,682 **** sys.argv = prog_argv progname = prog_argv[0] ! if eval(sys.version[:3])>1.3: ! sys.path[0] = os.path.split(progname)[0] # ??? ! t = Trace(count, trace, countfuncs=listfuncs, ignoremods=ignore_modules, ignoredirs=ignore_dirs, infile=counts_file, outfile=counts_file) try: t.run('execfile(' + `progname` + ')') --- 696,704 ---- sys.argv = prog_argv progname = prog_argv[0] ! sys.path[0] = os.path.split(progname)[0] ! t = Trace(count, trace, countfuncs=listfuncs, ! ignoremods=ignore_modules, ignoredirs=ignore_dirs, ! infile=counts_file, outfile=counts_file) try: t.run('execfile(' + `progname` + ')') From tim_one@users.sourceforge.net Wed Dec 11 21:29:58 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 11 Dec 2002 13:29:58 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.c,1.56,1.57 obj_timetz.c,1.5,1.6 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv1641 Modified Files: datetime.c obj_timetz.c Log Message: timetz repr(), str() and isoformat() may be working now. Index: datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.c,v retrieving revision 1.56 retrieving revision 1.57 diff -C2 -d -r1.56 -r1.57 *** datetime.c 11 Dec 2002 20:57:57 -0000 1.56 --- datetime.c 11 Dec 2002 21:29:56 -0000 1.57 *************** *** 755,759 **** */ static int ! format_timezone(char *buf, int buflen, const char *sep, PyObject *tzinfo, PyObject *tzinfoarg) { --- 755,759 ---- */ static int ! format_utcoffset(char *buf, int buflen, const char *sep, PyObject *tzinfo, PyObject *tzinfoarg) { Index: obj_timetz.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_timetz.c,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** obj_timetz.c 11 Dec 2002 20:57:58 -0000 1.5 --- obj_timetz.c 11 Dec 2002 21:29:56 -0000 1.6 *************** *** 100,124 **** } ! static PyObject * ! timetz_str(PyDateTime_TimeTZ *self) ! { ! return PyObject_CallMethod((PyObject *)self, "isoformat", "()"); ! } static PyObject * timetz_isoformat(PyDateTime_TimeTZ *self) { ! char buffer[100]; ! /* Reuse the time format code from the datetime type. */ ! PyDateTime_DateTime datetime; ! PyDateTime_DateTime *pdatetime = &datetime; ! /* Copy over just the time bytes. */ ! memcpy(pdatetime->data + _PyDateTime_DATE_DATASIZE, ! self->data, ! _PyDateTime_TIME_DATASIZE); ! isoformat_time(pdatetime, buffer, sizeof(buffer)); ! return PyString_FromString(buffer); } --- 100,124 ---- } ! /* Note: tp_str is inherited from time. */ static PyObject * timetz_isoformat(PyDateTime_TimeTZ *self) { ! char buf[100]; ! PyObject *result = time_isoformat((PyDateTime_Time *)self); ! if (result == NULL) ! return NULL; ! if (self->tzinfo == Py_None) ! return result; ! /* We need to append the UTC offset. */ ! if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo, ! (PyObject *)self) < 0) { ! Py_DECREF(result); ! return NULL; ! } ! PyString_ConcatAndDel(&result, PyString_FromString(buf)); ! return result; } *************** *** 307,311 **** (hashfunc)timetz_hash, /* tp_hash */ 0, /* tp_call */ ! (reprfunc)timetz_str, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ --- 307,311 ---- (hashfunc)timetz_hash, /* tp_hash */ 0, /* tp_call */ ! 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ 0, /* tp_setattro */ From tim_one@users.sourceforge.net Wed Dec 11 21:34:50 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 11 Dec 2002 13:34:50 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_timetz.c,1.6,1.7 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv3630 Modified Files: obj_timetz.c Log Message: timetz_repr(): Simplified some of this excruciating code. PyString_ConcatAndDel is happy to accept NULL arguments, so there's really no need for error-checking after every teensy step here. Index: obj_timetz.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_timetz.c,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** obj_timetz.c 11 Dec 2002 21:29:56 -0000 1.6 --- obj_timetz.c 11 Dec 2002 21:34:48 -0000 1.7 *************** *** 75,100 **** /* Append ", tzinfo=". */ ! r = PyString_FromString(", tzinfo="); ! if (r == NULL) { ! Py_DECREF(result); ! return NULL; ! } ! PyString_ConcatAndDel(&result, r); /* Append repr(tzinfo). */ ! r = PyObject_Repr(self->tzinfo); ! if (r == NULL) { ! Py_DECREF(result); ! return NULL; ! } ! PyString_ConcatAndDel(&result, r); /* Add a closing paren. */ ! r = PyString_FromString(")"); ! if (r == NULL) { ! Py_DECREF(result); ! return NULL; ! } ! PyString_ConcatAndDel(&result, r); return result; } --- 75,85 ---- /* Append ", tzinfo=". */ ! PyString_ConcatAndDel(&result, PyString_FromString(", tzinfo=")); /* Append repr(tzinfo). */ ! PyString_ConcatAndDel(&result, PyObject_Repr(self->tzinfo)); /* Add a closing paren. */ ! PyString_ConcatAndDel(&result, PyString_FromString(")")); return result; } From jhylton@users.sourceforge.net Wed Dec 11 21:43:15 2002 From: jhylton@users.sourceforge.net (jhylton@users.sourceforge.net) Date: Wed, 11 Dec 2002 13:43:15 -0800 Subject: [Python-checkins] python/dist/src/Tools/scripts trace.py,1.11,1.12 Message-ID: Update of /cvsroot/python/python/dist/src/Tools/scripts In directory sc8-pr-cvs1:/tmp/cvs-serv6880 Modified Files: trace.py Log Message: Correct buggy module docstring. Replace use of homebrew boolean with True/False. Reflow lots more long lines. Index: trace.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Tools/scripts/trace.py,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** trace.py 11 Dec 2002 21:28:32 -0000 1.11 --- trace.py 11 Dec 2002 21:43:13 -0000 1.12 *************** *** 42,46 **** trace.run(coverage.globaltrace, 'main()') # make a report, telling it where you want output ! trace.print_results(show_missing=1) """ --- 42,47 ---- trace.run(coverage.globaltrace, 'main()') # make a report, telling it where you want output ! r = trace.results() ! r.write_results(show_missing=1) """ *************** *** 52,58 **** import pickle - true = 1 - false = None - # DEBUG_MODE=1 # make this true to get printouts which help you understand what's going on --- 53,56 ---- *************** *** 148,152 **** class CoverageResults: ! def __init__(self, counts=None, calledfuncs=None, infile=None, outfile=None): self.counts = counts if self.counts is None: --- 146,151 ---- class CoverageResults: ! def __init__(self, counts=None, calledfuncs=None, infile=None, ! outfile=None): self.counts = counts if self.counts is None: *************** *** 164,168 **** thingie = pickle.load(open(self.infile, 'r')) if type(thingie) is types.DictType: ! # backwards compatibility for old trace.py after Zooko touched it but before calledfuncs --Zooko 2001-10-24 self.update(self.__class__(thingie)) elif type(thingie) is types.TupleType and len(thingie) == 2: --- 163,169 ---- thingie = pickle.load(open(self.infile, 'r')) if type(thingie) is types.DictType: ! # backwards compatibility for old trace.py after ! # Zooko touched it but before calledfuncs --Zooko ! # 2001-10-24 self.update(self.__class__(thingie)) elif type(thingie) is types.TupleType and len(thingie) == 2: *************** *** 172,176 **** pass except pickle.UnpicklingError: ! # backwards compatibility for old trace.py before Zooko touched it --Zooko 2001-10-24 self.update(self.__class__(marshal.load(open(self.infile)))) --- 173,178 ---- pass except pickle.UnpicklingError: ! # backwards compatibility for old trace.py before ! # Zooko touched it --Zooko 2001-10-24 self.update(self.__class__(marshal.load(open(self.infile)))) *************** *** 183,187 **** for key in other_counts.keys(): ! if key != 'calledfuncs': # backwards compatibility for abortive attempt to stuff calledfuncs into self.counts, by Zooko --Zooko 2001-10-24 counts[key] = counts.get(key, 0) + other_counts[key] --- 185,192 ---- for key in other_counts.keys(): ! if key != 'calledfuncs': ! # backwards compatibility for abortive attempt to ! # stuff calledfuncs into self.counts, by Zooko ! # --Zooko 2001-10-24 counts[key] = counts.get(key, 0) + other_counts[key] *************** *** 398,409 **** class Trace: ! def __init__(self, count=1, trace=1, countfuncs=0, ignoremods=(), ignoredirs=(), infile=None, outfile=None): """ ! @param count true iff it should count number of times each line is executed ! @param trace true iff it should print out each line that is being counted ! @param countfuncs true iff it should just output a list of (filename, modulename, funcname,) for functions that were called at least once; This overrides `count' and `trace' @param ignoremods a list of the names of modules to ignore ! @param ignoredirs a list of the names of directories to ignore all of the (recursive) contents of ! @param infile file from which to read stored counts to be added into the results @param outfile file in which to write the results """ --- 403,422 ---- class Trace: ! def __init__(self, count=1, trace=1, countfuncs=0, ignoremods=(), ! ignoredirs=(), infile=None, outfile=None): """ ! @param count true iff it should count number of times each ! line is executed ! @param trace true iff it should print out each line that is ! being counted ! @param countfuncs true iff it should just output a list of ! (filename, modulename, funcname,) for functions ! that were called at least once; This overrides ! `count' and `trace' @param ignoremods a list of the names of modules to ignore ! @param ignoredirs a list of the names of directories to ignore ! all of the (recursive) contents of ! @param infile file from which to read stored counts to be ! added into the results @param outfile file in which to write the results """ *************** *** 507,511 **** filename, lineno, funcname, context, lineindex = \ inspect.getframeinfo(frame, 1) ! key = (filename, lineno,) self.counts[key] = self.counts.get(key, 0) + 1 --- 520,524 ---- filename, lineno, funcname, context, lineindex = \ inspect.getframeinfo(frame, 1) ! key = filename, lineno self.counts[key] = self.counts.get(key, 0) + 1 *************** *** 606,610 **** coverdir = None summary = 0 ! listfuncs = false for opt, val in opts: --- 619,623 ---- coverdir = None summary = 0 ! listfuncs = False for opt, val in opts: *************** *** 618,622 **** if opt == "-l" or opt == "--listfuncs": ! listfuncs = true continue --- 631,635 ---- if opt == "-l" or opt == "--listfuncs": ! listfuncs = True continue From tim_one@users.sourceforge.net Wed Dec 11 21:47:41 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 11 Dec 2002 13:47:41 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.c,1.57,1.58 datetime.py,1.92,1.93 test_both.py,1.58,1.59 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv8566 Modified Files: datetime.c datetime.py test_both.py Log Message: Started added timetz tests to test_both. Changed the Python timetz to default all arguments to 0. Changed the C internals so that a uctoffset() call returning None can be distinguished from a call returning 0. Index: datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.c,v retrieving revision 1.57 retrieving revision 1.58 diff -C2 -d -r1.57 -r1.58 *** datetime.c 11 Dec 2002 21:29:56 -0000 1.57 --- datetime.c 11 Dec 2002 21:47:38 -0000 1.58 *************** *** 697,707 **** /* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the * result. tzinfo must be an instance of the tzinfo class. If utcoffset() ! * returns None, get_utcoffset returns 0. If uctoffset() doesn't return ! * a Python int or long, TypeError is raised and this returns -1. If ! * utcoffset() returns an int outside the legitimate range for a UTC offset, ! * ValueError is raised and this returns -1. */ static long ! get_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg) { PyObject *u; --- 697,708 ---- /* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the * result. tzinfo must be an instance of the tzinfo class. If utcoffset() ! * returns None, get_utcoffset returns 0 and sets *none to 1. If uctoffset() ! & doesn't return a Python int or long, TypeError is raised and this ! * returns -1. If utcoffset() returns an int outside the legitimate range ! * for a UTC offset, ValueError is raised and this returns -1. Else ! * *none is set to 0 and the offset is returned. */ static long ! get_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg, int *none) { PyObject *u; *************** *** 712,715 **** --- 713,717 ---- assert(tzinfoarg != NULL); + *none = 0; u = PyObject_CallMethod(tzinfo, "utcoffset", "O", tzinfoarg); if (u == NULL) *************** *** 718,721 **** --- 720,724 ---- if (u == Py_None) { result = 0; + *none = 1; goto Done; } *************** *** 762,769 **** long minutes; char sign; ! offset = get_utcoffset(tzinfo, tzinfoarg); if (offset == -1 && PyErr_Occurred()) return -1; sign = '+'; if (offset < 0) { --- 765,775 ---- long minutes; char sign; + int none; ! offset = get_utcoffset(tzinfo, tzinfoarg, &none); if (offset == -1 && PyErr_Occurred()) return -1; + if (none) + return 0; sign = '+'; if (offset < 0) { Index: datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.py,v retrieving revision 1.92 retrieving revision 1.93 diff -C2 -d -r1.92 -r1.93 *** datetime.py 10 Dec 2002 20:44:23 -0000 1.92 --- datetime.py 11 Dec 2002 21:47:38 -0000 1.93 *************** *** 892,896 **** """ ! def __init__(self, hour, minute, second=0, microsecond=0, tzinfo=None): """Constructor. --- 892,896 ---- """ ! def __init__(self, hour=0, minute=0, second=0, microsecond=0, tzinfo=None): """Constructor. Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.58 retrieving revision 1.59 diff -C2 -d -r1.58 -r1.59 *** test_both.py 11 Dec 2002 01:47:20 -0000 1.58 --- test_both.py 11 Dec 2002 21:47:39 -0000 1.59 *************** *** 42,45 **** --- 42,46 ---- time = datetime.time tzinfo = datetime.tzinfo + timetz = datetime.timetz MINYEAR = datetime.MINYEAR MAXYEAR = datetime.MAXYEAR *************** *** 1439,1442 **** --- 1440,1457 ---- self.failUnless(not cls()) + + class TestTimeTZ(unittest.TestCase): + + theclass = timetz + + def test_empty(self): + t = self.theclass() + self.assertEqual(t.hour, 0) + self.assertEqual(t.minute, 0) + self.assertEqual(t.second, 0) + self.assertEqual(t.microsecond, 0) + self.assertEqual(t.tzinfo, None) + + def test_suite(): allsuites = [unittest.makeSuite(klass, 'test') *************** *** 1448,1451 **** --- 1463,1467 ---- TestDateTime, TestTime, + TestTimeTZ, ) ] From tim_one@users.sourceforge.net Wed Dec 11 22:09:58 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 11 Dec 2002 14:09:58 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime test_both.py,1.59,1.60 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv17756 Modified Files: test_both.py Log Message: Test that timtz's tzinfo= arg requires a tzinfo subclass instance. Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.59 retrieving revision 1.60 diff -C2 -d -r1.59 -r1.60 *** test_both.py 11 Dec 2002 21:47:39 -0000 1.59 --- test_both.py 11 Dec 2002 22:09:56 -0000 1.60 *************** *** 1451,1456 **** self.assertEqual(t.second, 0) self.assertEqual(t.microsecond, 0) ! self.assertEqual(t.tzinfo, None) def test_suite(): --- 1451,1471 ---- self.assertEqual(t.second, 0) self.assertEqual(t.microsecond, 0) ! self.failUnless(t.tzinfo is None) + def test_bad_tzinfo_classes(self): + tz = self.theclass + self.assertRaises(TypeError, tz, tzinfo=12) + + class NiceTry(object): + def __init__(self): pass + def utcoffset(self, dt): pass + self.assertRaises(TypeError, tz, tzinfo=NiceTry) + + class BetterTry(tzinfo): + def __init__(self): pass + def utcoffset(self, dt): pass + b = BetterTry() + t = tz(tzinfo=b) + self.failUnless(t.tzinfo is b) def test_suite(): From tim_one@users.sourceforge.net Wed Dec 11 22:17:01 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 11 Dec 2002 14:17:01 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_timetz.c,1.7,1.8 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv20541 Modified Files: obj_timetz.c Log Message: Gave timetz a proper tp_dealloc function. test_both no longer leaks. Index: obj_timetz.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_timetz.c,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** obj_timetz.c 11 Dec 2002 21:34:48 -0000 1.7 --- obj_timetz.c 11 Dec 2002 22:16:59 -0000 1.8 *************** *** 52,55 **** --- 52,64 ---- } + /* Destructor. */ + + static void + timetz_dealloc(PyDateTime_TimeTZ *self) + { + Py_XDECREF(self->tzinfo); + self->ob_type->tp_free((PyObject *)self); + } + /* Various ways to turn a time into a string. */ *************** *** 281,285 **** sizeof(PyDateTime_TimeTZ), /* tp_basicsize */ 0, /* tp_itemsize */ ! (destructor)PyObject_Del, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ --- 290,294 ---- sizeof(PyDateTime_TimeTZ), /* tp_basicsize */ 0, /* tp_itemsize */ ! (destructor)timetz_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ From tim_one@users.sourceforge.net Wed Dec 11 22:18:11 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 11 Dec 2002 14:18:11 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_timetz.c,1.8,1.9 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv21149 Modified Files: obj_timetz.c Log Message: Repaired comment. Index: obj_timetz.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_timetz.c,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** obj_timetz.c 11 Dec 2002 22:16:59 -0000 1.8 --- obj_timetz.c 11 Dec 2002 22:18:09 -0000 1.9 *************** *** 61,65 **** } ! /* Various ways to turn a time into a string. */ static PyObject * --- 61,65 ---- } ! /* Various ways to turn a timetz into a string. */ static PyObject * From tim_one@users.sourceforge.net Wed Dec 11 22:20:21 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 11 Dec 2002 14:20:21 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_timetz.c,1.9,1.10 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv21892 Modified Files: obj_timetz.c Log Message: Repaired timetz.isoformat docstring (it's fancier than time.isoformat). Index: obj_timetz.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_timetz.c,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** obj_timetz.c 11 Dec 2002 22:18:09 -0000 1.9 --- obj_timetz.c 11 Dec 2002 22:20:17 -0000 1.10 *************** *** 253,257 **** static PyMethodDef timetz_methods[] = { {"isoformat", (PyCFunction)timetz_isoformat, METH_KEYWORDS, ! PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm].")}, {"strftime", (PyCFunction)timetz_strftime, METH_O, --- 253,258 ---- static PyMethodDef timetz_methods[] = { {"isoformat", (PyCFunction)timetz_isoformat, METH_KEYWORDS, ! PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]" ! "[+HH:MM].")}, {"strftime", (PyCFunction)timetz_strftime, METH_O, From tim_one@users.sourceforge.net Thu Dec 12 00:30:17 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 11 Dec 2002 16:30:17 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime doc.txt,1.45,1.46 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv30726 Modified Files: doc.txt Log Message: Added docs for the timetz object. I regret signing up for this <0.7 wink>. Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.45 retrieving revision 1.46 diff -C2 -d -r1.45 -r1.46 *** doc.txt 11 Dec 2002 20:57:58 -0000 1.45 --- doc.txt 12 Dec 2002 00:30:15 -0000 1.46 *************** *** 738,747 **** - class datetimetz - ================ - - class timetz ============ --- 738,838 ---- class timetz ============ + A time object represents a (local) time of day, independent of any + particular day, and subject to adjustment via a tzinfo object. + + Constructor: + + time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None) + + All arguments are optional. tzinfo may be None, or an instance of + a tzinfo subclass. The remaining arguments may be ints or longs, in + the following ranges: + + 0 <= hour < 24 + 0 <= minute < 60 + 0 <= second < 60 + 0 <= microsecond < 1000000 + + If an argument outside those ranges is given, ValueError is raised. + + Other constructors (class methods): + + None + + Class attributes: + + .min + The earliest representable time, timetz(0, 0, 0, 0). + + .max + The latest representable time, timetz(23, 59, 59, 999999). + + .resolution + The smallest possible difference between non-equal timetz + objects, timedelta(microseconds=1). + + Instance attributes (read-only): + + .hour in range(24) + .minute in range(60) + .second in range(60) + .microsecond in range(1000000) + .tzinfo the object passed as the tzinfo= argument to the + timetz constructor, or None if none was passed. + + Supported operations: + + - comparison of timetz to timetz, where timetz1 is considered + less than timetz2 when timetz1 precedes timetz2 in time, and + where the timetz objects are first adjusted by subtracting + their UTC offsets (obtained from self.tzinfo.utcoffset(self)). + + - hash, use as dict key + + - pickling + + - in Boolean contexts, a timetz object is considered to be true + if and only if it isn't equal to timetz(0) + + Instance methods: + + - isoformat() + Return a string representing the time in ISO 8601 format, + HH:MM:SS.mmmmmm + or, if self.microsecond is 0 + HH:MM:SS + If self.tzinfo.utcoffset(self) does not return None, a 6-character + string is appended, giving the UCT offset in (signed) hours and + minutes: + HH:MM:SS.mmmmmm+HH:MM + or, if self.microsecond is 0 + HH:MM:SS+HH:MM + + - __str__() + For a timetz t, str(t) is equivalent to t.isoformat(). + + - strftime(format) + Return a string representing the time, controlled by an explicit + format string. Format codes for any fields other than hour, minute, + second and time zone should not be used, since a timetz object has + meaningful values only for those fields. + Format code %Z: If self.tzinfo is None, or if + self.tzinfo.tzname(self) returns None, %Z is replaced by an empty + string. Else %Z is replaced by the returned value, which must be + a string. + Format code %z: This is an extension to the usual set of format + codes. If self.tzinfo is None, or if self.tzinfo.uctoffset(self) + returns None, %z is replaced by an empty string. Else the return + value is transformed into a 5-character string of the form +HHMM or + -HHMM, and replaces %z, where HH is a 2-digit string giving the + number of UTC offset hours, and MM is a 2-digit string giving the + number of UTC offset minutes. + XXX Sheesh. This needs an example. + + + class datetimetz + ================ From tim_one@users.sourceforge.net Thu Dec 12 01:11:11 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 11 Dec 2002 17:11:11 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.c,1.58,1.59 obj_timetz.c,1.10,1.11 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv11692 Modified Files: datetime.c obj_timetz.c Log Message: Whatever. It still compiles . Index: datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.c,v retrieving revision 1.58 retrieving revision 1.59 diff -C2 -d -r1.58 -r1.59 *** datetime.c 11 Dec 2002 21:47:38 -0000 1.58 --- datetime.c 12 Dec 2002 01:11:08 -0000 1.59 *************** *** 813,818 **** init_datetime(void) { ! PyObject *m; ! PyObject *d, *dt; /* Types that use __reduce__ for pickling need to set the following * magical attr in the type dict, with a true value. --- 813,820 ---- init_datetime(void) { ! PyObject *m; /* a module object */ ! PyObject *d; /* its dict */ ! PyObject *x; ! /* Types that use __reduce__ for pickling need to set the following * magical attr in the type dict, with a true value. *************** *** 842,913 **** return; ! dt = new_delta(0, 0, 1, 0); ! if (dt == NULL || PyDict_SetItemString(d, "resolution", dt) < 0) return; ! Py_DECREF(dt); ! dt = new_delta(-MAX_DELTA_DAYS, 0, 0, 0); ! if (dt == NULL || PyDict_SetItemString(d, "min", dt) < 0) return; ! Py_DECREF(dt); ! dt = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0); ! if (dt == NULL || PyDict_SetItemString(d, "max", dt) < 0) return; ! Py_DECREF(dt); /* date values */ d = PyDateTime_DateType.tp_dict; ! dt = new_date(1, 1, 1); ! if (dt == NULL || PyDict_SetItemString(d, "min", dt) < 0) return; ! Py_DECREF(dt); ! dt = new_date(MAXYEAR, 12, 31); ! if (dt == NULL || PyDict_SetItemString(d, "max", dt) < 0) return; ! Py_DECREF(dt); ! dt = new_delta(1, 0, 0, 0); ! if (dt == NULL || PyDict_SetItemString(d, "resolution", dt) < 0) return; ! Py_DECREF(dt); /* datetime values */ d = PyDateTime_DateTimeType.tp_dict; ! dt = new_datetime(1, 1, 1, 0, 0, 0, 0); ! if (dt == NULL || PyDict_SetItemString(d, "min", dt) < 0) return; ! Py_DECREF(dt); ! dt = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999); ! if (dt == NULL || PyDict_SetItemString(d, "max", dt) < 0) return; ! Py_DECREF(dt); ! dt = new_delta(0, 0, 1, 0); ! if (dt == NULL || PyDict_SetItemString(d, "resolution", dt) < 0) return; ! Py_DECREF(dt); /* time values */ d = PyDateTime_TimeType.tp_dict; ! dt = new_time(0, 0, 0, 0); ! if (dt == NULL || PyDict_SetItemString(d, "min", dt) < 0) return; ! Py_DECREF(dt); ! dt = new_time(23, 59, 59, 999999); ! if (dt == NULL || PyDict_SetItemString(d, "max", dt) < 0) return; ! Py_DECREF(dt); ! dt = new_delta(0, 0, 1, 0); ! if (dt == NULL || PyDict_SetItemString(d, "resolution", dt) < 0) return; ! Py_DECREF(dt); Py_DECREF(safepickle); --- 844,933 ---- return; ! x = new_delta(0, 0, 1, 0); ! if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) return; ! Py_DECREF(x); ! x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0); ! if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) return; ! Py_DECREF(x); ! x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0); ! if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) return; ! Py_DECREF(x); /* date values */ d = PyDateTime_DateType.tp_dict; ! x = new_date(1, 1, 1); ! if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) return; ! Py_DECREF(x); ! x = new_date(MAXYEAR, 12, 31); ! if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) return; ! Py_DECREF(x); ! x = new_delta(1, 0, 0, 0); ! if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) return; ! Py_DECREF(x); /* datetime values */ d = PyDateTime_DateTimeType.tp_dict; ! x = new_datetime(1, 1, 1, 0, 0, 0, 0); ! if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) return; ! Py_DECREF(x); ! x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999); ! if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) return; ! Py_DECREF(x); ! x = new_delta(0, 0, 1, 0); ! if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) return; ! Py_DECREF(x); /* time values */ d = PyDateTime_TimeType.tp_dict; ! x = new_time(0, 0, 0, 0); ! if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) return; ! Py_DECREF(x); ! x = new_time(23, 59, 59, 999999); ! if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) return; ! Py_DECREF(x); ! x = new_delta(0, 0, 1, 0); ! if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) return; ! Py_DECREF(x); ! ! /* timetz values */ ! d = PyDateTime_TimeTZType.tp_dict; ! ! x = new_timetz(0, 0, 0, 0, Py_None); ! if (x == NULL || PyDict_SetItemString(d, "min", x) < 0) ! return; ! Py_DECREF(x); ! ! x = new_timetz(23, 59, 59, 999999, Py_None); ! if (x == NULL || PyDict_SetItemString(d, "max", x) < 0) ! return; ! Py_DECREF(x); ! ! x = new_delta(0, 0, 1, 0); ! if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0) ! return; ! Py_DECREF(x); Py_DECREF(safepickle); Index: obj_timetz.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_timetz.c,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** obj_timetz.c 11 Dec 2002 22:20:17 -0000 1.10 --- obj_timetz.c 12 Dec 2002 01:11:09 -0000 1.11 *************** *** 117,120 **** --- 117,121 ---- } + /* XXX This one's going to be a PITA. */ static PyObject * timetz_strftime(PyDateTime_TimeTZ *self, PyObject *format) *************** *** 144,157 **** timetz_richcompare(PyDateTime_TimeTZ *self, PyObject *other, int op) { long diff; if (!PyType_IsSubtype(other->ob_type, &PyDateTime_TimeType)) { PyErr_Format(PyExc_TypeError, ! "can't compare time to %s instance", other->ob_type->tp_name); return NULL; } ! diff = memcmp(self->data, ((PyDateTime_TimeTZ *)other)->data, ! _PyDateTime_TIME_DATASIZE); return diff_to_bool(diff, op); } --- 145,219 ---- timetz_richcompare(PyDateTime_TimeTZ *self, PyObject *other, int op) { + PyObject *self_tzinfo; + PyObject *other_tzinfo; + long self_offset; + long other_offset; + int self_none; + int other_none; long diff; if (!PyType_IsSubtype(other->ob_type, &PyDateTime_TimeType)) { PyErr_Format(PyExc_TypeError, ! "can't compare 'timetz' to '%s'", other->ob_type->tp_name); return NULL; } ! ! self_tzinfo = self->tzinfo; ! other_tzinfo = PyType_IsSubtype(other->ob_type, ! &PyDateTime_TimeTZType) ? ! ((PyDateTime_TimeTZ *)other)->tzinfo : ! Py_None; ! ! if (self_tzinfo == other_tzinfo) ! return time_richcompare((PyDateTime_Time *)self, other, op); ! ! if (self_tzinfo == Py_None) { ! self_offset = 0; ! self_none = 1; ! } ! else { ! self_offset = get_utcoffset(self_tzinfo, ! (PyObject *)self, ! &self_none); ! if (self_offset == -1 && PyErr_Occurred()) ! return NULL; ! } ! ! if (other_tzinfo == Py_None) { ! other_offset = 0; ! other_none = 1; ! } ! else { ! other_offset = get_utcoffset(other_tzinfo, ! (PyObject *)other, ! &other_none); ! if (other_offset == -1 && PyErr_Occurred()) ! return NULL; ! } ! ! if (self_none ^ other_none) { ! PyErr_SetString(PyExc_TypeError, ! "can't compare naive and timezone-aware " ! "times"); ! return NULL; ! } ! ! if (self_offset == other_offset) ! return time_richcompare((PyDateTime_Time *)self, other, op); ! ! /* Convert everything except microseconds to seconds. These can't ! * overflow. ! */ ! self_offset = TIME_GET_HOUR(self) * 3600 + ! (TIME_GET_MINUTE(self) - self_offset) * 60 + ! TIME_GET_SECOND(self); ! other_offset = TIME_GET_HOUR(other) * 3600 + ! (TIME_GET_MINUTE(other) - other_offset) * 60 + ! TIME_GET_SECOND(other); ! diff = self_offset - other_offset; ! if (diff == 0) ! diff = TIME_GET_MICROSECOND(self) - ! TIME_GET_MICROSECOND(other); return diff_to_bool(diff, op); } From tim_one@users.sourceforge.net Thu Dec 12 01:13:38 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 11 Dec 2002 17:13:38 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_timetz.c,1.11,1.12 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv12030 Modified Files: obj_timetz.c Log Message: Format. Index: obj_timetz.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_timetz.c,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** obj_timetz.c 12 Dec 2002 01:11:09 -0000 1.11 --- obj_timetz.c 12 Dec 2002 01:13:36 -0000 1.12 *************** *** 210,215 **** TIME_GET_SECOND(self); other_offset = TIME_GET_HOUR(other) * 3600 + ! (TIME_GET_MINUTE(other) - other_offset) * 60 + ! TIME_GET_SECOND(other); diff = self_offset - other_offset; if (diff == 0) --- 210,215 ---- TIME_GET_SECOND(self); other_offset = TIME_GET_HOUR(other) * 3600 + ! (TIME_GET_MINUTE(other) - other_offset) * 60 + ! TIME_GET_SECOND(other); diff = self_offset - other_offset; if (diff == 0) From tim_one@users.sourceforge.net Thu Dec 12 01:30:50 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 11 Dec 2002 17:30:50 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_timetz.c,1.12,1.13 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv16595 Modified Files: obj_timetz.c Log Message: More. Index: obj_timetz.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_timetz.c,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** obj_timetz.c 12 Dec 2002 01:13:36 -0000 1.12 --- obj_timetz.c 12 Dec 2002 01:30:47 -0000 1.13 *************** *** 224,234 **** timetz_hash(PyDateTime_TimeTZ *self) { ! if (self->hashcode == -1) { ! PyObject *temp = timetz_getstate(self); ! if (temp != NULL) { ! self->hashcode = PyObject_Hash(temp); ! Py_DECREF(temp); ! } } return self->hashcode; } --- 224,254 ---- timetz_hash(PyDateTime_TimeTZ *self) { ! long offset; ! int none; ! ! if (self->hashcode != -1) ! goto Done; ! ! self->hashcode = time_hash((PyDateTime_Time *)self); ! if (self->tzinfo == Py_None || ! (self->hashcode == -1 && PyErr_Occurred())) ! goto Done; ! ! offset = get_utcoffset(self->tzinfo, (PyObject *)self, &none); ! if (offset == -1 && PyErr_Occurred()) { ! self->hashcode = -1; ! goto Done; } + if (none) /* utcoffset returned None */ + goto Done; + + /* It doesn't really matter what we do now. Scrambling the bits + * a little based on the offset is as good as anything. + */ + self->hashcode ^= offset * 1319; + if (self->hashcode == -1) + self->hashcode = -2; + + Done: return self->hashcode; } From tim_one@users.sourceforge.net Thu Dec 12 01:38:29 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 11 Dec 2002 17:38:29 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime test_both.py,1.60,1.61 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv18224 Modified Files: test_both.py Log Message: Enough of timetz is working now so that TestTimeTZ can inherit from TestTime and pass, with one glitch due to that neither the Python nor the C implementations know how to pickle a timetz. Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.60 retrieving revision 1.61 diff -C2 -d -r1.60 -r1.61 *** test_both.py 11 Dec 2002 22:09:56 -0000 1.60 --- test_both.py 12 Dec 2002 01:38:26 -0000 1.61 *************** *** 1417,1420 **** --- 1417,1427 ---- def test_pickling(self): + # XXX The C implementation of timetz passes this by accident right + # XXX now, and the Python implementation of timetz fails this by + # XXX accident. That's because neither of them yet know how to + # XXX pickle a timetz. + if self.theclass is timetz and not TESTING_C: + return + import pickle, cPickle args = 20, 59, 16, 64**2 *************** *** 1441,1445 **** ! class TestTimeTZ(unittest.TestCase): theclass = timetz --- 1448,1452 ---- ! class TestTimeTZ(TestTime): theclass = timetz From tim_one@users.sourceforge.net Thu Dec 12 01:57:02 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 11 Dec 2002 17:57:02 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_timetz.c,1.13,1.14 test_both.py,1.61,1.62 test_datetime.py,1.62,1.63 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv23865 Modified Files: obj_timetz.c test_both.py test_datetime.py Log Message: Moved more timetz tests into test_both. Since I went thru all the work of writing a timetz richcompare, may as well use it. Index: obj_timetz.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_timetz.c,v retrieving revision 1.13 retrieving revision 1.14 diff -C2 -d -r1.13 -r1.14 *** obj_timetz.c 12 Dec 2002 01:30:47 -0000 1.13 --- obj_timetz.c 12 Dec 2002 01:57:00 -0000 1.14 *************** *** 393,397 **** 0, /* tp_traverse */ 0, /* tp_clear */ ! (richcmpfunc)time_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ --- 393,397 ---- 0, /* tp_traverse */ 0, /* tp_clear */ ! (richcmpfunc)timetz_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.61 retrieving revision 1.62 diff -C2 -d -r1.61 -r1.62 *** test_both.py 12 Dec 2002 01:38:26 -0000 1.61 --- test_both.py 12 Dec 2002 01:57:00 -0000 1.62 *************** *** 1476,1479 **** --- 1476,1520 ---- self.failUnless(t.tzinfo is b) + def test_zones(self): + est = FixedOffset(-300, "EST") + utc = FixedOffset(0, "UTC") + met = FixedOffset(60, "MET") + t1 = timetz( 7, 47, tzinfo=est) + t2 = timetz(12, 47, tzinfo=utc) + t3 = timetz(13, 47, tzinfo=met) + self.assertEqual(t1.tzinfo, est) + self.assertEqual(t2.tzinfo, utc) + self.assertEqual(t3.tzinfo, met) + # XXX The commented-out tests are still in test_datetime.py. + # self.assertEqual(t1.utcoffset(), -300) + # self.assertEqual(t2.utcoffset(), 0) + # self.assertEqual(t3.utcoffset(), 60) + # self.assertEqual(t1.tzname(), "EST") + # self.assertEqual(t2.tzname(), "UTC") + # self.assertEqual(t3.tzname(), "MET") + # self.assertEqual(hash(t1), hash(t2)) + # self.assertEqual(hash(t1), hash(t3)) + # self.assertEqual(hash(t2), hash(t3)) + self.assertEqual(t1, t2) + self.assertEqual(t1, t3) + self.assertEqual(t2, t3) + self.assertEqual(str(t1), "07:47:00-05:00") + self.assertEqual(str(t2), "12:47:00+00:00") + self.assertEqual(str(t3), "13:47:00+01:00") + if TESTING_C: + d = '_datetime.' + else: + d = '' + self.assertEqual(repr(t1), d + "timetz(7, 47, tzinfo=est)") + self.assertEqual(repr(t2), d + "timetz(12, 47, tzinfo=utc)") + self.assertEqual(repr(t3), d + "timetz(13, 47, tzinfo=met)") + self.assertEqual(t1.isoformat(), "07:47:00-05:00") + self.assertEqual(t2.isoformat(), "12:47:00+00:00") + self.assertEqual(t3.isoformat(), "13:47:00+01:00") + # self.assertEqual(t1.strftime("%H:%M:%S %Z %z"), "07:47:00 EST -0500") + # self.assertEqual(t2.strftime("%H:%M:%S %Z %z"), "12:47:00 UTC +0000") + # self.assertEqual(t3.strftime("%H:%M:%S %Z %z"), "13:47:00 MET +0100") + + def test_suite(): allsuites = [unittest.makeSuite(klass, 'test') Index: test_datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_datetime.py,v retrieving revision 1.62 retrieving revision 1.63 diff -C2 -d -r1.62 -r1.63 *** test_datetime.py 11 Dec 2002 01:47:20 -0000 1.62 --- test_datetime.py 12 Dec 2002 01:57:00 -0000 1.63 *************** *** 41,47 **** t2 = timetz(12, 47, tzinfo=utc) t3 = timetz(13, 47, tzinfo=met) ! self.assertEqual(t1.tzinfo, est) ! self.assertEqual(t2.tzinfo, utc) ! self.assertEqual(t3.tzinfo, met) self.assertEqual(t1.utcoffset(), -300) self.assertEqual(t2.utcoffset(), 0) --- 41,45 ---- t2 = timetz(12, 47, tzinfo=utc) t3 = timetz(13, 47, tzinfo=met) ! # XXX Most of the tests here have moved into test_both.py. self.assertEqual(t1.utcoffset(), -300) self.assertEqual(t2.utcoffset(), 0) *************** *** 53,68 **** self.assertEqual(hash(t1), hash(t3)) self.assertEqual(hash(t2), hash(t3)) - self.assertEqual(t1, t2) - self.assertEqual(t1, t3) - self.assertEqual(t2, t3) - self.assertEqual(str(t1), "07:47:00-05:00") - self.assertEqual(str(t2), "12:47:00+00:00") - self.assertEqual(str(t3), "13:47:00+01:00") - self.assertEqual(repr(t1), "timetz(7, 47, tzinfo=est)") - self.assertEqual(repr(t2), "timetz(12, 47, tzinfo=utc)") - self.assertEqual(repr(t3), "timetz(13, 47, tzinfo=met)") - self.assertEqual(t1.isoformat(), "07:47:00-05:00") - self.assertEqual(t2.isoformat(), "12:47:00+00:00") - self.assertEqual(t3.isoformat(), "13:47:00+01:00") self.assertEqual(t1.strftime("%H:%M:%S %Z %z"), "07:47:00 EST -0500") self.assertEqual(t2.strftime("%H:%M:%S %Z %z"), "12:47:00 UTC +0000") --- 51,54 ---- From tim_one@users.sourceforge.net Thu Dec 12 02:19:46 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 11 Dec 2002 18:19:46 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime obj_timetz.c,1.14,1.15 test_both.py,1.62,1.63 test_datetime.py,1.63,1.64 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv30008 Modified Files: obj_timetz.c test_both.py test_datetime.py Log Message: Repaired timetz_hash(). Index: obj_timetz.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_timetz.c,v retrieving revision 1.14 retrieving revision 1.15 diff -C2 -d -r1.14 -r1.15 *** obj_timetz.c 12 Dec 2002 01:57:00 -0000 1.14 --- obj_timetz.c 12 Dec 2002 02:19:43 -0000 1.15 *************** *** 226,229 **** --- 226,230 ---- long offset; int none; + long minutes; if (self->hashcode != -1) *************** *** 240,250 **** goto Done; } ! if (none) /* utcoffset returned None */ goto Done; ! /* It doesn't really matter what we do now. Scrambling the bits ! * a little based on the offset is as good as anything. */ ! self->hashcode ^= offset * 1319; if (self->hashcode == -1) self->hashcode = -2; --- 241,259 ---- goto Done; } ! if (none) goto Done; ! /* It doesn't really matter what we do now, except that we have to ! * ensure that timetz objects that compare equal have equal hashcodes. ! * So something based on subtracting offset minutes is needed. ! * CAUTION: it's not OK to return right away if offset==0: we ! * need to go thru the whole business below so that, e.g., a timetz ! * with hour=5 and offset=-60 gets the same hash code as a timetz ! * with hour=6 and offset=0. */ ! minutes = TIME_GET_HOUR(self) * 60L + TIME_GET_MINUTE(self) - offset; ! self->hashcode = minutes * 3601L + /* the multiplier is arbitrary */ ! TIME_GET_SECOND(self) * 61L + ! TIME_GET_MICROSECOND(self); if (self->hashcode == -1) self->hashcode = -2; Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.62 retrieving revision 1.63 diff -C2 -d -r1.62 -r1.63 *** test_both.py 12 Dec 2002 01:57:00 -0000 1.62 --- test_both.py 12 Dec 2002 02:19:43 -0000 1.63 *************** *** 1493,1499 **** # self.assertEqual(t2.tzname(), "UTC") # self.assertEqual(t3.tzname(), "MET") ! # self.assertEqual(hash(t1), hash(t2)) ! # self.assertEqual(hash(t1), hash(t3)) ! # self.assertEqual(hash(t2), hash(t3)) self.assertEqual(t1, t2) self.assertEqual(t1, t3) --- 1493,1499 ---- # self.assertEqual(t2.tzname(), "UTC") # self.assertEqual(t3.tzname(), "MET") ! self.assertEqual(hash(t1), hash(t2)) ! self.assertEqual(hash(t1), hash(t3)) ! self.assertEqual(hash(t2), hash(t3)) self.assertEqual(t1, t2) self.assertEqual(t1, t3) Index: test_datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_datetime.py,v retrieving revision 1.63 retrieving revision 1.64 diff -C2 -d -r1.63 -r1.64 *** test_datetime.py 12 Dec 2002 01:57:00 -0000 1.63 --- test_datetime.py 12 Dec 2002 02:19:43 -0000 1.64 *************** *** 48,54 **** self.assertEqual(t2.tzname(), "UTC") self.assertEqual(t3.tzname(), "MET") - self.assertEqual(hash(t1), hash(t2)) - self.assertEqual(hash(t1), hash(t3)) - self.assertEqual(hash(t2), hash(t3)) self.assertEqual(t1.strftime("%H:%M:%S %Z %z"), "07:47:00 EST -0500") self.assertEqual(t2.strftime("%H:%M:%S %Z %z"), "12:47:00 UTC +0000") --- 48,51 ---- From tim_one@users.sourceforge.net Thu Dec 12 02:55:19 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 11 Dec 2002 18:55:19 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime doc.txt,1.46,1.47 obj_timetz.c,1.15,1.16 test_both.py,1.63,1.64 test_datetime.py,1.64,1.65 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv6799 Modified Files: doc.txt obj_timetz.c test_both.py test_datetime.py Log Message: Implemented the timetz tzinfo convenience functions, and beefed up their tests. Index: doc.txt =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/doc.txt,v retrieving revision 1.46 retrieving revision 1.47 diff -C2 -d -r1.46 -r1.47 *** doc.txt 12 Dec 2002 00:30:15 -0000 1.46 --- doc.txt 12 Dec 2002 02:55:16 -0000 1.47 *************** *** 832,835 **** --- 832,844 ---- XXX Sheesh. This needs an example. + - utcoffset() + If self.tzinfo is None, returns None, else self.tzinfo.utcoffset(self). + + - tzname(): + If self.tzinfo is None, returns None, else self.tzinfo.tzname(self). + + - dst() + If self.tzinfo is None, returns None, else self.tzinfo.dst(self). + class datetimetz Index: obj_timetz.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/obj_timetz.c,v retrieving revision 1.15 retrieving revision 1.16 diff -C2 -d -r1.15 -r1.16 *** obj_timetz.c 12 Dec 2002 02:19:43 -0000 1.15 --- obj_timetz.c 12 Dec 2002 02:55:16 -0000 1.16 *************** *** 61,64 **** --- 61,97 ---- } + /* Indirect access to tzinfo methods. One more "convenience function" and + * it won't be possible to find the useful methods anymore <0.5 wink>. + */ + static PyObject * + timetz_convienience(PyDateTime_TimeTZ *self, char *name) + { + PyObject *result; + + if (self->tzinfo == Py_None) { + result = Py_None; + Py_INCREF(result); + } + else + result = PyObject_CallMethod(self->tzinfo, name, "O", self); + return result; + } + + /* These are all METH_NOARGS, so don't need to check the arglist. */ + static PyObject * + timetz_utcoffset(PyDateTime_TimeTZ *self, PyObject *unused) { + return timetz_convienience(self, "utcoffset"); + } + + static PyObject * + timetz_tzname(PyDateTime_TimeTZ *self, PyObject *unused) { + return timetz_convienience(self, "tzname"); + } + + static PyObject * + timetz_dst(PyDateTime_TimeTZ *self, PyObject *unused) { + return timetz_convienience(self, "dst"); + } + /* Various ways to turn a timetz into a string. */ *************** *** 350,353 **** --- 383,395 ---- PyDoc_STR("format -> strftime() style string.")}, + {"utcoffset", (PyCFunction)timetz_utcoffset, METH_NOARGS, + PyDoc_STR("Return self.tzinfo.utcoffset(self).")}, + + {"tzname", (PyCFunction)timetz_tzname, METH_NOARGS, + PyDoc_STR("Return self.tzinfo.tzname(self).")}, + + {"dst", (PyCFunction)timetz_dst, METH_NOARGS, + PyDoc_STR("Return self.tzinfo.dst(self).")}, + {"__setstate__", (PyCFunction)timetz_setstate, METH_O, PyDoc_STR("__setstate__(state)")}, *************** *** 356,359 **** --- 398,402 ---- PyDoc_STR("__getstate__() -> state")}, {NULL, NULL} + }; Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.63 retrieving revision 1.64 diff -C2 -d -r1.63 -r1.64 *** test_both.py 12 Dec 2002 02:19:43 -0000 1.63 --- test_both.py 12 Dec 2002 02:55:16 -0000 1.64 *************** *** 64,70 **** class FixedOffset(tzinfo): ! def __init__(self, offset, name): self.__offset = offset self.__name = name def __repr__(self): return self.__name.lower() --- 64,71 ---- class FixedOffset(tzinfo): ! def __init__(self, offset, name, dstoffset=42): self.__offset = offset self.__name = name + self.__dstoffset = dstoffset def __repr__(self): return self.__name.lower() *************** *** 74,78 **** return self.__name def dst(self, dt): ! return 0 class TestTZInfo(unittest.TestCase): --- 75,79 ---- return self.__name def dst(self, dt): ! return self.__dstoffset class TestTZInfo(unittest.TestCase): *************** *** 97,101 **** self.assertEqual(fo.utcoffset(dt), 3) self.assertEqual(fo.tzname(dt), "Three") ! self.assertEqual(fo.dst(dt), 0) ############################################################################# --- 98,102 ---- self.assertEqual(fo.utcoffset(dt), 3) self.assertEqual(fo.tzname(dt), "Three") ! self.assertEqual(fo.dst(dt), 42) ############################################################################# *************** *** 1477,1505 **** def test_zones(self): ! est = FixedOffset(-300, "EST") ! utc = FixedOffset(0, "UTC") ! met = FixedOffset(60, "MET") t1 = timetz( 7, 47, tzinfo=est) t2 = timetz(12, 47, tzinfo=utc) t3 = timetz(13, 47, tzinfo=met) self.assertEqual(t1.tzinfo, est) self.assertEqual(t2.tzinfo, utc) self.assertEqual(t3.tzinfo, met) ! # XXX The commented-out tests are still in test_datetime.py. ! # self.assertEqual(t1.utcoffset(), -300) ! # self.assertEqual(t2.utcoffset(), 0) ! # self.assertEqual(t3.utcoffset(), 60) ! # self.assertEqual(t1.tzname(), "EST") ! # self.assertEqual(t2.tzname(), "UTC") ! # self.assertEqual(t3.tzname(), "MET") self.assertEqual(hash(t1), hash(t2)) self.assertEqual(hash(t1), hash(t3)) self.assertEqual(hash(t2), hash(t3)) self.assertEqual(t1, t2) self.assertEqual(t1, t3) self.assertEqual(t2, t3) self.assertEqual(str(t1), "07:47:00-05:00") self.assertEqual(str(t2), "12:47:00+00:00") self.assertEqual(str(t3), "13:47:00+01:00") if TESTING_C: d = '_datetime.' --- 1478,1534 ---- def test_zones(self): ! est = FixedOffset(-300, "EST", 1) ! utc = FixedOffset(0, "UTC", -2) ! met = FixedOffset(60, "MET", 3) t1 = timetz( 7, 47, tzinfo=est) t2 = timetz(12, 47, tzinfo=utc) t3 = timetz(13, 47, tzinfo=met) + t4 = timetz(microsecond=40) + t5 = timetz(microsecond=40, tzinfo=utc) + self.assertEqual(t1.tzinfo, est) self.assertEqual(t2.tzinfo, utc) self.assertEqual(t3.tzinfo, met) ! self.failUnless(t4.tzinfo is None) ! self.assertEqual(t5.tzinfo, utc) ! ! self.assertEqual(t1.utcoffset(), -300) ! self.assertEqual(t2.utcoffset(), 0) ! self.assertEqual(t3.utcoffset(), 60) ! self.failUnless(t4.utcoffset() is None) ! self.assertRaises(TypeError, t1.utcoffset, "no args") ! ! self.assertEqual(t1.tzname(), "EST") ! self.assertEqual(t2.tzname(), "UTC") ! self.assertEqual(t3.tzname(), "MET") ! self.failUnless(t4.tzname() is None) ! self.assertRaises(TypeError, t1.tzname, "no args") ! ! self.assertEqual(t1.dst(), 1) ! self.assertEqual(t2.dst(), -2) ! self.assertEqual(t3.dst(), 3) ! self.failUnless(t4.dst() is None) ! self.assertRaises(TypeError, t1.dst, "no args") ! self.assertEqual(hash(t1), hash(t2)) self.assertEqual(hash(t1), hash(t3)) self.assertEqual(hash(t2), hash(t3)) + self.assertEqual(t1, t2) self.assertEqual(t1, t3) self.assertEqual(t2, t3) + self.assertEqual(str(t1), "07:47:00-05:00") self.assertEqual(str(t2), "12:47:00+00:00") self.assertEqual(str(t3), "13:47:00+01:00") + self.assertEqual(str(t4), "00:00:00.000040") + self.assertEqual(str(t5), "00:00:00.000040+00:00") + + self.assertEqual(t1.isoformat(), "07:47:00-05:00") + self.assertEqual(t2.isoformat(), "12:47:00+00:00") + self.assertEqual(t3.isoformat(), "13:47:00+01:00") + self.assertEqual(t4.isoformat(), "00:00:00.000040") + self.assertEqual(t5.isoformat(), "00:00:00.000040+00:00") + if TESTING_C: d = '_datetime.' *************** *** 1509,1515 **** self.assertEqual(repr(t2), d + "timetz(12, 47, tzinfo=utc)") self.assertEqual(repr(t3), d + "timetz(13, 47, tzinfo=met)") ! self.assertEqual(t1.isoformat(), "07:47:00-05:00") ! self.assertEqual(t2.isoformat(), "12:47:00+00:00") ! self.assertEqual(t3.isoformat(), "13:47:00+01:00") # self.assertEqual(t1.strftime("%H:%M:%S %Z %z"), "07:47:00 EST -0500") # self.assertEqual(t2.strftime("%H:%M:%S %Z %z"), "12:47:00 UTC +0000") --- 1538,1545 ---- self.assertEqual(repr(t2), d + "timetz(12, 47, tzinfo=utc)") self.assertEqual(repr(t3), d + "timetz(13, 47, tzinfo=met)") ! self.assertEqual(repr(t4), d + "timetz(0, 0, 0, 40)") ! self.assertEqual(repr(t5), d + "timetz(0, 0, 0, 40, tzinfo=utc)") ! ! # XXX The commented-out tests are still in test_datetime.py. # self.assertEqual(t1.strftime("%H:%M:%S %Z %z"), "07:47:00 EST -0500") # self.assertEqual(t2.strftime("%H:%M:%S %Z %z"), "12:47:00 UTC +0000") Index: test_datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_datetime.py,v retrieving revision 1.64 retrieving revision 1.65 diff -C2 -d -r1.64 -r1.65 *** test_datetime.py 12 Dec 2002 02:19:43 -0000 1.64 --- test_datetime.py 12 Dec 2002 02:55:16 -0000 1.65 *************** *** 27,31 **** return self.__name def dst(self, dt): ! return 0 --- 27,31 ---- return self.__name def dst(self, dt): ! return 42 *************** *** 42,51 **** t3 = timetz(13, 47, tzinfo=met) # XXX Most of the tests here have moved into test_both.py. - self.assertEqual(t1.utcoffset(), -300) - self.assertEqual(t2.utcoffset(), 0) - self.assertEqual(t3.utcoffset(), 60) - self.assertEqual(t1.tzname(), "EST") - self.assertEqual(t2.tzname(), "UTC") - self.assertEqual(t3.tzname(), "MET") self.assertEqual(t1.strftime("%H:%M:%S %Z %z"), "07:47:00 EST -0500") self.assertEqual(t2.strftime("%H:%M:%S %Z %z"), "12:47:00 UTC +0000") --- 42,45 ---- From tim_one@users.sourceforge.net Thu Dec 12 02:58:45 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 11 Dec 2002 18:58:45 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.py,1.93,1.94 test_both.py,1.64,1.65 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv8047 Modified Files: datetime.py test_both.py Log Message: Beefed up the timetz tests a little more. Index: datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.py,v retrieving revision 1.93 retrieving revision 1.94 diff -C2 -d -r1.93 -r1.94 *** datetime.py 11 Dec 2002 21:47:38 -0000 1.93 --- datetime.py 12 Dec 2002 02:58:42 -0000 1.94 *************** *** 934,938 **** return supercmp(other) if myoff is None or otoff is None: ! raise ValueError, "cannot mix naive and timezone-aware time" myhhmm = self.hour * 60 + self.minute - myoff othhmm = other.hour * 60 + other.minute - otoff --- 934,938 ---- return supercmp(other) if myoff is None or otoff is None: ! raise TypeError, "cannot mix naive and timezone-aware time" myhhmm = self.hour * 60 + self.minute - myoff othhmm = other.hour * 60 + other.minute - otoff Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.64 retrieving revision 1.65 diff -C2 -d -r1.64 -r1.65 *** test_both.py 12 Dec 2002 02:55:16 -0000 1.64 --- test_both.py 12 Dec 2002 02:58:43 -0000 1.65 *************** *** 1518,1521 **** --- 1518,1524 ---- self.assertEqual(t1, t3) self.assertEqual(t2, t3) + self.assertRaises(TypeError, lambda: t4 == t5) # mixed tz-aware & naive + self.assertRaises(TypeError, lambda: t4 < t5) # mixed tz-aware & naive + self.assertRaises(TypeError, lambda: t5 < t4) # mixed tz-aware & naive self.assertEqual(str(t1), "07:47:00-05:00") From tim_one@users.sourceforge.net Thu Dec 12 03:15:05 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 11 Dec 2002 19:15:05 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.c,1.59,1.60 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv12542 Modified Files: datetime.c Log Message: format_utcoffset(): If utcoffset() returns None, store a \0 byte into the buffer. The callers really have no way to know (or any reason to care) whether this actually wrote a utcoffset into the buffer. Index: datetime.c =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.c,v retrieving revision 1.59 retrieving revision 1.60 diff -C2 -d -r1.59 -r1.60 *** datetime.c 12 Dec 2002 01:11:08 -0000 1.59 --- datetime.c 12 Dec 2002 03:15:02 -0000 1.60 *************** *** 749,756 **** /* Add an hours & minutes UTC offset string to buf. buf has no more than * buflen bytes remaining. The UTC offset is gotten by calling ! * tzinfo.uctoffset(tzinfoarg). If that returns None, nothing is done. ! * Else the returned value is checked for sanity (an integer in range), ! * and if that's OK it's converted to an hours & minutes string of the ! * form * sign HH sep MM * Returns 0 if everything is OK. If the return value from utcoffset() is --- 749,756 ---- /* Add an hours & minutes UTC offset string to buf. buf has no more than * buflen bytes remaining. The UTC offset is gotten by calling ! * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into ! * *buf, and that's all. Else the returned value is checked for sanity (an ! * integer in range), and if that's OK it's converted to an hours & minutes ! * string of the form * sign HH sep MM * Returns 0 if everything is OK. If the return value from utcoffset() is *************** *** 770,775 **** if (offset == -1 && PyErr_Occurred()) return -1; ! if (none) return 0; sign = '+'; if (offset < 0) { --- 770,777 ---- if (offset == -1 && PyErr_Occurred()) return -1; ! if (none) { ! *buf = '\0'; return 0; + } sign = '+'; if (offset < 0) { From tim_one@users.sourceforge.net Thu Dec 12 03:24:57 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 11 Dec 2002 19:24:57 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.py,1.94,1.95 test_both.py,1.65,1.66 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv15091 Modified Files: datetime.py test_both.py Log Message: Test that a utcoffset out of bounds is caught when it gets formatted. Change the Python implementation to catch it (the C implementation already did). Index: datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.py,v retrieving revision 1.94 retrieving revision 1.95 diff -C2 -d -r1.94 -r1.95 *** datetime.py 12 Dec 2002 02:58:42 -0000 1.94 --- datetime.py 12 Dec 2002 03:24:55 -0000 1.95 *************** *** 970,973 **** --- 970,975 ---- sign = "+" hh, mm = divmod(off, 60) + if hh >= 24: + raise ValueError("utcoffset must be in -1439 .. 1439") return "%s%02d%s%02d" % (sign, hh, sep, mm) Index: test_both.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_both.py,v retrieving revision 1.65 retrieving revision 1.66 diff -C2 -d -r1.65 -r1.66 *** test_both.py 12 Dec 2002 02:58:43 -0000 1.65 --- test_both.py 12 Dec 2002 03:24:55 -0000 1.66 *************** *** 1549,1552 **** --- 1549,1571 ---- # self.assertEqual(t3.strftime("%H:%M:%S %Z %z"), "13:47:00 MET +0100") + def test_utc_offset_out_of_bounds(self): + class Edgy(tzinfo): + def __init__(self, offset): + self.offset = offset + def utcoffset(self, dt): + return self.offset + + for offset, legit in ((-1440, False), + (-1439, True), + (1439, True), + (1440, False)): + t = timetz(1, 2, 3, tzinfo=Edgy(offset)) + if legit: + aofs = abs(offset) + h, m = divmod(aofs, 60) + tag = "%c%02d:%02d" % (offset < 0 and '-' or '+', h, m) + self.assertEqual(str(t), "01:02:03" + tag) + else: + self.assertRaises(ValueError, str, t) def test_suite(): From tim_one@users.sourceforge.net Thu Dec 12 04:03:49 2002 From: tim_one@users.sourceforge.net (tim_one@users.sourceforge.net) Date: Wed, 11 Dec 2002 20:03:49 -0800 Subject: [Python-checkins] python/nondist/sandbox/datetime datetime.py,1.95,1.96 test_datetime.py,1.65,1.66 Message-ID: Update of /cvsroot/python/python/nondist/sandbox/datetime In directory sc8-pr-cvs1:/tmp/cvs-serv23554 Modified Files: datetime.py test_datetime.py Log Message: Implement tzinfo.strftime() correctly. This includes: - Don't call utcoffset or tzname unless they're actually needed by the format string. - Handle % escapes in the format string correctly. For example, %%Z is the string %Z, not a % followed by a reference to the format code %Z. - If %Z is used and the tzname has any % characters, escape them. All this was a minor PITA in Python, and will be a major PITA when rewritten in C. Index: datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/datetime.py,v retrieving revision 1.95 retrieving revision 1.96 diff -C2 -d -r1.95 -r1.96 *** datetime.py 12 Dec 2002 03:24:55 -0000 1.95 --- datetime.py 12 Dec 2002 04:03:47 -0000 1.96 *************** *** 161,164 **** --- 161,193 ---- return result + # Correctly substitute for %z and %Z escapes in strftime formats. + def _handle_z_escapes(format, Zreplace, zreplace): + result = [] + push = result.append + i, n = 0, len(format) + while i < n: + ch = format[i] + i += 1 + if ch == '%': + if i < n: + ch = format[i] + i += 1 + if ch == 'z': + s = zreplace() + assert '%' not in s + result.append(s) + elif ch == 'Z': + # strftime is going to have at this, so escape % + s = Zreplace().replace('%', '%%') + result.append(s) + else: + push('%') + push(ch) + else: + push('%') + else: + push(ch) + return "".join(result) + # This is a start at a struct tm workalike. Goals: # *************** *** 961,976 **** def _tzstr(self, sep=":"): """Return formatted timezone offset (+xx:xx) or None.""" ! if self.__tzinfo is not None: ! off = self.__tzinfo.utcoffset(self) ! if off is not None: ! if off < 0: ! sign = "-" ! off = -off ! else: ! sign = "+" ! hh, mm = divmod(off, 60) ! if hh >= 24: ! raise ValueError("utcoffset must be in -1439 .. 1439") ! return "%s%02d%s%02d" % (sign, hh, sep, mm) def __repr__(self): --- 990,1005 ---- def _tzstr(self, sep=":"): """Return formatted timezone offset (+xx:xx) or None.""" ! off = self.utcoffset() ! if off is not None: ! if off < 0: ! sign = "-" ! off = -off ! else: ! sign = "+" ! hh, mm = divmod(off, 60) ! if hh >= 24: ! raise ValueError("utcoffset must be in -1439 .. 1439") ! off = "%s%02d%s%02d" % (sign, hh, sep, mm) ! return off def __repr__(self): *************** *** 1002,1010 **** UTC offset (+zzzz). """ ! tz = self._tzstr(sep="") ! if tz: ! fmt = fmt.replace("%z", tz).replace("%Z", self.tzinfo.tzname(None)) ! else: ! fmt = fmt.replace("%z", "").replace("%Z", "") return super(timetz, self).strftime(fmt) --- 1031,1045 ---- UTC offset (+zzzz). """ ! ! # Don't call utcoffset or tzname unless the format string really ! # needs them -- there's no requirement in the docs that a tzinfo ! # object implement every method. ! def getz(): ! return self._tzstr('') or "" ! ! def getZ(): ! return self.tzname() or "" ! ! fmt = _handle_z_escapes(fmt, getZ, getz) return super(timetz, self).strftime(fmt) Index: test_datetime.py =================================================================== RCS file: /cvsroot/python/python/nondist/sandbox/datetime/test_datetime.py,v retrieving revision 1.65 retrieving revision 1.66 diff -C2 -d -r1.65 -r1.66 *** test_datetime.py 12 Dec 2002 02:55:16 -0000 1.65 --- test_datetime.py 12 Dec 2002 04:03:47 -0000 1.66 *************** *** 42,49 **** t3 = timetz(13, 47, tzinfo=met) # XXX Most of the tests here have moved into test_both.py. ! self.assertEqual(t1.strftime("%H:%M:%S %Z %z"), "07:47:00 EST -0500") self.assertEqual(t2.strftime("%H:%M:%S %Z %z"), "12:47:00 UTC +0000") self.assertEqual(t3.strftime("%H:%M:%S %Z %z"), "13:47:00 MET +0100") class TestDateTime(unittest.TestCase): --- 42,54 ---- t3 = timetz(13, 47, tzinfo=met) # XXX Most of the tests here have moved into test_both.py. ! self.assertEqual(t1.strftime("%H:%M:%S %%Z=%Z %%z=%z"), ! "07:47:00 %Z=EST %z=-0500") self.assertEqual(t2.strftime("%H:%M:%S %Z %z"), "12:47:00 UTC +0000") self.assertEqual(t3.strftime("%H:%M:%S %Z %z"), "13:47:00 MET +0100") + yuck = FixedOffset(-1439, "%z %Z %%z%%Z") + t1 = timetz(23, 59, tzinfo=yuck) + self.assertEqual(t1.strftime("%H:%M %%Z='%Z' %%z='%z'"), + "23:59 %Z='%z %Z %%z%%Z' %z='-2359'") class TestDateTime(unittest.TestCase): From jackjansen@users.sourceforge.net Thu Dec 12 10:31:55 2002 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Thu, 12 Dec 2002 02:31:55 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules/scrap _Scrapmodule.c,1.4,1.5 scrapscan.py,1.8,1.9 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules/scrap In directory sc8-pr-cvs1:/tmp/cvs-serv21368/Modules/scrap Modified Files: _Scrapmodule.c scrapscan.py Log Message: Getting rid of pre-Carbon (MacOS8) support. All code depending on TARGET_API_MAC_OS8 (or !TARGET_API_MAC_CARBON) is gone. Also some TARGET_API_MAC_OSX conditional code is gone, because it is no longer used on OSX-only Python (only in MacPython-OS9). Index: _Scrapmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/scrap/_Scrapmodule.c,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** _Scrapmodule.c 18 Nov 2002 15:26:42 -0000 1.4 --- _Scrapmodule.c 12 Dec 2002 10:31:52 -0000 1.5 *************** *** 30,52 **** #endif - #if TARGET_API_MAC_OS8 - - /* - ** Generate ScrapInfo records - */ - static PyObject * - SCRRec_New(itself) - ScrapStuff *itself; - { - - return Py_BuildValue("lO&hhO&", itself->scrapSize, - ResObj_New, itself->scrapHandle, itself->scrapCount, itself->scrapState, - PyMac_BuildStr255, itself->scrapName); - } - #endif - static PyObject *Scrap_Error; - #if !TARGET_API_MAC_OS8 /* ----------------------- Object type Scrap ------------------------ */ --- 30,35 ---- *************** *** 281,285 **** /* --------------------- End object type Scrap ---------------------- */ - #endif /* !TARGET_API_MAC_OS8 */ static PyObject *Scrap_LoadScrap(PyObject *_self, PyObject *_args) --- 264,267 ---- *************** *** 309,385 **** } - #if TARGET_API_MAC_OS8 - - static PyObject *Scrap_InfoScrap(PyObject *_self, PyObject *_args) - { - PyObject *_res = NULL; - ScrapStuffPtr _rv; - if (!PyArg_ParseTuple(_args, "")) - return NULL; - _rv = InfoScrap(); - _res = Py_BuildValue("O&", - SCRRec_New, _rv); - return _res; - } - - static PyObject *Scrap_GetScrap(PyObject *_self, PyObject *_args) - { - PyObject *_res = NULL; - long _rv; - Handle destination; - ScrapFlavorType flavorType; - SInt32 offset; - if (!PyArg_ParseTuple(_args, "O&O&", - ResObj_Convert, &destination, - PyMac_GetOSType, &flavorType)) - return NULL; - _rv = GetScrap(destination, - flavorType, - &offset); - _res = Py_BuildValue("ll", - _rv, - offset); - return _res; - } - - static PyObject *Scrap_ZeroScrap(PyObject *_self, PyObject *_args) - { - PyObject *_res = NULL; - OSStatus _err; - if (!PyArg_ParseTuple(_args, "")) - return NULL; - _err = ZeroScrap(); - if (_err != noErr) return PyMac_Error(_err); - Py_INCREF(Py_None); - _res = Py_None; - return _res; - } - - static PyObject *Scrap_PutScrap(PyObject *_self, PyObject *_args) - { - PyObject *_res = NULL; - OSStatus _err; - SInt32 sourceBufferByteCount; - ScrapFlavorType flavorType; - char *sourceBuffer__in__; - int sourceBuffer__len__; - int sourceBuffer__in_len__; - if (!PyArg_ParseTuple(_args, "lO&s#", - &sourceBufferByteCount, - PyMac_GetOSType, &flavorType, - &sourceBuffer__in__, &sourceBuffer__in_len__)) - return NULL; - _err = PutScrap(sourceBufferByteCount, - flavorType, - sourceBuffer__in__); - if (_err != noErr) return PyMac_Error(_err); - Py_INCREF(Py_None); - _res = Py_None; - sourceBuffer__error__: ; - return _res; - } - #endif /* TARGET_API_MAC_OS8 */ - - #if !TARGET_API_MAC_OS8 static PyObject *Scrap_GetCurrentScrap(PyObject *_self, PyObject *_args) { --- 291,294 ---- *************** *** 421,425 **** return _res; } - #endif static PyMethodDef Scrap_methods[] = { --- 330,333 ---- *************** *** 428,444 **** {"UnloadScrap", (PyCFunction)Scrap_UnloadScrap, 1, "() -> None"}, - - #if TARGET_API_MAC_OS8 - {"InfoScrap", (PyCFunction)Scrap_InfoScrap, 1, - "() -> (ScrapStuffPtr _rv)"}, - {"GetScrap", (PyCFunction)Scrap_GetScrap, 1, - "(Handle destination, ScrapFlavorType flavorType) -> (long _rv, SInt32 offset)"}, - {"ZeroScrap", (PyCFunction)Scrap_ZeroScrap, 1, - "() -> None"}, - {"PutScrap", (PyCFunction)Scrap_PutScrap, 1, - "(SInt32 sourceBufferByteCount, ScrapFlavorType flavorType, Buffer sourceBuffer) -> None"}, - #endif - - #if !TARGET_API_MAC_OS8 {"GetCurrentScrap", (PyCFunction)Scrap_GetCurrentScrap, 1, "() -> (ScrapRef scrap)"}, --- 336,339 ---- *************** *** 447,451 **** {"CallInScrapPromises", (PyCFunction)Scrap_CallInScrapPromises, 1, "() -> None"}, - #endif {NULL, NULL, 0} }; --- 342,345 ---- *************** *** 468,477 **** PyDict_SetItemString(d, "Error", Scrap_Error) != 0) return; - #if !TARGET_API_MAC_OS8 Scrap_Type.ob_type = &PyType_Type; Py_INCREF(&Scrap_Type); if (PyDict_SetItemString(d, "ScrapType", (PyObject *)&Scrap_Type) != 0) Py_FatalError("can't initialize ScrapType"); - #endif } --- 362,369 ---- Index: scrapscan.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/scrap/scrapscan.py,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** scrapscan.py 15 Aug 2002 22:05:58 -0000 1.8 --- scrapscan.py 12 Dec 2002 10:31:53 -0000 1.9 *************** *** 41,58 **** return [ "GetScrapFlavorInfoList", ] - - def makegreylist(self): - return [ - ('#if !TARGET_API_MAC_CARBON', [ - 'InfoScrap', - 'GetScrap', - 'ZeroScrap', - 'PutScrap', - ]), - ('#if TARGET_API_MAC_CARBON', [ - 'CallInScrapPromises', - 'ClearCurrentScrap', - ])] def makeblacklisttypes(self): --- 41,49 ---- return [ "GetScrapFlavorInfoList", + 'InfoScrap', + 'GetScrap', + 'ZeroScrap', + 'PutScrap', ] def makeblacklisttypes(self): From jackjansen@users.sourceforge.net Thu Dec 12 10:31:54 2002 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Thu, 12 Dec 2002 02:31:54 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules/qt _Qtmodule.c,1.11,1.12 qtscan.py,1.20,1.21 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules/qt In directory sc8-pr-cvs1:/tmp/cvs-serv21368/Modules/qt Modified Files: _Qtmodule.c qtscan.py Log Message: Getting rid of pre-Carbon (MacOS8) support. All code depending on TARGET_API_MAC_OS8 (or !TARGET_API_MAC_CARBON) is gone. Also some TARGET_API_MAC_OSX conditional code is gone, because it is no longer used on OSX-only Python (only in MacPython-OS9). Index: _Qtmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/qt/_Qtmodule.c,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** _Qtmodule.c 3 Dec 2002 23:40:21 -0000 1.11 --- _Qtmodule.c 12 Dec 2002 10:31:52 -0000 1.12 *************** *** 6277,6332 **** } - #if !TARGET_API_MAC_CARBON - - static PyObject *MovieObj_SetMovieAnchorDataRef(MovieObject *_self, PyObject *_args) - { - PyObject *_res = NULL; - OSErr _err; - Handle dataRef; - OSType dataRefType; - #ifndef SetMovieAnchorDataRef - PyMac_PRECHECK(SetMovieAnchorDataRef); - #endif - if (!PyArg_ParseTuple(_args, "O&O&", - ResObj_Convert, &dataRef, - PyMac_GetOSType, &dataRefType)) - return NULL; - _err = SetMovieAnchorDataRef(_self->ob_itself, - dataRef, - dataRefType); - if (_err != noErr) return PyMac_Error(_err); - Py_INCREF(Py_None); - _res = Py_None; - return _res; - } - #endif - - #if !TARGET_API_MAC_CARBON - - static PyObject *MovieObj_GetMovieAnchorDataRef(MovieObject *_self, PyObject *_args) - { - PyObject *_res = NULL; - OSErr _err; - Handle dataRef; - OSType dataRefType; - long outFlags; - #ifndef GetMovieAnchorDataRef - PyMac_PRECHECK(GetMovieAnchorDataRef); - #endif - if (!PyArg_ParseTuple(_args, "")) - return NULL; - _err = GetMovieAnchorDataRef(_self->ob_itself, - &dataRef, - &dataRefType, - &outFlags); - if (_err != noErr) return PyMac_Error(_err); - _res = Py_BuildValue("O&O&l", - ResObj_New, dataRef, - PyMac_BuildOSType, dataRefType, - outFlags); - return _res; - } - #endif - static PyObject *MovieObj_SetMovieColorTable(MovieObject *_self, PyObject *_args) { --- 6277,6280 ---- *************** *** 6535,6556 **** } - #if !TARGET_API_MAC_CARBON - - static PyObject *MovieObj_GetMovieLoadState(MovieObject *_self, PyObject *_args) - { - PyObject *_res = NULL; - long _rv; - #ifndef GetMovieLoadState - PyMac_PRECHECK(GetMovieLoadState); - #endif - if (!PyArg_ParseTuple(_args, "")) - return NULL; - _rv = GetMovieLoadState(_self->ob_itself); - _res = Py_BuildValue("l", - _rv); - return _res; - } - #endif - static PyObject *MovieObj_NewMovieController(MovieObject *_self, PyObject *_args) { --- 6483,6486 ---- *************** *** 6860,6873 **** {"GetMovieDefaultDataRef", (PyCFunction)MovieObj_GetMovieDefaultDataRef, 1, PyDoc_STR("() -> (Handle dataRef, OSType dataRefType)")}, - - #if !TARGET_API_MAC_CARBON - {"SetMovieAnchorDataRef", (PyCFunction)MovieObj_SetMovieAnchorDataRef, 1, - PyDoc_STR("(Handle dataRef, OSType dataRefType) -> None")}, - #endif - - #if !TARGET_API_MAC_CARBON - {"GetMovieAnchorDataRef", (PyCFunction)MovieObj_GetMovieAnchorDataRef, 1, - PyDoc_STR("() -> (Handle dataRef, OSType dataRefType, long outFlags)")}, - #endif {"SetMovieColorTable", (PyCFunction)MovieObj_SetMovieColorTable, 1, PyDoc_STR("(CTabHandle ctab) -> None")}, --- 6790,6793 ---- *************** *** 6888,6896 **** {"GetMovieStatus", (PyCFunction)MovieObj_GetMovieStatus, 1, PyDoc_STR("() -> (ComponentResult _rv, Track firstProblemTrack)")}, - - #if !TARGET_API_MAC_CARBON - {"GetMovieLoadState", (PyCFunction)MovieObj_GetMovieLoadState, 1, - PyDoc_STR("() -> (long _rv)")}, - #endif {"NewMovieController", (PyCFunction)MovieObj_NewMovieController, 1, PyDoc_STR("(Rect movieRect, long someFlags) -> (MovieController _rv)")}, --- 6808,6811 ---- *************** *** 6982,7007 **** - #if !TARGET_API_MAC_CARBON - - static PyObject *Qt_CheckQuickTimeRegistration(PyObject *_self, PyObject *_args) - { - PyObject *_res = NULL; - void * registrationKey; - long flags; - #ifndef CheckQuickTimeRegistration - PyMac_PRECHECK(CheckQuickTimeRegistration); - #endif - if (!PyArg_ParseTuple(_args, "sl", - ®istrationKey, - &flags)) - return NULL; - CheckQuickTimeRegistration(registrationKey, - flags); - Py_INCREF(Py_None); - _res = Py_None; - return _res; - } - #endif - static PyObject *Qt_EnterMovies(PyObject *_self, PyObject *_args) { --- 6897,6900 ---- *************** *** 7136,7177 **** } - #if !TARGET_API_MAC_CARBON - - static PyObject *Qt_OpenADataHandler(PyObject *_self, PyObject *_args) - { - PyObject *_res = NULL; - OSErr _err; - Handle dataRef; - OSType dataHandlerSubType; - Handle anchorDataRef; - OSType anchorDataRefType; - TimeBase tb; - long flags; - ComponentInstance dh; - #ifndef OpenADataHandler - PyMac_PRECHECK(OpenADataHandler); - #endif - if (!PyArg_ParseTuple(_args, "O&O&O&O&O&l", - ResObj_Convert, &dataRef, - PyMac_GetOSType, &dataHandlerSubType, - ResObj_Convert, &anchorDataRef, - PyMac_GetOSType, &anchorDataRefType, - TimeBaseObj_Convert, &tb, - &flags)) - return NULL; - _err = OpenADataHandler(dataRef, - dataHandlerSubType, - anchorDataRef, - anchorDataRefType, - tb, - flags, - &dh); - if (_err != noErr) return PyMac_Error(_err); - _res = Py_BuildValue("O&", - CmpInstObj_New, dh); - return _res; - } - #endif - static PyObject *Qt_PasteHandleIntoMovie(PyObject *_self, PyObject *_args) { --- 7029,7032 ---- *************** *** 8847,8879 **** } - #if !TARGET_API_MAC_CARBON - - static PyObject *Qt_SpriteMediaGetIndImageProperty(PyObject *_self, PyObject *_args) - { - PyObject *_res = NULL; - ComponentResult _rv; - MediaHandler mh; - short imageIndex; - long imagePropertyType; - void * imagePropertyValue; - #ifndef SpriteMediaGetIndImageProperty - PyMac_PRECHECK(SpriteMediaGetIndImageProperty); - #endif - if (!PyArg_ParseTuple(_args, "O&hls", - CmpInstObj_Convert, &mh, - &imageIndex, - &imagePropertyType, - &imagePropertyValue)) - return NULL; - _rv = SpriteMediaGetIndImageProperty(mh, - imageIndex, - imagePropertyType, - imagePropertyValue); - _res = Py_BuildValue("l", - _rv); - return _res; - } - #endif - static PyObject *Qt_SpriteMediaDisposeSprite(PyObject *_self, PyObject *_args) { --- 8702,8705 ---- *************** *** 9259,9407 **** } - #if !TARGET_API_MAC_CARBON - - static PyObject *Qt_MovieMediaGetCurrentMovieProperty(PyObject *_self, PyObject *_args) - { - PyObject *_res = NULL; - ComponentResult _rv; - MediaHandler mh; - OSType whichProperty; - void * value; - #ifndef MovieMediaGetCurrentMovieProperty - PyMac_PRECHECK(MovieMediaGetCurrentMovieProperty); - #endif - if (!PyArg_ParseTuple(_args, "O&O&s", - CmpInstObj_Convert, &mh, - PyMac_GetOSType, &whichProperty, - &value)) - return NULL; - _rv = MovieMediaGetCurrentMovieProperty(mh, - whichProperty, - value); - _res = Py_BuildValue("l", - _rv); - return _res; - } - #endif - - #if !TARGET_API_MAC_CARBON - - static PyObject *Qt_MovieMediaGetCurrentTrackProperty(PyObject *_self, PyObject *_args) - { - PyObject *_res = NULL; - ComponentResult _rv; - MediaHandler mh; - long trackID; - OSType whichProperty; - void * value; - #ifndef MovieMediaGetCurrentTrackProperty - PyMac_PRECHECK(MovieMediaGetCurrentTrackProperty); - #endif - if (!PyArg_ParseTuple(_args, "O&lO&s", - CmpInstObj_Convert, &mh, - &trackID, - PyMac_GetOSType, &whichProperty, - &value)) - return NULL; - _rv = MovieMediaGetCurrentTrackProperty(mh, - trackID, - whichProperty, - value); - _res = Py_BuildValue("l", - _rv); - return _res; - } - #endif - - #if !TARGET_API_MAC_CARBON - - static PyObject *Qt_MovieMediaGetChildMovieDataReference(PyObject *_self, PyObject *_args) - { - PyObject *_res = NULL; - ComponentResult _rv; - MediaHandler mh; - QTAtomID dataRefID; - short dataRefIndex; - OSType dataRefType; - Handle dataRef; - QTAtomID dataRefIDOut; - short dataRefIndexOut; - #ifndef MovieMediaGetChildMovieDataReference - PyMac_PRECHECK(MovieMediaGetChildMovieDataReference); - #endif - if (!PyArg_ParseTuple(_args, "O&lh", - CmpInstObj_Convert, &mh, - &dataRefID, - &dataRefIndex)) - return NULL; - _rv = MovieMediaGetChildMovieDataReference(mh, - dataRefID, - dataRefIndex, - &dataRefType, - &dataRef, - &dataRefIDOut, - &dataRefIndexOut); - _res = Py_BuildValue("lO&O&lh", - _rv, - PyMac_BuildOSType, dataRefType, - ResObj_New, dataRef, - dataRefIDOut, - dataRefIndexOut); - return _res; - } - #endif - - #if !TARGET_API_MAC_CARBON - - static PyObject *Qt_MovieMediaSetChildMovieDataReference(PyObject *_self, PyObject *_args) - { - PyObject *_res = NULL; - ComponentResult _rv; - MediaHandler mh; - QTAtomID dataRefID; - OSType dataRefType; - Handle dataRef; - #ifndef MovieMediaSetChildMovieDataReference - PyMac_PRECHECK(MovieMediaSetChildMovieDataReference); - #endif - if (!PyArg_ParseTuple(_args, "O&lO&O&", - CmpInstObj_Convert, &mh, - &dataRefID, - PyMac_GetOSType, &dataRefType, - ResObj_Convert, &dataRef)) - return NULL; - _rv = MovieMediaSetChildMovieDataReference(mh, - dataRefID, - dataRefType, - dataRef); - _res = Py_BuildValue("l", - _rv); - return _res; - } - #endif - - #if !TARGET_API_MAC_CARBON - - static PyObject *Qt_MovieMediaLoadChildMovieFromDataReference(PyObject *_self, PyObject *_args) - { - PyObject *_res = NULL; - ComponentResult _rv; - MediaHandler mh; - QTAtomID dataRefID; - #ifndef MovieMediaLoadChildMovieFromDataReference - PyMac_PRECHECK(MovieMediaLoadChildMovieFromDataReference); - #endif - if (!PyArg_ParseTuple(_args, "O&l", - CmpInstObj_Convert, &mh, - &dataRefID)) - return NULL; - _rv = MovieMediaLoadChildMovieFromDataReference(mh, - dataRefID); - _res = Py_BuildValue("l", - _rv); - return _res; - } - #endif - static PyObject *Qt_Media3DGetCurrentGroup(PyObject *_self, PyObject *_args) { --- 9085,9088 ---- *************** *** 9637,9663 **** } - #if !TARGET_API_MAC_CARBON - - static PyObject *Qt_Media3DGetViewObject(PyObject *_self, PyObject *_args) - { - PyObject *_res = NULL; - ComponentResult _rv; - MediaHandler mh; - void * tq3viewObject; - #ifndef Media3DGetViewObject - PyMac_PRECHECK(Media3DGetViewObject); - #endif - if (!PyArg_ParseTuple(_args, "O&s", - CmpInstObj_Convert, &mh, - &tq3viewObject)) - return NULL; - _rv = Media3DGetViewObject(mh, - tq3viewObject); - _res = Py_BuildValue("l", - _rv); - return _res; - } - #endif - static PyObject *Qt_NewTimeBase(PyObject *_self, PyObject *_args) { --- 9318,9321 ---- *************** *** 9835,9843 **** static PyMethodDef Qt_methods[] = { - - #if !TARGET_API_MAC_CARBON - {"CheckQuickTimeRegistration", (PyCFunction)Qt_CheckQuickTimeRegistration, 1, - PyDoc_STR("(void * registrationKey, long flags) -> None")}, - #endif {"EnterMovies", (PyCFunction)Qt_EnterMovies, 1, PyDoc_STR("() -> None")}, --- 9493,9496 ---- *************** *** 9856,9864 **** {"GetDataHandler", (PyCFunction)Qt_GetDataHandler, 1, PyDoc_STR("(Handle dataRef, OSType dataHandlerSubType, long flags) -> (Component _rv)")}, - - #if !TARGET_API_MAC_CARBON - {"OpenADataHandler", (PyCFunction)Qt_OpenADataHandler, 1, - PyDoc_STR("(Handle dataRef, OSType dataHandlerSubType, Handle anchorDataRef, OSType anchorDataRefType, TimeBase tb, long flags) -> (ComponentInstance dh)")}, - #endif {"PasteHandleIntoMovie", (PyCFunction)Qt_PasteHandleIntoMovie, 1, PyDoc_STR("(Handle h, OSType handleType, Movie theMovie, long flags, ComponentInstance userComp) -> None")}, --- 9509,9512 ---- *************** *** 9989,9997 **** {"SpriteMediaGetActionVariable", (PyCFunction)Qt_SpriteMediaGetActionVariable, 1, PyDoc_STR("(MediaHandler mh, QTAtomID variableID) -> (ComponentResult _rv, float value)")}, - - #if !TARGET_API_MAC_CARBON - {"SpriteMediaGetIndImageProperty", (PyCFunction)Qt_SpriteMediaGetIndImageProperty, 1, - PyDoc_STR("(MediaHandler mh, short imageIndex, long imagePropertyType, void * imagePropertyValue) -> (ComponentResult _rv)")}, - #endif {"SpriteMediaDisposeSprite", (PyCFunction)Qt_SpriteMediaDisposeSprite, 1, PyDoc_STR("(MediaHandler mh, QTAtomID spriteID) -> (ComponentResult _rv)")}, --- 9637,9640 ---- *************** *** 10026,10054 **** {"FlashMediaGetSupportedSwfVersion", (PyCFunction)Qt_FlashMediaGetSupportedSwfVersion, 1, PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, UInt8 swfVersion)")}, - - #if !TARGET_API_MAC_CARBON - {"MovieMediaGetCurrentMovieProperty", (PyCFunction)Qt_MovieMediaGetCurrentMovieProperty, 1, - PyDoc_STR("(MediaHandler mh, OSType whichProperty, void * value) -> (ComponentResult _rv)")}, - #endif - - #if !TARGET_API_MAC_CARBON - {"MovieMediaGetCurrentTrackProperty", (PyCFunction)Qt_MovieMediaGetCurrentTrackProperty, 1, - PyDoc_STR("(MediaHandler mh, long trackID, OSType whichProperty, void * value) -> (ComponentResult _rv)")}, - #endif - - #if !TARGET_API_MAC_CARBON - {"MovieMediaGetChildMovieDataReference", (PyCFunction)Qt_MovieMediaGetChildMovieDataReference, 1, - PyDoc_STR("(MediaHandler mh, QTAtomID dataRefID, short dataRefIndex) -> (ComponentResult _rv, OSType dataRefType, Handle dataRef, QTAtomID dataRefIDOut, short dataRefIndexOut)")}, - #endif - - #if !TARGET_API_MAC_CARBON - {"MovieMediaSetChildMovieDataReference", (PyCFunction)Qt_MovieMediaSetChildMovieDataReference, 1, - PyDoc_STR("(MediaHandler mh, QTAtomID dataRefID, OSType dataRefType, Handle dataRef) -> (ComponentResult _rv)")}, - #endif - - #if !TARGET_API_MAC_CARBON - {"MovieMediaLoadChildMovieFromDataReference", (PyCFunction)Qt_MovieMediaLoadChildMovieFromDataReference, 1, - PyDoc_STR("(MediaHandler mh, QTAtomID dataRefID) -> (ComponentResult _rv)")}, - #endif {"Media3DGetCurrentGroup", (PyCFunction)Qt_Media3DGetCurrentGroup, 1, PyDoc_STR("(MediaHandler mh, void * group) -> (ComponentResult _rv)")}, --- 9669,9672 ---- *************** *** 10071,10079 **** {"Media3DGetCameraRange", (PyCFunction)Qt_Media3DGetCameraRange, 1, PyDoc_STR("(MediaHandler mh, void * tQ3CameraRange) -> (ComponentResult _rv)")}, - - #if !TARGET_API_MAC_CARBON - {"Media3DGetViewObject", (PyCFunction)Qt_Media3DGetViewObject, 1, - PyDoc_STR("(MediaHandler mh, void * tq3viewObject) -> (ComponentResult _rv)")}, - #endif {"NewTimeBase", (PyCFunction)Qt_NewTimeBase, 1, PyDoc_STR("() -> (TimeBase _rv)")}, --- 9689,9692 ---- Index: qtscan.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/qt/qtscan.py,v retrieving revision 1.20 retrieving revision 1.21 diff -C2 -d -r1.20 -r1.21 *** qtscan.py 15 Aug 2002 21:48:15 -0000 1.20 --- qtscan.py 12 Dec 2002 10:31:52 -0000 1.21 *************** *** 63,84 **** "MakeMediaTimeTable", # ditto ## "VideoMediaGetStallCount", # Undefined in CW Pro 3 library ! ] ! def makegreylist(self): ! return [ ! ('#if !TARGET_API_MAC_CARBON', [ ! 'SpriteMediaGetIndImageProperty', # XXXX Why isn't this in carbon? ! 'CheckQuickTimeRegistration', ! 'SetMovieAnchorDataRef', ! 'GetMovieAnchorDataRef', ! 'GetMovieLoadState', ! 'OpenADataHandler', ! 'MovieMediaGetCurrentMovieProperty', ! 'MovieMediaGetCurrentTrackProperty', ! 'MovieMediaGetChildMovieDataReference', ! 'MovieMediaSetChildMovieDataReference', ! 'MovieMediaLoadChildMovieFromDataReference', ! 'Media3DGetViewObject', ! ])] def makeblacklisttypes(self): --- 63,81 ---- "MakeMediaTimeTable", # ditto ## "VideoMediaGetStallCount", # Undefined in CW Pro 3 library ! # OS8 only: ! 'SpriteMediaGetIndImageProperty', # XXXX Why isn't this in carbon? ! 'CheckQuickTimeRegistration', ! 'SetMovieAnchorDataRef', ! 'GetMovieAnchorDataRef', ! 'GetMovieLoadState', ! 'OpenADataHandler', ! 'MovieMediaGetCurrentMovieProperty', ! 'MovieMediaGetCurrentTrackProperty', ! 'MovieMediaGetChildMovieDataReference', ! 'MovieMediaSetChildMovieDataReference', ! 'MovieMediaLoadChildMovieFromDataReference', ! 'Media3DGetViewObject', ! ] def makeblacklisttypes(self): From jackjansen@users.sourceforge.net Thu Dec 12 10:31:55 2002 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Thu, 12 Dec 2002 02:31:55 -0800 Subject: [Python-checkins] python/dist/src/Mac/Modules/snd _Sndmodule.c,1.12,1.13 sndscan.py,1.18,1.19 sndsupport.py,1.20,1.21 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Modules/snd In directory sc8-pr-cvs1:/tmp/cvs-serv21368/Modules/snd Modified Files: _Sndmodule.c sndscan.py sndsupport.py Log Message: Getting rid of pre-Carbon (MacOS8) support. All code depending on TARGET_API_MAC_OS8 (or !TARGET_API_MAC_CARBON) is gone. Also some TARGET_API_MAC_OSX conditional code is gone, because it is no longer used on OSX-only Python (only in MacPython-OS9). Index: _Sndmodule.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/snd/_Sndmodule.c,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** _Sndmodule.c 3 Dec 2002 23:40:21 -0000 1.12 --- _Sndmodule.c 12 Dec 2002 10:31:53 -0000 1.13 *************** *** 28,40 **** #endif - #if !TARGET_API_MAC_CARBON - /* Create a SndCommand object (an (int, int, int) tuple) */ - static PyObject * - SndCmd_New(SndCommand *pc) - { - return Py_BuildValue("hhl", pc->cmd, pc->param1, pc->param2); - } - #endif - /* Convert a SndCommand argument */ static int --- 28,31 ---- *************** *** 55,61 **** static pascal void SndCh_UserRoutine(SndChannelPtr chan, SndCommand *cmd); /* Forward */ static pascal void SPB_completion(SPBPtr my_spb); /* Forward */ - #if !TARGET_API_MAC_CARBON - static pascal void SPB_interrupt(SPBPtr my_spb); /* Forward */ - #endif static PyObject *Snd_Error; --- 46,49 ---- *************** *** 148,217 **** } - #if !TARGET_API_MAC_CARBON - - static PyObject *SndCh_SndStartFilePlay(SndChannelObject *_self, PyObject *_args) - { - PyObject *_res = NULL; - OSErr _err; - short fRefNum; - short resNum; - long bufferSize; - Boolean async; - if (!PyArg_ParseTuple(_args, "hhlb", - &fRefNum, - &resNum, - &bufferSize, - &async)) - return NULL; - _err = SndStartFilePlay(_self->ob_itself, - fRefNum, - resNum, - bufferSize, - 0, - 0, - 0, - async); - if (_err != noErr) return PyMac_Error(_err); - Py_INCREF(Py_None); - _res = Py_None; - return _res; - } - #endif - - #if !TARGET_API_MAC_CARBON - - static PyObject *SndCh_SndPauseFilePlay(SndChannelObject *_self, PyObject *_args) - { - PyObject *_res = NULL; - OSErr _err; - if (!PyArg_ParseTuple(_args, "")) - return NULL; - _err = SndPauseFilePlay(_self->ob_itself); - if (_err != noErr) return PyMac_Error(_err); - Py_INCREF(Py_None); - _res = Py_None; - return _res; - } - #endif - - #if !TARGET_API_MAC_CARBON - - static PyObject *SndCh_SndStopFilePlay(SndChannelObject *_self, PyObject *_args) - { - PyObject *_res = NULL; - OSErr _err; - Boolean quietNow; - if (!PyArg_ParseTuple(_args, "b", - &quietNow)) - return NULL; - _err = SndStopFilePlay(_self->ob_itself, - quietNow); - if (_err != noErr) return PyMac_Error(_err); - Py_INCREF(Py_None); - _res = Py_None; - return _res; - } - #endif - static PyObject *SndCh_SndChannelStatus(SndChannelObject *_self, PyObject *_args) { --- 136,139 ---- *************** *** 277,295 **** {"SndPlay", (PyCFunction)SndCh_SndPlay, 1, PyDoc_STR("(SndListHandle sndHandle, Boolean async) -> None")}, - - #if !TARGET_API_MAC_CARBON - {"SndStartFilePlay", (PyCFunction)SndCh_SndStartFilePlay, 1, - PyDoc_STR("(short fRefNum, short resNum, long bufferSize, Boolean async) -> None")}, - #endif - - #if !TARGET_API_MAC_CARBON - {"SndPauseFilePlay", (PyCFunction)SndCh_SndPauseFilePlay, 1, - PyDoc_STR("() -> None")}, - #endif - - #if !TARGET_API_MAC_CARBON - {"SndStopFilePlay", (PyCFunction)SndCh_SndStopFilePlay, 1, - PyDoc_STR("(Boolean quietNow) -> None")}, - #endif {"SndChannelStatus", (PyCFunction)SndCh_SndChannelStatus, 1, PyDoc_STR("(short theLength) -> (SCStatus theStatus)")}, --- 199,202 ---- *************** *** 580,603 **** } - #if !TARGET_API_MAC_CARBON - - static PyObject *Snd_SndControl(PyObject *_self, PyObject *_args) - { - PyObject *_res = NULL; - OSErr _err; - short id; - SndCommand cmd; - if (!PyArg_ParseTuple(_args, "h", - &id)) - return NULL; - _err = SndControl(id, - &cmd); - if (_err != noErr) return PyMac_Error(_err); - _res = Py_BuildValue("O&", - SndCmd_New, &cmd); - return _res; - } - #endif - static PyObject *Snd_SndSoundManagerVersion(PyObject *_self, PyObject *_args) { --- 487,490 ---- *************** *** 656,854 **** } - #if !TARGET_API_MAC_CARBON - - static PyObject *Snd_MACEVersion(PyObject *_self, PyObject *_args) - { - PyObject *_res = NULL; - NumVersion _rv; - if (!PyArg_ParseTuple(_args, "")) - return NULL; - _rv = MACEVersion(); - _res = Py_BuildValue("O&", - PyMac_BuildNumVersion, _rv); - return _res; - } - #endif - - #if !TARGET_API_MAC_CARBON - - static PyObject *Snd_Comp3to1(PyObject *_self, PyObject *_args) - { - PyObject *_res = NULL; - char *buffer__in__; - char *buffer__out__; - long buffer__len__; - int buffer__in_len__; - StateBlock *state__in__; - StateBlock state__out__; - int state__in_len__; - unsigned long numChannels; - unsigned long whichChannel; - if (!PyArg_ParseTuple(_args, "s#s#ll", - &buffer__in__, &buffer__in_len__, - (char **)&state__in__, &state__in_len__, - &numChannels, - &whichChannel)) - return NULL; - if ((buffer__out__ = malloc(buffer__in_len__)) == NULL) - { - PyErr_NoMemory(); - goto buffer__error__; - } - buffer__len__ = buffer__in_len__; - if (state__in_len__ != sizeof(StateBlock)) - { - PyErr_SetString(PyExc_TypeError, "buffer length should be sizeof(StateBlock)"); - goto state__error__; - } - Comp3to1(buffer__in__, buffer__out__, (long)buffer__len__, - state__in__, &state__out__, - numChannels, - whichChannel); - _res = Py_BuildValue("s#s#", - buffer__out__, (int)buffer__len__, - (char *)&state__out__, (int)sizeof(StateBlock)); - state__error__: ; - free(buffer__out__); - buffer__error__: ; - return _res; - } - #endif - - #if !TARGET_API_MAC_CARBON - - static PyObject *Snd_Exp1to3(PyObject *_self, PyObject *_args) - { - PyObject *_res = NULL; - char *buffer__in__; - char *buffer__out__; - long buffer__len__; - int buffer__in_len__; - StateBlock *state__in__; - StateBlock state__out__; - int state__in_len__; - unsigned long numChannels; - unsigned long whichChannel; - if (!PyArg_ParseTuple(_args, "s#s#ll", - &buffer__in__, &buffer__in_len__, - (char **)&state__in__, &state__in_len__, - &numChannels, - &whichChannel)) - return NULL; - if ((buffer__out__ = malloc(buffer__in_len__)) == NULL) - { - PyErr_NoMemory(); - goto buffer__error__; - } - buffer__len__ = buffer__in_len__; - if (state__in_len__ != sizeof(StateBlock)) - { - PyErr_SetString(PyExc_TypeError, "buffer length should be sizeof(StateBlock)"); - goto state__error__; - } - Exp1to3(buffer__in__, buffer__out__, (long)buffer__len__, - state__in__, &state__out__, - numChannels, - whichChannel); - _res = Py_BuildValue("s#s#", - buffer__out__, (int)buffer__len__, - (char *)&state__out__, (int)sizeof(StateBlock)); - state__error__: ; - free(buffer__out__); - buffer__error__: ; - return _res; - } - #endif - - #if !TARGET_API_MAC_CARBON - - static PyObject *Snd_Comp6to1(PyObject *_self, PyObject *_args) - { - PyObject *_res = NULL; - char *buffer__in__; - char *buffer__out__; - long buffer__len__; - int buffer__in_len__; - StateBlock *state__in__; - StateBlock state__out__; - int state__in_len__; - unsigned long numChannels; - unsigned long whichChannel; - if (!PyArg_ParseTuple(_args, "s#s#ll", - &buffer__in__, &buffer__in_len__, - (char **)&state__in__, &state__in_len__, - &numChannels, - &whichChannel)) - return NULL; - if ((buffer__out__ = malloc(buffer__in_len__)) == NULL) - { - PyErr_NoMemory(); - goto buffer__error__; - } - buffer__len__ = buffer__in_len__; - if (state__in_len__ != sizeof(StateBlock)) - { - PyErr_SetString(PyExc_TypeError, "buffer length should be sizeof(StateBlock)"); - goto state__error__; - } - Comp6to1(buffer__in__, buffer__out__, (long)buffer__len__, - state__in__, &state__out__, - numChannels, - whichChannel); - _res = Py_BuildValue("s#s#", - buffer__out__, (int)buffer__len__, - (char *)&state__out__, (int)sizeof(StateBlock)); - state__error__: ; - free(buffer__out__); - buffer__error__: ; - return _res; - } - #endif - - #if !TARGET_API_MAC_CARBON - - static PyObject *Snd_Exp1to6(PyObject *_self, PyObject *_args) - { - PyObject *_res = NULL; - char *buffer__in__; - char *buffer__out__; - long buffer__len__; - int buffer__in_len__; - StateBlock *state__in__; - StateBlock state__out__; - int state__in_len__; - unsigned long numChannels; - unsigned long whichChannel; - if (!PyArg_ParseTuple(_args, "s#s#ll", - &buffer__in__, &buffer__in_len__, - (char **)&state__in__, &state__in_len__, - &numChannels, - &whichChannel)) - return NULL; - if ((buffer__out__ = malloc(buffer__in_len__)) == NULL) - { - PyErr_NoMemory(); - goto buffer__error__; - } - buffer__len__ = buffer__in_len__; - if (state__in_len__ != sizeof(StateBlock)) - { - PyErr_SetString(PyExc_TypeError, "buffer length should be sizeof(StateBlock)"); - goto state__error__; - } - Exp1to6(buffer__in__, buffer__out__, (long)buffer__len__, - state__in__, &state__out__, - numChannels, - whichChannel); - _res = Py_BuildValue("s#s#", - buffer__out__, (int)buffer__len__, - (char *)&state__out__, (int)sizeof(StateBlock)); - state__error__: ; - free(buffer__out__); - buffer__error__: ; - return _res; - } - #endif - static PyObject *Snd_GetSysBeepVolume(PyObject *_self, PyObject *_args) { --- 543,546 ---- *************** *** 1042,1070 **** } - #if !TARGET_API_MAC_CARBON - - static PyObject *Snd_SndRecordToFile(PyObject *_self, PyObject *_args) - { - PyObject *_res = NULL; - OSErr _err; - Point corner; - OSType quality; - short fRefNum; - if (!PyArg_ParseTuple(_args, "O&O&h", - PyMac_GetPoint, &corner, - PyMac_GetOSType, &quality, - &fRefNum)) - return NULL; - _err = SndRecordToFile((ModalFilterUPP)0, - corner, - quality, - fRefNum); - if (_err != noErr) return PyMac_Error(_err); - Py_INCREF(Py_None); - _res = Py_None; - return _res; - } - #endif - static PyObject *Snd_SPBSignInDevice(PyObject *_self, PyObject *_args) { --- 734,737 ---- *************** *** 1173,1200 **** } - #if !TARGET_API_MAC_CARBON - - static PyObject *Snd_SPBRecordToFile(PyObject *_self, PyObject *_args) - { - PyObject *_res = NULL; - OSErr _err; - short fRefNum; - SPBPtr inParamPtr; - Boolean asynchFlag; - if (!PyArg_ParseTuple(_args, "hO&b", - &fRefNum, - SPBObj_Convert, &inParamPtr, - &asynchFlag)) - return NULL; - _err = SPBRecordToFile(fRefNum, - inParamPtr, - asynchFlag); - if (_err != noErr) return PyMac_Error(_err); - Py_INCREF(Py_None); - _res = Py_None; - return _res; - } - #endif - static PyObject *Snd_SPBPauseRecording(PyObject *_self, PyObject *_args) { --- 840,843 ---- *************** *** 1357,1365 **** {"SndNewChannel", (PyCFunction)Snd_SndNewChannel, 1, PyDoc_STR("(short synth, long init, PyObject* userRoutine) -> (SndChannelPtr chan)")}, - - #if !TARGET_API_MAC_CARBON - {"SndControl", (PyCFunction)Snd_SndControl, 1, - PyDoc_STR("(short id) -> (SndCommand cmd)")}, - #endif {"SndSoundManagerVersion", (PyCFunction)Snd_SndSoundManagerVersion, 1, PyDoc_STR("() -> (NumVersion _rv)")}, --- 1000,1003 ---- *************** *** 1370,1398 **** {"SndSetSysBeepState", (PyCFunction)Snd_SndSetSysBeepState, 1, PyDoc_STR("(short sysBeepState) -> None")}, - - #if !TARGET_API_MAC_CARBON - {"MACEVersion", (PyCFunction)Snd_MACEVersion, 1, - PyDoc_STR("() -> (NumVersion _rv)")}, - #endif - - #if !TARGET_API_MAC_CARBON - {"Comp3to1", (PyCFunction)Snd_Comp3to1, 1, - PyDoc_STR("(Buffer buffer, StateBlock state, unsigned long numChannels, unsigned long whichChannel) -> (Buffer buffer, StateBlock state)")}, - #endif - - #if !TARGET_API_MAC_CARBON - {"Exp1to3", (PyCFunction)Snd_Exp1to3, 1, - PyDoc_STR("(Buffer buffer, StateBlock state, unsigned long numChannels, unsigned long whichChannel) -> (Buffer buffer, StateBlock state)")}, - #endif - - #if !TARGET_API_MAC_CARBON - {"Comp6to1", (PyCFunction)Snd_Comp6to1, 1, - PyDoc_STR("(Buffer buffer, StateBlock state, unsigned long numChannels, unsigned long whichChannel) -> (Buffer buffer, StateBlock state)")}, - #endif - - #if !TARGET_API_MAC_CARBON - {"Exp1to6", (PyCFunction)Snd_Exp1to6, 1, - PyDoc_STR("(Buffer buffer, StateBlock state, unsigned long numChannels, unsigned long whichChannel) -> (Buffer buffer, StateBlock state)")}, - #endif {"GetSysBeepVolume", (PyCFunction)Snd_GetSysBeepVolume, 1, PyDoc_STR("() -> (long level)")}, --- 1008,1011 ---- *************** *** 1417,1425 **** {"SndRecord", (PyCFunction)Snd_SndRecord, 1, PyDoc_STR("(Point corner, OSType quality) -> (SndListHandle sndHandle)")}, - - #if !TARGET_API_MAC_CARBON - {"SndRecordToFile", (PyCFunction)Snd_SndRecordToFile, 1, - PyDoc_STR("(Point corner, OSType quality, short fRefNum) -> None")}, - #endif {"SPBSignInDevice", (PyCFunction)Snd_SPBSignInDevice, 1, PyDoc_STR("(short deviceRefNum, Str255 deviceName) -> None")}, --- 1030,1033 ---- *************** *** 1434,1442 **** {"SPBRecord", (PyCFunction)Snd_SPBRecord, 1, PyDoc_STR("(SPBPtr inParamPtr, Boolean asynchFlag) -> None")}, - - #if !TARGET_API_MAC_CARBON - {"SPBRecordToFile", (PyCFunction)Snd_SPBRecordToFile, 1, - PyDoc_STR("(short fRefNum, SPBPtr inParamPtr, Boolean asynchFlag) -> None")}, - #endif {"SPBPauseRecording", (PyCFunction)Snd_SPBPauseRecording, 1, PyDoc_STR("(long inRefNum) -> None")}, --- 1042,1045 ---- *************** *** 1522,1539 **** } - #if !TARGET_API_MAC_CARBON - static pascal void - SPB_interrupt(SPBPtr my_spb) - { - SPBObject *p = (SPBObject *)(my_spb->userLong); - - if (p && p->ob_interrupt) { - long A5 = SetA5(p->ob_A5); - p->ob_thiscallback = p->ob_interrupt; /* Hope we cannot get two at the same time */ - Py_AddPendingCall(SPB_CallCallBack, (void *)p); - SetA5(A5); - } - } - #endif --- 1125,1128 ---- Index: sndscan.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/snd/sndscan.py,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** sndscan.py 15 Aug 2002 21:48:15 -0000 1.18 --- sndscan.py 12 Dec 2002 10:31:53 -0000 1.19 *************** *** 50,71 **** 'rate44khz', 'kInvalidSource', ] - - def makegreylist(self): - return [ - ('#if !TARGET_API_MAC_CARBON', [ - 'MACEVersion', - 'SPBRecordToFile', - 'Exp1to6', - 'Comp6to1', - 'Exp1to3', - 'Comp3to1', - 'SndControl', - 'SndStopFilePlay', - 'SndStartFilePlay', - 'SndPauseFilePlay', - 'SndRecordToFile', - ])] def makeblacklisttypes(self): --- 50,67 ---- 'rate44khz', 'kInvalidSource', + # OS8 only: + 'MACEVersion', + 'SPBRecordToFile', + 'Exp1to6', + 'Comp6to1', + 'Exp1to3', + 'Comp3to1', + 'SndControl', + 'SndStopFilePlay', + 'SndStartFilePlay', + 'SndPauseFilePlay', + 'SndRecordToFile', ] def makeblacklisttypes(self): Index: sndsupport.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Modules/snd/sndsupport.py,v retrieving revision 1.20 retrieving revision 1.21 diff -C2 -d -r1.20 -r1.21 *** sndsupport.py 29 Nov 2002 23:40:47 -0000 1.20 --- sndsupport.py 12 Dec 2002 10:31:53 -0000 1.21 *************** *** 97,109 **** includestuff = includestuff + """ - #if !TARGET_API_MAC_CARBON - /* Create a SndCommand object (an (int, int, int) tuple) */ - static PyObject * - SndCmd_New(SndCommand *pc) - { - return Py_BuildValue("hhl", pc->cmd, pc->param1, pc->param2); - } - #endif - /* Convert a SndCommand argument */ static int --- 97,100 ---- *************** *** 124,130 **** static pascal void SndCh_UserRoutine(SndChannelPtr chan, SndCommand *cmd); /* Forward */ static pascal void SPB_completion(SPBPtr my_spb); /* Forward */ - #if !TARGET_API_MAC_CARBON - static pascal void SPB_interrupt(SPBPtr my_spb); /* Forward */ - #endif """ --- 115,118 ---- *************** *** 193,210 **** } - #if !TARGET_API_MAC_CARBON - static pascal void - SPB_interrupt(SPBPtr my_spb) - { - SPBObject *p = (SPBObject *)(my_spb->userLong); - - if (p && p->ob_interrupt) { - long A5 = SetA5(p->ob_A5); - p->ob_thiscallback = p->ob_interrupt; /* Hope we cannot get two at the same time */ - Py_AddPendingCall(SPB_CallCallBack, (void *)p); - SetA5(A5); - } - } - #endif """ --- 181,184 ---- From jackjansen@users.sourceforge.net Thu Dec 12 10:31:56 2002 From: jackjansen@users.sourceforge.net (jackjansen@users.sourceforge.net) Date: Thu, 12 Dec 2002 02:31:56 -0800 Subject: [Python-checkins] python/dist/src/Mac/Python macgetargv.c,1.26,1.27 macgetcompiler.c,1.18,1.19 macgetpath.c,1.27,1.28 macglue.c,1.112,1.113 macmain.c,1.79,1.80 pyGUSISIOUX.cp,1.4,1.5 Message-ID: Update of /cvsroot/python/python/dist/src/Mac/Python In directory sc8-pr-cvs1:/tmp/cvs-serv21368/Python Modified Files: macgetargv.c macgetcompiler.c macgetpath.c macglue.c macmain.c pyGUSISIOUX.cp Log Message: Getting rid of pre-Carbon (MacOS8) support. All code depending on TARGET_API_MAC_OS8 (or !TARGET_API_MAC_CARBON) is gone. Also some TARGET_API_MAC_OSX conditional code is gone, because it is no longer used on OSX-only Python (only in MacPython-OS9). Index: macgetargv.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Python/macgetargv.c,v retrieving revision 1.26 retrieving revision 1.27 diff -C2 -d -r1.26 -r1.27 *** macgetargv.c 10 Sep 2001 22:00:39 -0000 1.26 --- macgetargv.c 12 Dec 2002 10:31:53 -0000 1.27 *************** *** 55,63 **** #include "macglue.h" - #ifdef TARGET_API_MAC_OSX - #define PATHNAMELEN 1024 - #else #define PATHNAMELEN 256 - #endif static int arg_count; --- 55,59 ---- *************** *** 80,85 **** #endif - - #if !TARGET_API_MAC_OSX /* Initialize FSSpec and full name of current application */ --- 76,79 ---- *************** *** 105,109 **** return 0; } - #endif /* !TARGET_API_MAC_OSX */ /* Check that there aren't any args remaining in the event */ --- 99,102 ---- *************** *** 230,236 **** got_one = 0; for (n = 0; n < 100 && !got_one; n++) { - #if !TARGET_API_MAC_CARBON - SystemTask(); - #endif ok = GetNextEvent(everyEvent, &event); if (ok && event.what == kHighLevelEvent) { --- 223,226 ---- *************** *** 246,256 **** { arg_count = 0; - #if TARGET_API_MAC_OSX - /* In an OSX bundle argv[0] is okay */ - arg_count++; - #else (void)PyMac_init_process_location(); arg_vector[arg_count++] = strdup(PyMac_ApplicationPath); - #endif /* TARGET_API_MAC_OSX */ if( !noevents ) { --- 236,241 ---- Index: macgetcompiler.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Python/macgetcompiler.c,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** macgetcompiler.c 7 Jul 2002 20:54:44 -0000 1.18 --- macgetcompiler.c 12 Dec 2002 10:31:54 -0000 1.19 *************** *** 48,58 **** #endif ! #if TARGET_API_MAC_CARBON ! #define TARGET_API "" ! #else ! #define TARGET_API " PPC" ! #endif ! ! #define COMPILER " [CW" TARGET_API HASGUSI HASTHREAD"]" #endif --- 48,52 ---- #endif ! #define COMPILER " [CW" HASGUSI HASTHREAD"]" #endif Index: macgetpath.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Python/macgetpath.c,v retrieving revision 1.27 retrieving revision 1.28 diff -C2 -d -r1.27 -r1.28 *** macgetpath.c 17 Jul 2002 16:30:35 -0000 1.27 --- macgetpath.c 12 Dec 2002 10:31:54 -0000 1.28 *************** *** 39,47 **** #endif - #ifdef TARGET_API_MAC_OSX - #define PATHNAMELEN 1024 - #else #define PATHNAMELEN 256 - #endif /* Return the initial python search path. This is called once from --- 39,43 ---- Index: macglue.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Python/macglue.c,v retrieving revision 1.112 retrieving revision 1.113 diff -C2 -d -r1.112 -r1.113 *** macglue.c 26 Jun 2002 20:37:40 -0000 1.112 --- macglue.c 12 Dec 2002 10:31:54 -0000 1.113 *************** *** 52,60 **** #endif - #if !TARGET_API_MAC_OS8 - /* Unfortunately this call is probably slower... */ - #define LMGetTicks() TickCount() - #endif - #ifdef __MWERKS__ #include --- 52,55 ---- *************** *** 86,90 **** #endif - #if TARGET_API_MAC_CARBON /* ** On MacOSX StackSpace() lies: it gives the distance from heap end to stack pointer, --- 81,84 ---- *************** *** 94,98 **** */ #define MAXIMUM_STACK_SIZE (256*1024) - #endif /* --- 88,91 ---- *************** *** 149,169 **** /* - ** Some stuff for our GetDirectory and PromptGetFile routines - */ - struct hook_args { - int selectcur_hit; /* Set to true when "select current" selected */ - char *prompt; /* The prompt */ - }; - #if !TARGET_API_MAC_OS8 - /* The StandardFile hooks don't exist in Carbon. This breaks GetDirectory, - ** but the macfsn code will replace it by a NavServices version anyway. - */ - #define myhook_upp NULL - #else - static DlgHookYDUPP myhook_upp; - static int upp_inited = 0; - #endif - - /* ** The python-code event handler */ --- 142,145 ---- *************** *** 257,302 **** } - #if TARGET_API_MAC_OS8 - /* - ** Replacement routines for the PLstr... functions so we don't need - ** StdCLib. - */ - pascal void - PLstrcpy(unsigned char *to, unsigned char *fr) - { - memcpy(to, fr, fr[0]+1); - } - - pascal int - PLstrcmp(unsigned char *s1, unsigned char *s2) - { - int res; - int l = s1[0] < s2[0] ? s1[0] : s2[0]; - - res = memcmp(s1+1, s2+1, l); - if ( res != 0 ) - return res; - - if ( s1[0] < s2[0] ) - return -1; - else if ( s1[0] > s2[0] ) - return 1; - else - return 0; - } - - pascal unsigned char * - PLstrrchr(unsigned char *str, unsigned char chr) - { - unsigned char *ptr = 0; - unsigned char *p; - - for(p=str+1; p 255 ) len = 255; - strncpy((char *)dst+1, src, len); - dst[0] = len; - } - #endif /* TARGET_API_MAC_OS8 */ #ifdef USE_STACKCHECK --- 251,254 ---- *************** *** 421,446 **** int force; { - #if !TARGET_API_MAC_OS8 if ( interrupted || (!schedparams.check_interrupt && !force) ) return; if ( CheckEventQueueForUserCancel() ) interrupted = 1; - #else - register EvQElPtr q; - - if ( interrupted || (!schedparams.check_interrupt && !force) || !PyMac_InForeground() ) - return; - q = (EvQElPtr) LMGetEventQueue()->qHead; - - for (; q; q = (EvQElPtr)q->qLink) { - if (q->evtQWhat == keyDown && - (char)q->evtQMessage == '.' && - (q->evtQModifiers & cmdKey) != 0) { - FlushEvents(keyDownMask, 0); - interrupted = 1; - break; - } - } - #endif } --- 332,339 ---- *************** *** 449,453 **** { if (schedparams.enabled) { ! if ( interrupted || (unsigned long)LMGetTicks() > schedparams.next_check ) { scan_event_queue(0); if (interrupted) { --- 342,346 ---- { if (schedparams.enabled) { ! if ( interrupted || (unsigned long)TickCount() > schedparams.next_check ) { scan_event_queue(0); if (interrupted) { *************** *** 458,462 **** if ( PyMac_Yield() < 0) return -1; ! schedparams.next_check = (unsigned long)LMGetTicks() + schedparams.check_interval; } --- 351,355 ---- if ( PyMac_Yield() < 0) return -1; ! schedparams.next_check = (unsigned long)TickCount() + schedparams.check_interval; } *************** *** 499,512 **** EventRecord *evp; { - #if TARGET_API_MAC_OS8 - if ( evp->what == mouseDown ) { - WindowPtr wp; - - if ( FindWindow(evp->where, &wp) == inSysWindow ) { - SystemClick(evp, wp); - return; - } - } - #endif #ifdef __MWERKS__ { --- 392,395 ---- *************** *** 569,580 **** (python_event_handler && !maycallpython) ) { if ( maxsleep >= 0 ) { ! #if TARGET_API_MAC_OS8 ! SystemTask(); ! #else ! int xxx = 0; ! #endif } } else { ! latest_time_ready = LMGetTicks() + maxsleep; do { /* XXXX Hack by Jack. --- 452,459 ---- (python_event_handler && !maycallpython) ) { if ( maxsleep >= 0 ) { ! /* XXXX Need to do something here */ } } else { ! latest_time_ready = TickCount() + maxsleep; do { /* XXXX Hack by Jack. *************** *** 591,595 **** return -1; } ! maxsleep = latest_time_ready - LMGetTicks(); } while ( maxsleep > 0 ); } --- 470,474 ---- return -1; } ! maxsleep = latest_time_ready - TickCount(); } while ( maxsleep > 0 ); } *************** *** 731,811 **** #endif /* !TARGET_API_MAC_OSX */ - - #if TARGET_API_MAC_OS8 - /* - ** Helper routine for GetDirectory - */ - static pascal short - myhook_proc(short item, DialogPtr theDialog, struct hook_args *dataptr) - { - if ( item == sfHookFirstCall && dataptr->prompt) { - Handle prompth; - short type; - Rect rect; - - GetDialogItem(theDialog, PROMPT_ITEM, &type, &prompth, &rect); - if ( prompth ) - SetDialogItemText(prompth, (unsigned char *)dataptr->prompt); - } else - if ( item == SELECTCUR_ITEM ) { - item = sfItemCancelButton; - dataptr->selectcur_hit = 1; - } - return item; - } - - /* - ** Ask the user for a directory. I still can't understand - ** why Apple doesn't provide a standard solution for this... - */ - int - PyMac_GetDirectory(dirfss, prompt) - FSSpec *dirfss; - char *prompt; - { - static SFTypeList list = {'fldr', 0, 0, 0}; - static Point where = {-1, -1}; - StandardFileReply reply; - struct hook_args hook_args; - - if ( !upp_inited ) { - myhook_upp = NewDlgHookYDProc(myhook_proc); - upp_inited = 1; - } - if ( prompt && *prompt ) - hook_args.prompt = (char *)Pstring(prompt); - else - hook_args.prompt = NULL; - hook_args.selectcur_hit = 0; - CustomGetFile((FileFilterYDUPP)0, 1, list, &reply, GETDIR_ID, where, myhook_upp, - NULL, NULL, NULL, (void *)&hook_args); - - reply.sfFile.name[0] = 0; - if( FSMakeFSSpec(reply.sfFile.vRefNum, reply.sfFile.parID, reply.sfFile.name, dirfss) ) - return 0; - return hook_args.selectcur_hit; - } - - /* - ** Slightly extended StandardGetFile: accepts a prompt */ - void PyMac_PromptGetFile(short numTypes, ConstSFTypeListPtr typeList, - StandardFileReply *reply, char *prompt) - { - static Point where = {-1, -1}; - struct hook_args hook_args; - - if ( !upp_inited ) { - myhook_upp = NewDlgHookYDProc(myhook_proc); - upp_inited = 1; - } - if ( prompt && *prompt ) - hook_args.prompt = (char *)Pstring(prompt); - else - hook_args.prompt = NULL; - hook_args.selectcur_hit = 0; - CustomGetFile((FileFilterYDUPP)0, numTypes, typeList, reply, GETFILEPROMPT_ID, where, - myhook_upp, NULL, NULL, NULL, (void *)&hook_args); - } - #endif /* TARGET_API_MAC_OS8 */ - - --- 610,611 ---- Index: macmain.c =================================================================== RCS file: /cvsroot/python/python/dist/src/Mac/Python/macmain.c,v retrieving revision 1.79 retrieving revision 1.80 diff -C2 -d -r1.79 -r1.80 *** macmain.c 5 Aug 2002 14:13:31 -0000 1.79 --- macmain.c 12 Dec 2002 10:31:54 -0000 1.80 *************** *** 39,43 **** #include #include - #if TARGET_API_MAC_CARBON #include #include --- 39,42 ---- *************** *** 45,49 **** #include #include - #endif /* TARGET_API_MAC_CARBON */ #include #include --- 44,47 ---- *************** *** 95,108 **** init_mac_world(void) { - #if !TARGET_API_MAC_CARBON - /* These aren't needed for carbon */ - MaxApplZone(); - InitGraf(&qd.thePort); - InitFonts(); - InitWindows(); - TEInit(); - InitDialogs((long)0); - InitMenus(); - #endif InitCursor(); } --- 93,96 ---- *************** *** 177,186 **** exit(0); } - #if !TARGET_API_MAC_CARBON - if ( item == OPT_HELP ) { - HMSetBalloons(!HMGetBalloons()); - } - #endif - #if !TARGET_API_MAC_OSX if ( item == OPT_CMDLINE ) { int old_argc = *argcp; --- 165,168 ---- *************** *** 203,207 **** /* XXXX Is it not safe to use free() here, apparently */ } - #endif /* !TARGET_API_MAC_OSX */ #define OPT_ITEM(num, var) \ if ( item == (num) ) { \ --- 185,188 ---- *************** *** 280,286 **** PyMac_options.keep_console = POPT_KEEPCONSOLE_OUTPUT; /* default-default */ PyMac_options.unixnewlines = 1; - #if !TARGET_API_MAC_OSX PyMac_PreferenceOptions(&PyMac_options); - #endif if ( embedded ) { --- 261,265 ---- *************** *** 294,302 **** ** command line arguments. */ - #if TARGET_API_MAC_OSX - if (*argcp == 2 && strncmp((*argvp)[1], "-psn_", 5) == 0) - #endif *argcp = PyMac_GetArgv(argvp, PyMac_options.noargs); - #if !TARGET_API_MAC_OSX #ifndef NO_ARGV0_CHDIR if (*argcp >= 1 && (*argvp)[0] && (*argvp)[0][0]) { --- 273,277 ---- *************** *** 312,316 **** } #endif - #endif /* Do interactive option setting, if allowed and