You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1983 lines
54 KiB

36 years ago
36 years ago
36 years ago
36 years ago
23 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
Merged revisions 53451-53537 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r53454 | brett.cannon | 2007-01-15 20:12:08 +0100 (Mon, 15 Jan 2007) | 3 lines Add a note for strptime that just because strftime supports some extra directive that is not documented that strptime will as well. ........ r53458 | vinay.sajip | 2007-01-16 10:50:07 +0100 (Tue, 16 Jan 2007) | 1 line Updated rotating file handlers to use _open(). ........ r53459 | marc-andre.lemburg | 2007-01-16 14:03:06 +0100 (Tue, 16 Jan 2007) | 2 lines Add news items for the recent pybench and platform changes. ........ r53460 | sjoerd.mullender | 2007-01-16 17:42:38 +0100 (Tue, 16 Jan 2007) | 4 lines Fixed ntpath.expandvars to not replace references to non-existing variables with nothing. Also added tests. This fixes bug #494589. ........ r53464 | neal.norwitz | 2007-01-17 07:23:51 +0100 (Wed, 17 Jan 2007) | 1 line Give Calvin Spealman access for python-dev summaries. ........ r53465 | neal.norwitz | 2007-01-17 09:37:26 +0100 (Wed, 17 Jan 2007) | 1 line Remove Calvin since he only has access to the website currently. ........ r53466 | thomas.heller | 2007-01-17 10:40:34 +0100 (Wed, 17 Jan 2007) | 2 lines Replace C++ comments with C comments. ........ r53472 | andrew.kuchling | 2007-01-17 20:55:06 +0100 (Wed, 17 Jan 2007) | 1 line [Part of bug #1599254] Add suggestion to Mailbox docs to use Maildir, and warn user to lock/unlock mailboxes when modifying them ........ r53475 | georg.brandl | 2007-01-17 22:09:04 +0100 (Wed, 17 Jan 2007) | 2 lines Bug #1637967: missing //= operator in list. ........ r53477 | georg.brandl | 2007-01-17 22:19:58 +0100 (Wed, 17 Jan 2007) | 2 lines Bug #1629125: fix wrong data type (int -> Py_ssize_t) in PyDict_Next docs. ........ r53481 | neal.norwitz | 2007-01-18 06:40:58 +0100 (Thu, 18 Jan 2007) | 1 line Try reverting part of r53145 that seems to cause the Windows buildbots to fail in test_uu.UUFileTest.test_encode ........ r53482 | fred.drake | 2007-01-18 06:42:30 +0100 (Thu, 18 Jan 2007) | 1 line add missing version entry ........ r53483 | neal.norwitz | 2007-01-18 07:20:55 +0100 (Thu, 18 Jan 2007) | 7 lines This test doesn't pass on Windows. The cause seems to be that chmod doesn't support the same funcationality as on Unix. I'm not sure if this fix is the best (or if it will even work)--it's a test to see if the buildbots start passing again. It might be better to not even run this test if it's windows (or non-posix). ........ r53488 | neal.norwitz | 2007-01-19 06:53:33 +0100 (Fri, 19 Jan 2007) | 1 line SF #1635217, Fix unbalanced paren ........ r53489 | martin.v.loewis | 2007-01-19 07:42:22 +0100 (Fri, 19 Jan 2007) | 3 lines Prefix AST symbols with _Py_. Fixes #1637022. Will backport. ........ r53497 | martin.v.loewis | 2007-01-19 19:01:38 +0100 (Fri, 19 Jan 2007) | 2 lines Add UUIDs for 2.5.1 and 2.5.2 ........ r53499 | raymond.hettinger | 2007-01-19 19:07:18 +0100 (Fri, 19 Jan 2007) | 1 line SF# 1635892: Fix docs for betavariate's input parameters . ........ r53503 | martin.v.loewis | 2007-01-20 15:05:39 +0100 (Sat, 20 Jan 2007) | 2 lines Merge 53501 and 53502 from 25 branch: Add /GS- for AMD64 and Itanium builds where missing. ........ r53504 | walter.doerwald | 2007-01-20 18:28:31 +0100 (Sat, 20 Jan 2007) | 2 lines Port test_resource.py to unittest. ........ r53505 | walter.doerwald | 2007-01-20 19:19:33 +0100 (Sat, 20 Jan 2007) | 2 lines Add argument tests an calls of resource.getrusage(). ........ r53506 | walter.doerwald | 2007-01-20 20:03:17 +0100 (Sat, 20 Jan 2007) | 2 lines resource.RUSAGE_BOTH might not exist. ........ r53507 | walter.doerwald | 2007-01-21 00:07:28 +0100 (Sun, 21 Jan 2007) | 2 lines Port test_new.py to unittest. ........ r53508 | martin.v.loewis | 2007-01-21 10:33:07 +0100 (Sun, 21 Jan 2007) | 2 lines Patch #1610575: Add support for _Bool to struct. ........ r53509 | georg.brandl | 2007-01-21 11:28:43 +0100 (Sun, 21 Jan 2007) | 3 lines Bug #1486663: don't reject keyword arguments for subclasses of builtin types. ........ r53511 | georg.brandl | 2007-01-21 11:35:10 +0100 (Sun, 21 Jan 2007) | 2 lines Patch #1627441: close sockets properly in urllib2. ........ r53517 | georg.brandl | 2007-01-22 20:40:21 +0100 (Mon, 22 Jan 2007) | 3 lines Use new email module names (#1637162, #1637159, #1637157). ........ r53518 | andrew.kuchling | 2007-01-22 21:26:40 +0100 (Mon, 22 Jan 2007) | 1 line Improve pattern used for mbox 'From' lines; add a simple test ........ r53519 | andrew.kuchling | 2007-01-22 21:27:50 +0100 (Mon, 22 Jan 2007) | 1 line Make comment match the code ........ r53522 | georg.brandl | 2007-01-22 22:10:33 +0100 (Mon, 22 Jan 2007) | 2 lines Bug #1249573: fix rfc822.parsedate not accepting a certain date format ........ r53524 | georg.brandl | 2007-01-22 22:23:41 +0100 (Mon, 22 Jan 2007) | 2 lines Bug #1627316: handle error in condition/ignore pdb commands more gracefully. ........ r53526 | lars.gustaebel | 2007-01-23 12:17:33 +0100 (Tue, 23 Jan 2007) | 4 lines Patch #1507247: tarfile.py: use current umask for intermediate directories. ........ r53527 | thomas.wouters | 2007-01-23 14:42:00 +0100 (Tue, 23 Jan 2007) | 13 lines SF patch #1630975: Fix crash when replacing sys.stdout in sitecustomize When running the interpreter in an environment that would cause it to set stdout/stderr/stdin's encoding, having a sitecustomize that would replace them with something other than PyFile objects would crash the interpreter. Fix it by simply ignoring the encoding-setting for non-files. This could do with a test, but I can think of no maintainable and portable way to test this bug, short of adding a sitecustomize.py to the buildsystem and have it always run with it (hmmm....) ........ r53528 | thomas.wouters | 2007-01-23 14:50:49 +0100 (Tue, 23 Jan 2007) | 4 lines Add news entry about last checkin (oops.) ........ r53531 | martin.v.loewis | 2007-01-23 22:11:47 +0100 (Tue, 23 Jan 2007) | 4 lines Make PyTraceBack_Here use the current thread, not the frame's thread state. Fixes #1579370. Will backport. ........ r53535 | brett.cannon | 2007-01-24 00:21:22 +0100 (Wed, 24 Jan 2007) | 5 lines Fix crasher for when an object's __del__ creates a new weakref to itself. Patch only fixes new-style classes; classic classes still buggy. Closes bug #1377858. Already backported. ........ r53536 | walter.doerwald | 2007-01-24 01:42:19 +0100 (Wed, 24 Jan 2007) | 2 lines Port test_popen.py to unittest. ........
19 years ago
36 years ago
Changes to recursive-object comparisons, having to do with a test case I found where rich comparison of unequal recursive objects gave unintuituve results. In a discussion with Tim, where we discovered that our intuition on when a<=b should be true was failing, we decided to outlaw ordering comparisons on recursive objects. (Once we have fixed our intuition and designed a matching algorithm that's practical and reasonable to implement, we can allow such orderings again.) - Refactored the recursive-object comparison framework; more is now done in the support routines so less needs to be done in the calling routines (even at the expense of slowing it down a bit -- this should normally never be invoked, it's mostly just there to avoid blowing up the interpreter). - Changed the framework so that the comparison operator used is also stored. (The dictionary now stores triples (v, w, op) instead of pairs (v, w).) - Changed the nesting limit to a more reasonable small 20; this only slows down comparisons of very deeply nested objects (unlikely to occur in practice), while speeding up comparisons of recursive objects (previously, this would first waste time and space on 500 nested comparisons before it would start detecting recursion). - Changed rich comparisons for recursive objects to raise a ValueError exception when recursion is detected for ordering oprators (<, <=, >, >=). Unrelated change: - Moved PyObject_Unicode() to just under PyObject_Str(), where it belongs. MAL's patch must've inserted in a random spot between two functions in the file -- between two helpers for rich comparison...
25 years ago
16 years ago
16 years ago
Restructure comparison dramatically. There is no longer a default *ordering* between objects; there is only a default equality test (defined by an object being equal to itself only). Read the comment in object.c. The current implementation never uses a three-way comparison to compute a rich comparison, but it does use a rich comparison to compute a three-way comparison. I'm not quite done ripping out all the calls to PyObject_Compare/Cmp, or replacing tp_compare implementations with tp_richcompare implementations; but much of that has happened (to make most unit tests pass). The following tests still fail, because I need help deciding or understanding: test_codeop -- depends on comparing code objects test_datetime -- need Tim Peters' opinion test_marshal -- depends on comparing code objects test_mutants -- need help understanding it The problem with test_codeop and test_marshal is this: these tests compare two different code objects and expect them to be equal. Is that still a feature we'd like to support? I've temporarily removed the comparison and hash code from code objects, so they use the default (equality by pointer only) comparison. For the other two tests, run them to see for yourself. (There may be more failing test with "-u all".) A general problem with getting lots of these tests to pass is the reality that for object types that have a natural total ordering, implementing __cmp__ is much more convenient than implementing __eq__, __ne__, __lt__, and so on. Should we go back to allowing __cmp__ to provide a total ordering? Should we provide some other way to implement rich comparison with a single method override? Alex proposed a __key__() method; I've considered a __richcmp__() method. Or perhaps __cmp__() just shouldn't be killed off...
20 years ago
Restructure comparison dramatically. There is no longer a default *ordering* between objects; there is only a default equality test (defined by an object being equal to itself only). Read the comment in object.c. The current implementation never uses a three-way comparison to compute a rich comparison, but it does use a rich comparison to compute a three-way comparison. I'm not quite done ripping out all the calls to PyObject_Compare/Cmp, or replacing tp_compare implementations with tp_richcompare implementations; but much of that has happened (to make most unit tests pass). The following tests still fail, because I need help deciding or understanding: test_codeop -- depends on comparing code objects test_datetime -- need Tim Peters' opinion test_marshal -- depends on comparing code objects test_mutants -- need help understanding it The problem with test_codeop and test_marshal is this: these tests compare two different code objects and expect them to be equal. Is that still a feature we'd like to support? I've temporarily removed the comparison and hash code from code objects, so they use the default (equality by pointer only) comparison. For the other two tests, run them to see for yourself. (There may be more failing test with "-u all".) A general problem with getting lots of these tests to pass is the reality that for object types that have a natural total ordering, implementing __cmp__ is much more convenient than implementing __eq__, __ne__, __lt__, and so on. Should we go back to allowing __cmp__ to provide a total ordering? Should we provide some other way to implement rich comparison with a single method override? Alex proposed a __key__() method; I've considered a __richcmp__() method. Or perhaps __cmp__() just shouldn't be killed off...
20 years ago
Restructure comparison dramatically. There is no longer a default *ordering* between objects; there is only a default equality test (defined by an object being equal to itself only). Read the comment in object.c. The current implementation never uses a three-way comparison to compute a rich comparison, but it does use a rich comparison to compute a three-way comparison. I'm not quite done ripping out all the calls to PyObject_Compare/Cmp, or replacing tp_compare implementations with tp_richcompare implementations; but much of that has happened (to make most unit tests pass). The following tests still fail, because I need help deciding or understanding: test_codeop -- depends on comparing code objects test_datetime -- need Tim Peters' opinion test_marshal -- depends on comparing code objects test_mutants -- need help understanding it The problem with test_codeop and test_marshal is this: these tests compare two different code objects and expect them to be equal. Is that still a feature we'd like to support? I've temporarily removed the comparison and hash code from code objects, so they use the default (equality by pointer only) comparison. For the other two tests, run them to see for yourself. (There may be more failing test with "-u all".) A general problem with getting lots of these tests to pass is the reality that for object types that have a natural total ordering, implementing __cmp__ is much more convenient than implementing __eq__, __ne__, __lt__, and so on. Should we go back to allowing __cmp__ to provide a total ordering? Should we provide some other way to implement rich comparison with a single method override? Alex proposed a __key__() method; I've considered a __richcmp__() method. Or perhaps __cmp__() just shouldn't be killed off...
20 years ago
Restructure comparison dramatically. There is no longer a default *ordering* between objects; there is only a default equality test (defined by an object being equal to itself only). Read the comment in object.c. The current implementation never uses a three-way comparison to compute a rich comparison, but it does use a rich comparison to compute a three-way comparison. I'm not quite done ripping out all the calls to PyObject_Compare/Cmp, or replacing tp_compare implementations with tp_richcompare implementations; but much of that has happened (to make most unit tests pass). The following tests still fail, because I need help deciding or understanding: test_codeop -- depends on comparing code objects test_datetime -- need Tim Peters' opinion test_marshal -- depends on comparing code objects test_mutants -- need help understanding it The problem with test_codeop and test_marshal is this: these tests compare two different code objects and expect them to be equal. Is that still a feature we'd like to support? I've temporarily removed the comparison and hash code from code objects, so they use the default (equality by pointer only) comparison. For the other two tests, run them to see for yourself. (There may be more failing test with "-u all".) A general problem with getting lots of these tests to pass is the reality that for object types that have a natural total ordering, implementing __cmp__ is much more convenient than implementing __eq__, __ne__, __lt__, and so on. Should we go back to allowing __cmp__ to provide a total ordering? Should we provide some other way to implement rich comparison with a single method override? Alex proposed a __key__() method; I've considered a __richcmp__() method. Or perhaps __cmp__() just shouldn't be killed off...
20 years ago
Restructure comparison dramatically. There is no longer a default *ordering* between objects; there is only a default equality test (defined by an object being equal to itself only). Read the comment in object.c. The current implementation never uses a three-way comparison to compute a rich comparison, but it does use a rich comparison to compute a three-way comparison. I'm not quite done ripping out all the calls to PyObject_Compare/Cmp, or replacing tp_compare implementations with tp_richcompare implementations; but much of that has happened (to make most unit tests pass). The following tests still fail, because I need help deciding or understanding: test_codeop -- depends on comparing code objects test_datetime -- need Tim Peters' opinion test_marshal -- depends on comparing code objects test_mutants -- need help understanding it The problem with test_codeop and test_marshal is this: these tests compare two different code objects and expect them to be equal. Is that still a feature we'd like to support? I've temporarily removed the comparison and hash code from code objects, so they use the default (equality by pointer only) comparison. For the other two tests, run them to see for yourself. (There may be more failing test with "-u all".) A general problem with getting lots of these tests to pass is the reality that for object types that have a natural total ordering, implementing __cmp__ is much more convenient than implementing __eq__, __ne__, __lt__, and so on. Should we go back to allowing __cmp__ to provide a total ordering? Should we provide some other way to implement rich comparison with a single method override? Alex proposed a __key__() method; I've considered a __richcmp__() method. Or perhaps __cmp__() just shouldn't be killed off...
20 years ago
Restructure comparison dramatically. There is no longer a default *ordering* between objects; there is only a default equality test (defined by an object being equal to itself only). Read the comment in object.c. The current implementation never uses a three-way comparison to compute a rich comparison, but it does use a rich comparison to compute a three-way comparison. I'm not quite done ripping out all the calls to PyObject_Compare/Cmp, or replacing tp_compare implementations with tp_richcompare implementations; but much of that has happened (to make most unit tests pass). The following tests still fail, because I need help deciding or understanding: test_codeop -- depends on comparing code objects test_datetime -- need Tim Peters' opinion test_marshal -- depends on comparing code objects test_mutants -- need help understanding it The problem with test_codeop and test_marshal is this: these tests compare two different code objects and expect them to be equal. Is that still a feature we'd like to support? I've temporarily removed the comparison and hash code from code objects, so they use the default (equality by pointer only) comparison. For the other two tests, run them to see for yourself. (There may be more failing test with "-u all".) A general problem with getting lots of these tests to pass is the reality that for object types that have a natural total ordering, implementing __cmp__ is much more convenient than implementing __eq__, __ne__, __lt__, and so on. Should we go back to allowing __cmp__ to provide a total ordering? Should we provide some other way to implement rich comparison with a single method override? Alex proposed a __key__() method; I've considered a __richcmp__() method. Or perhaps __cmp__() just shouldn't be killed off...
20 years ago
Restructure comparison dramatically. There is no longer a default *ordering* between objects; there is only a default equality test (defined by an object being equal to itself only). Read the comment in object.c. The current implementation never uses a three-way comparison to compute a rich comparison, but it does use a rich comparison to compute a three-way comparison. I'm not quite done ripping out all the calls to PyObject_Compare/Cmp, or replacing tp_compare implementations with tp_richcompare implementations; but much of that has happened (to make most unit tests pass). The following tests still fail, because I need help deciding or understanding: test_codeop -- depends on comparing code objects test_datetime -- need Tim Peters' opinion test_marshal -- depends on comparing code objects test_mutants -- need help understanding it The problem with test_codeop and test_marshal is this: these tests compare two different code objects and expect them to be equal. Is that still a feature we'd like to support? I've temporarily removed the comparison and hash code from code objects, so they use the default (equality by pointer only) comparison. For the other two tests, run them to see for yourself. (There may be more failing test with "-u all".) A general problem with getting lots of these tests to pass is the reality that for object types that have a natural total ordering, implementing __cmp__ is much more convenient than implementing __eq__, __ne__, __lt__, and so on. Should we go back to allowing __cmp__ to provide a total ordering? Should we provide some other way to implement rich comparison with a single method override? Alex proposed a __key__() method; I've considered a __richcmp__() method. Or perhaps __cmp__() just shouldn't be killed off...
20 years ago
36 years ago
Restructure comparison dramatically. There is no longer a default *ordering* between objects; there is only a default equality test (defined by an object being equal to itself only). Read the comment in object.c. The current implementation never uses a three-way comparison to compute a rich comparison, but it does use a rich comparison to compute a three-way comparison. I'm not quite done ripping out all the calls to PyObject_Compare/Cmp, or replacing tp_compare implementations with tp_richcompare implementations; but much of that has happened (to make most unit tests pass). The following tests still fail, because I need help deciding or understanding: test_codeop -- depends on comparing code objects test_datetime -- need Tim Peters' opinion test_marshal -- depends on comparing code objects test_mutants -- need help understanding it The problem with test_codeop and test_marshal is this: these tests compare two different code objects and expect them to be equal. Is that still a feature we'd like to support? I've temporarily removed the comparison and hash code from code objects, so they use the default (equality by pointer only) comparison. For the other two tests, run them to see for yourself. (There may be more failing test with "-u all".) A general problem with getting lots of these tests to pass is the reality that for object types that have a natural total ordering, implementing __cmp__ is much more convenient than implementing __eq__, __ne__, __lt__, and so on. Should we go back to allowing __cmp__ to provide a total ordering? Should we provide some other way to implement rich comparison with a single method override? Alex proposed a __key__() method; I've considered a __richcmp__() method. Or perhaps __cmp__() just shouldn't be killed off...
20 years ago
Restructure comparison dramatically. There is no longer a default *ordering* between objects; there is only a default equality test (defined by an object being equal to itself only). Read the comment in object.c. The current implementation never uses a three-way comparison to compute a rich comparison, but it does use a rich comparison to compute a three-way comparison. I'm not quite done ripping out all the calls to PyObject_Compare/Cmp, or replacing tp_compare implementations with tp_richcompare implementations; but much of that has happened (to make most unit tests pass). The following tests still fail, because I need help deciding or understanding: test_codeop -- depends on comparing code objects test_datetime -- need Tim Peters' opinion test_marshal -- depends on comparing code objects test_mutants -- need help understanding it The problem with test_codeop and test_marshal is this: these tests compare two different code objects and expect them to be equal. Is that still a feature we'd like to support? I've temporarily removed the comparison and hash code from code objects, so they use the default (equality by pointer only) comparison. For the other two tests, run them to see for yourself. (There may be more failing test with "-u all".) A general problem with getting lots of these tests to pass is the reality that for object types that have a natural total ordering, implementing __cmp__ is much more convenient than implementing __eq__, __ne__, __lt__, and so on. Should we go back to allowing __cmp__ to provide a total ordering? Should we provide some other way to implement rich comparison with a single method override? Alex proposed a __key__() method; I've considered a __richcmp__() method. Or perhaps __cmp__() just shouldn't be killed off...
20 years ago
Restructure comparison dramatically. There is no longer a default *ordering* between objects; there is only a default equality test (defined by an object being equal to itself only). Read the comment in object.c. The current implementation never uses a three-way comparison to compute a rich comparison, but it does use a rich comparison to compute a three-way comparison. I'm not quite done ripping out all the calls to PyObject_Compare/Cmp, or replacing tp_compare implementations with tp_richcompare implementations; but much of that has happened (to make most unit tests pass). The following tests still fail, because I need help deciding or understanding: test_codeop -- depends on comparing code objects test_datetime -- need Tim Peters' opinion test_marshal -- depends on comparing code objects test_mutants -- need help understanding it The problem with test_codeop and test_marshal is this: these tests compare two different code objects and expect them to be equal. Is that still a feature we'd like to support? I've temporarily removed the comparison and hash code from code objects, so they use the default (equality by pointer only) comparison. For the other two tests, run them to see for yourself. (There may be more failing test with "-u all".) A general problem with getting lots of these tests to pass is the reality that for object types that have a natural total ordering, implementing __cmp__ is much more convenient than implementing __eq__, __ne__, __lt__, and so on. Should we go back to allowing __cmp__ to provide a total ordering? Should we provide some other way to implement rich comparison with a single method override? Alex proposed a __key__() method; I've considered a __richcmp__() method. Or perhaps __cmp__() just shouldn't be killed off...
20 years ago
Restructure comparison dramatically. There is no longer a default *ordering* between objects; there is only a default equality test (defined by an object being equal to itself only). Read the comment in object.c. The current implementation never uses a three-way comparison to compute a rich comparison, but it does use a rich comparison to compute a three-way comparison. I'm not quite done ripping out all the calls to PyObject_Compare/Cmp, or replacing tp_compare implementations with tp_richcompare implementations; but much of that has happened (to make most unit tests pass). The following tests still fail, because I need help deciding or understanding: test_codeop -- depends on comparing code objects test_datetime -- need Tim Peters' opinion test_marshal -- depends on comparing code objects test_mutants -- need help understanding it The problem with test_codeop and test_marshal is this: these tests compare two different code objects and expect them to be equal. Is that still a feature we'd like to support? I've temporarily removed the comparison and hash code from code objects, so they use the default (equality by pointer only) comparison. For the other two tests, run them to see for yourself. (There may be more failing test with "-u all".) A general problem with getting lots of these tests to pass is the reality that for object types that have a natural total ordering, implementing __cmp__ is much more convenient than implementing __eq__, __ne__, __lt__, and so on. Should we go back to allowing __cmp__ to provide a total ordering? Should we provide some other way to implement rich comparison with a single method override? Alex proposed a __key__() method; I've considered a __richcmp__() method. Or perhaps __cmp__() just shouldn't be killed off...
20 years ago
14 years ago
36 years ago
36 years ago
36 years ago
34 years ago
36 years ago
36 years ago
36 years ago
Restructure comparison dramatically. There is no longer a default *ordering* between objects; there is only a default equality test (defined by an object being equal to itself only). Read the comment in object.c. The current implementation never uses a three-way comparison to compute a rich comparison, but it does use a rich comparison to compute a three-way comparison. I'm not quite done ripping out all the calls to PyObject_Compare/Cmp, or replacing tp_compare implementations with tp_richcompare implementations; but much of that has happened (to make most unit tests pass). The following tests still fail, because I need help deciding or understanding: test_codeop -- depends on comparing code objects test_datetime -- need Tim Peters' opinion test_marshal -- depends on comparing code objects test_mutants -- need help understanding it The problem with test_codeop and test_marshal is this: these tests compare two different code objects and expect them to be equal. Is that still a feature we'd like to support? I've temporarily removed the comparison and hash code from code objects, so they use the default (equality by pointer only) comparison. For the other two tests, run them to see for yourself. (There may be more failing test with "-u all".) A general problem with getting lots of these tests to pass is the reality that for object types that have a natural total ordering, implementing __cmp__ is much more convenient than implementing __eq__, __ne__, __lt__, and so on. Should we go back to allowing __cmp__ to provide a total ordering? Should we provide some other way to implement rich comparison with a single method override? Alex proposed a __key__() method; I've considered a __richcmp__() method. Or perhaps __cmp__() just shouldn't be killed off...
20 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
36 years ago
26 years ago
  1. /* Generic object operations; and implementation of None */
  2. #include "Python.h"
  3. #include "frameobject.h"
  4. #ifdef __cplusplus
  5. extern "C" {
  6. #endif
  7. #ifdef Py_REF_DEBUG
  8. Py_ssize_t _Py_RefTotal;
  9. Py_ssize_t
  10. _Py_GetRefTotal(void)
  11. {
  12. PyObject *o;
  13. Py_ssize_t total = _Py_RefTotal;
  14. /* ignore the references to the dummy object of the dicts and sets
  15. because they are not reliable and not useful (now that the
  16. hash table code is well-tested) */
  17. o = _PyDict_Dummy();
  18. if (o != NULL)
  19. total -= o->ob_refcnt;
  20. o = _PySet_Dummy();
  21. if (o != NULL)
  22. total -= o->ob_refcnt;
  23. return total;
  24. }
  25. #endif /* Py_REF_DEBUG */
  26. /* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
  27. These are used by the individual routines for object creation.
  28. Do not call them otherwise, they do not initialize the object! */
  29. #ifdef Py_TRACE_REFS
  30. /* Head of circular doubly-linked list of all objects. These are linked
  31. * together via the _ob_prev and _ob_next members of a PyObject, which
  32. * exist only in a Py_TRACE_REFS build.
  33. */
  34. static PyObject refchain = {&refchain, &refchain};
  35. /* Insert op at the front of the list of all objects. If force is true,
  36. * op is added even if _ob_prev and _ob_next are non-NULL already. If
  37. * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
  38. * force should be true if and only if op points to freshly allocated,
  39. * uninitialized memory, or you've unlinked op from the list and are
  40. * relinking it into the front.
  41. * Note that objects are normally added to the list via _Py_NewReference,
  42. * which is called by PyObject_Init. Not all objects are initialized that
  43. * way, though; exceptions include statically allocated type objects, and
  44. * statically allocated singletons (like Py_True and Py_None).
  45. */
  46. void
  47. _Py_AddToAllObjects(PyObject *op, int force)
  48. {
  49. #ifdef Py_DEBUG
  50. if (!force) {
  51. /* If it's initialized memory, op must be in or out of
  52. * the list unambiguously.
  53. */
  54. assert((op->_ob_prev == NULL) == (op->_ob_next == NULL));
  55. }
  56. #endif
  57. if (force || op->_ob_prev == NULL) {
  58. op->_ob_next = refchain._ob_next;
  59. op->_ob_prev = &refchain;
  60. refchain._ob_next->_ob_prev = op;
  61. refchain._ob_next = op;
  62. }
  63. }
  64. #endif /* Py_TRACE_REFS */
  65. #ifdef COUNT_ALLOCS
  66. static PyTypeObject *type_list;
  67. /* All types are added to type_list, at least when
  68. they get one object created. That makes them
  69. immortal, which unfortunately contributes to
  70. garbage itself. If unlist_types_without_objects
  71. is set, they will be removed from the type_list
  72. once the last object is deallocated. */
  73. static int unlist_types_without_objects;
  74. extern Py_ssize_t tuple_zero_allocs, fast_tuple_allocs;
  75. extern Py_ssize_t quick_int_allocs, quick_neg_int_allocs;
  76. extern Py_ssize_t null_strings, one_strings;
  77. void
  78. dump_counts(FILE* f)
  79. {
  80. PyTypeObject *tp;
  81. for (tp = type_list; tp; tp = tp->tp_next)
  82. fprintf(f, "%s alloc'd: %" PY_FORMAT_SIZE_T "d, "
  83. "freed: %" PY_FORMAT_SIZE_T "d, "
  84. "max in use: %" PY_FORMAT_SIZE_T "d\n",
  85. tp->tp_name, tp->tp_allocs, tp->tp_frees,
  86. tp->tp_maxalloc);
  87. fprintf(f, "fast tuple allocs: %" PY_FORMAT_SIZE_T "d, "
  88. "empty: %" PY_FORMAT_SIZE_T "d\n",
  89. fast_tuple_allocs, tuple_zero_allocs);
  90. fprintf(f, "fast int allocs: pos: %" PY_FORMAT_SIZE_T "d, "
  91. "neg: %" PY_FORMAT_SIZE_T "d\n",
  92. quick_int_allocs, quick_neg_int_allocs);
  93. fprintf(f, "null strings: %" PY_FORMAT_SIZE_T "d, "
  94. "1-strings: %" PY_FORMAT_SIZE_T "d\n",
  95. null_strings, one_strings);
  96. }
  97. PyObject *
  98. get_counts(void)
  99. {
  100. PyTypeObject *tp;
  101. PyObject *result;
  102. PyObject *v;
  103. result = PyList_New(0);
  104. if (result == NULL)
  105. return NULL;
  106. for (tp = type_list; tp; tp = tp->tp_next) {
  107. v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs,
  108. tp->tp_frees, tp->tp_maxalloc);
  109. if (v == NULL) {
  110. Py_DECREF(result);
  111. return NULL;
  112. }
  113. if (PyList_Append(result, v) < 0) {
  114. Py_DECREF(v);
  115. Py_DECREF(result);
  116. return NULL;
  117. }
  118. Py_DECREF(v);
  119. }
  120. return result;
  121. }
  122. void
  123. inc_count(PyTypeObject *tp)
  124. {
  125. if (tp->tp_next == NULL && tp->tp_prev == NULL) {
  126. /* first time; insert in linked list */
  127. if (tp->tp_next != NULL) /* sanity check */
  128. Py_FatalError("XXX inc_count sanity check");
  129. if (type_list)
  130. type_list->tp_prev = tp;
  131. tp->tp_next = type_list;
  132. /* Note that as of Python 2.2, heap-allocated type objects
  133. * can go away, but this code requires that they stay alive
  134. * until program exit. That's why we're careful with
  135. * refcounts here. type_list gets a new reference to tp,
  136. * while ownership of the reference type_list used to hold
  137. * (if any) was transferred to tp->tp_next in the line above.
  138. * tp is thus effectively immortal after this.
  139. */
  140. Py_INCREF(tp);
  141. type_list = tp;
  142. #ifdef Py_TRACE_REFS
  143. /* Also insert in the doubly-linked list of all objects,
  144. * if not already there.
  145. */
  146. _Py_AddToAllObjects((PyObject *)tp, 0);
  147. #endif
  148. }
  149. tp->tp_allocs++;
  150. if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
  151. tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
  152. }
  153. void dec_count(PyTypeObject *tp)
  154. {
  155. tp->tp_frees++;
  156. if (unlist_types_without_objects &&
  157. tp->tp_allocs == tp->tp_frees) {
  158. /* unlink the type from type_list */
  159. if (tp->tp_prev)
  160. tp->tp_prev->tp_next = tp->tp_next;
  161. else
  162. type_list = tp->tp_next;
  163. if (tp->tp_next)
  164. tp->tp_next->tp_prev = tp->tp_prev;
  165. tp->tp_next = tp->tp_prev = NULL;
  166. Py_DECREF(tp);
  167. }
  168. }
  169. #endif
  170. #ifdef Py_REF_DEBUG
  171. /* Log a fatal error; doesn't return. */
  172. void
  173. _Py_NegativeRefcount(const char *fname, int lineno, PyObject *op)
  174. {
  175. char buf[300];
  176. PyOS_snprintf(buf, sizeof(buf),
  177. "%s:%i object at %p has negative ref count "
  178. "%" PY_FORMAT_SIZE_T "d",
  179. fname, lineno, op, op->ob_refcnt);
  180. Py_FatalError(buf);
  181. }
  182. #endif /* Py_REF_DEBUG */
  183. void
  184. Py_IncRef(PyObject *o)
  185. {
  186. Py_XINCREF(o);
  187. }
  188. void
  189. Py_DecRef(PyObject *o)
  190. {
  191. Py_XDECREF(o);
  192. }
  193. PyObject *
  194. PyObject_Init(PyObject *op, PyTypeObject *tp)
  195. {
  196. if (op == NULL)
  197. return PyErr_NoMemory();
  198. /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
  199. Py_TYPE(op) = tp;
  200. _Py_NewReference(op);
  201. return op;
  202. }
  203. PyVarObject *
  204. PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
  205. {
  206. if (op == NULL)
  207. return (PyVarObject *) PyErr_NoMemory();
  208. /* Any changes should be reflected in PyObject_INIT_VAR */
  209. op->ob_size = size;
  210. Py_TYPE(op) = tp;
  211. _Py_NewReference((PyObject *)op);
  212. return op;
  213. }
  214. PyObject *
  215. _PyObject_New(PyTypeObject *tp)
  216. {
  217. PyObject *op;
  218. op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
  219. if (op == NULL)
  220. return PyErr_NoMemory();
  221. return PyObject_INIT(op, tp);
  222. }
  223. PyVarObject *
  224. _PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
  225. {
  226. PyVarObject *op;
  227. const size_t size = _PyObject_VAR_SIZE(tp, nitems);
  228. op = (PyVarObject *) PyObject_MALLOC(size);
  229. if (op == NULL)
  230. return (PyVarObject *)PyErr_NoMemory();
  231. return PyObject_INIT_VAR(op, tp, nitems);
  232. }
  233. int
  234. PyObject_Print(PyObject *op, FILE *fp, int flags)
  235. {
  236. int ret = 0;
  237. if (PyErr_CheckSignals())
  238. return -1;
  239. #ifdef USE_STACKCHECK
  240. if (PyOS_CheckStack()) {
  241. PyErr_SetString(PyExc_MemoryError, "stack overflow");
  242. return -1;
  243. }
  244. #endif
  245. clearerr(fp); /* Clear any previous error condition */
  246. if (op == NULL) {
  247. Py_BEGIN_ALLOW_THREADS
  248. fprintf(fp, "<nil>");
  249. Py_END_ALLOW_THREADS
  250. }
  251. else {
  252. if (op->ob_refcnt <= 0)
  253. /* XXX(twouters) cast refcount to long until %zd is
  254. universally available */
  255. Py_BEGIN_ALLOW_THREADS
  256. fprintf(fp, "<refcnt %ld at %p>",
  257. (long)op->ob_refcnt, op);
  258. Py_END_ALLOW_THREADS
  259. else {
  260. PyObject *s;
  261. if (flags & Py_PRINT_RAW)
  262. s = PyObject_Str(op);
  263. else
  264. s = PyObject_Repr(op);
  265. if (s == NULL)
  266. ret = -1;
  267. else if (PyBytes_Check(s)) {
  268. fwrite(PyBytes_AS_STRING(s), 1,
  269. PyBytes_GET_SIZE(s), fp);
  270. }
  271. else if (PyUnicode_Check(s)) {
  272. PyObject *t;
  273. t = PyUnicode_AsEncodedString(s, "utf-8", "backslashreplace");
  274. if (t == NULL)
  275. ret = 0;
  276. else {
  277. fwrite(PyBytes_AS_STRING(t), 1,
  278. PyBytes_GET_SIZE(t), fp);
  279. Py_DECREF(t);
  280. }
  281. }
  282. else {
  283. PyErr_Format(PyExc_TypeError,
  284. "str() or repr() returned '%.100s'",
  285. s->ob_type->tp_name);
  286. ret = -1;
  287. }
  288. Py_XDECREF(s);
  289. }
  290. }
  291. if (ret == 0) {
  292. if (ferror(fp)) {
  293. PyErr_SetFromErrno(PyExc_IOError);
  294. clearerr(fp);
  295. ret = -1;
  296. }
  297. }
  298. return ret;
  299. }
  300. /* For debugging convenience. Set a breakpoint here and call it from your DLL */
  301. void
  302. _Py_BreakPoint(void)
  303. {
  304. }
  305. /* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
  306. void
  307. _PyObject_Dump(PyObject* op)
  308. {
  309. if (op == NULL)
  310. fprintf(stderr, "NULL\n");
  311. else {
  312. #ifdef WITH_THREAD
  313. PyGILState_STATE gil;
  314. #endif
  315. fprintf(stderr, "object : ");
  316. #ifdef WITH_THREAD
  317. gil = PyGILState_Ensure();
  318. #endif
  319. (void)PyObject_Print(op, stderr, 0);
  320. #ifdef WITH_THREAD
  321. PyGILState_Release(gil);
  322. #endif
  323. /* XXX(twouters) cast refcount to long until %zd is
  324. universally available */
  325. fprintf(stderr, "\n"
  326. "type : %s\n"
  327. "refcount: %ld\n"
  328. "address : %p\n",
  329. Py_TYPE(op)==NULL ? "NULL" : Py_TYPE(op)->tp_name,
  330. (long)op->ob_refcnt,
  331. op);
  332. }
  333. }
  334. PyObject *
  335. PyObject_Repr(PyObject *v)
  336. {
  337. PyObject *res;
  338. if (PyErr_CheckSignals())
  339. return NULL;
  340. #ifdef USE_STACKCHECK
  341. if (PyOS_CheckStack()) {
  342. PyErr_SetString(PyExc_MemoryError, "stack overflow");
  343. return NULL;
  344. }
  345. #endif
  346. if (v == NULL)
  347. return PyUnicode_FromString("<NULL>");
  348. if (Py_TYPE(v)->tp_repr == NULL)
  349. return PyUnicode_FromFormat("<%s object at %p>",
  350. v->ob_type->tp_name, v);
  351. res = (*v->ob_type->tp_repr)(v);
  352. if (res == NULL)
  353. return NULL;
  354. if (!PyUnicode_Check(res)) {
  355. PyErr_Format(PyExc_TypeError,
  356. "__repr__ returned non-string (type %.200s)",
  357. res->ob_type->tp_name);
  358. Py_DECREF(res);
  359. return NULL;
  360. }
  361. #ifndef Py_DEBUG
  362. if (PyUnicode_READY(res) < 0)
  363. return NULL;
  364. #endif
  365. return res;
  366. }
  367. PyObject *
  368. PyObject_Str(PyObject *v)
  369. {
  370. PyObject *res;
  371. if (PyErr_CheckSignals())
  372. return NULL;
  373. #ifdef USE_STACKCHECK
  374. if (PyOS_CheckStack()) {
  375. PyErr_SetString(PyExc_MemoryError, "stack overflow");
  376. return NULL;
  377. }
  378. #endif
  379. if (v == NULL)
  380. return PyUnicode_FromString("<NULL>");
  381. if (PyUnicode_CheckExact(v)) {
  382. #ifndef Py_DEBUG
  383. if (PyUnicode_READY(v) < 0)
  384. return NULL;
  385. #endif
  386. Py_INCREF(v);
  387. return v;
  388. }
  389. if (Py_TYPE(v)->tp_str == NULL)
  390. return PyObject_Repr(v);
  391. /* It is possible for a type to have a tp_str representation that loops
  392. infinitely. */
  393. if (Py_EnterRecursiveCall(" while getting the str of an object"))
  394. return NULL;
  395. res = (*Py_TYPE(v)->tp_str)(v);
  396. Py_LeaveRecursiveCall();
  397. if (res == NULL)
  398. return NULL;
  399. if (!PyUnicode_Check(res)) {
  400. PyErr_Format(PyExc_TypeError,
  401. "__str__ returned non-string (type %.200s)",
  402. Py_TYPE(res)->tp_name);
  403. Py_DECREF(res);
  404. return NULL;
  405. }
  406. #ifndef Py_DEBUG
  407. if (PyUnicode_READY(res) < 0)
  408. return NULL;
  409. #endif
  410. assert(_PyUnicode_CheckConsistency(res, 1));
  411. return res;
  412. }
  413. PyObject *
  414. PyObject_ASCII(PyObject *v)
  415. {
  416. PyObject *repr, *ascii, *res;
  417. repr = PyObject_Repr(v);
  418. if (repr == NULL)
  419. return NULL;
  420. /* repr is guaranteed to be a PyUnicode object by PyObject_Repr */
  421. ascii = _PyUnicode_AsASCIIString(repr, "backslashreplace");
  422. Py_DECREF(repr);
  423. if (ascii == NULL)
  424. return NULL;
  425. res = PyUnicode_DecodeASCII(
  426. PyBytes_AS_STRING(ascii),
  427. PyBytes_GET_SIZE(ascii),
  428. NULL);
  429. Py_DECREF(ascii);
  430. return res;
  431. }
  432. PyObject *
  433. PyObject_Bytes(PyObject *v)
  434. {
  435. PyObject *result, *func;
  436. _Py_IDENTIFIER(__bytes__);
  437. if (v == NULL)
  438. return PyBytes_FromString("<NULL>");
  439. if (PyBytes_CheckExact(v)) {
  440. Py_INCREF(v);
  441. return v;
  442. }
  443. func = _PyObject_LookupSpecial(v, &PyId___bytes__);
  444. if (func != NULL) {
  445. result = PyObject_CallFunctionObjArgs(func, NULL);
  446. Py_DECREF(func);
  447. if (result == NULL)
  448. return NULL;
  449. if (!PyBytes_Check(result)) {
  450. PyErr_Format(PyExc_TypeError,
  451. "__bytes__ returned non-bytes (type %.200s)",
  452. Py_TYPE(result)->tp_name);
  453. Py_DECREF(result);
  454. return NULL;
  455. }
  456. return result;
  457. }
  458. else if (PyErr_Occurred())
  459. return NULL;
  460. return PyBytes_FromObject(v);
  461. }
  462. /* For Python 3.0.1 and later, the old three-way comparison has been
  463. completely removed in favour of rich comparisons. PyObject_Compare() and
  464. PyObject_Cmp() are gone, and the builtin cmp function no longer exists.
  465. The old tp_compare slot has been renamed to tp_reserved, and should no
  466. longer be used. Use tp_richcompare instead.
  467. See (*) below for practical amendments.
  468. tp_richcompare gets called with a first argument of the appropriate type
  469. and a second object of an arbitrary type. We never do any kind of
  470. coercion.
  471. The tp_richcompare slot should return an object, as follows:
  472. NULL if an exception occurred
  473. NotImplemented if the requested comparison is not implemented
  474. any other false value if the requested comparison is false
  475. any other true value if the requested comparison is true
  476. The PyObject_RichCompare[Bool]() wrappers raise TypeError when they get
  477. NotImplemented.
  478. (*) Practical amendments:
  479. - If rich comparison returns NotImplemented, == and != are decided by
  480. comparing the object pointer (i.e. falling back to the base object
  481. implementation).
  482. */
  483. /* Map rich comparison operators to their swapped version, e.g. LT <--> GT */
  484. int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
  485. static char *opstrings[] = {"<", "<=", "==", "!=", ">", ">="};
  486. /* Perform a rich comparison, raising TypeError when the requested comparison
  487. operator is not supported. */
  488. static PyObject *
  489. do_richcompare(PyObject *v, PyObject *w, int op)
  490. {
  491. richcmpfunc f;
  492. PyObject *res;
  493. int checked_reverse_op = 0;
  494. if (v->ob_type != w->ob_type &&
  495. PyType_IsSubtype(w->ob_type, v->ob_type) &&
  496. (f = w->ob_type->tp_richcompare) != NULL) {
  497. checked_reverse_op = 1;
  498. res = (*f)(w, v, _Py_SwappedOp[op]);
  499. if (res != Py_NotImplemented)
  500. return res;
  501. Py_DECREF(res);
  502. }
  503. if ((f = v->ob_type->tp_richcompare) != NULL) {
  504. res = (*f)(v, w, op);
  505. if (res != Py_NotImplemented)
  506. return res;
  507. Py_DECREF(res);
  508. }
  509. if (!checked_reverse_op && (f = w->ob_type->tp_richcompare) != NULL) {
  510. res = (*f)(w, v, _Py_SwappedOp[op]);
  511. if (res != Py_NotImplemented)
  512. return res;
  513. Py_DECREF(res);
  514. }
  515. /* If neither object implements it, provide a sensible default
  516. for == and !=, but raise an exception for ordering. */
  517. switch (op) {
  518. case Py_EQ:
  519. res = (v == w) ? Py_True : Py_False;
  520. break;
  521. case Py_NE:
  522. res = (v != w) ? Py_True : Py_False;
  523. break;
  524. default:
  525. /* XXX Special-case None so it doesn't show as NoneType() */
  526. PyErr_Format(PyExc_TypeError,
  527. "unorderable types: %.100s() %s %.100s()",
  528. v->ob_type->tp_name,
  529. opstrings[op],
  530. w->ob_type->tp_name);
  531. return NULL;
  532. }
  533. Py_INCREF(res);
  534. return res;
  535. }
  536. /* Perform a rich comparison with object result. This wraps do_richcompare()
  537. with a check for NULL arguments and a recursion check. */
  538. PyObject *
  539. PyObject_RichCompare(PyObject *v, PyObject *w, int op)
  540. {
  541. PyObject *res;
  542. assert(Py_LT <= op && op <= Py_GE);
  543. if (v == NULL || w == NULL) {
  544. if (!PyErr_Occurred())
  545. PyErr_BadInternalCall();
  546. return NULL;
  547. }
  548. if (Py_EnterRecursiveCall(" in comparison"))
  549. return NULL;
  550. res = do_richcompare(v, w, op);
  551. Py_LeaveRecursiveCall();
  552. return res;
  553. }
  554. /* Perform a rich comparison with integer result. This wraps
  555. PyObject_RichCompare(), returning -1 for error, 0 for false, 1 for true. */
  556. int
  557. PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
  558. {
  559. PyObject *res;
  560. int ok;
  561. /* Quick result when objects are the same.
  562. Guarantees that identity implies equality. */
  563. if (v == w) {
  564. if (op == Py_EQ)
  565. return 1;
  566. else if (op == Py_NE)
  567. return 0;
  568. }
  569. res = PyObject_RichCompare(v, w, op);
  570. if (res == NULL)
  571. return -1;
  572. if (PyBool_Check(res))
  573. ok = (res == Py_True);
  574. else
  575. ok = PyObject_IsTrue(res);
  576. Py_DECREF(res);
  577. return ok;
  578. }
  579. /* Set of hash utility functions to help maintaining the invariant that
  580. if a==b then hash(a)==hash(b)
  581. All the utility functions (_Py_Hash*()) return "-1" to signify an error.
  582. */
  583. /* For numeric types, the hash of a number x is based on the reduction
  584. of x modulo the prime P = 2**_PyHASH_BITS - 1. It's designed so that
  585. hash(x) == hash(y) whenever x and y are numerically equal, even if
  586. x and y have different types.
  587. A quick summary of the hashing strategy:
  588. (1) First define the 'reduction of x modulo P' for any rational
  589. number x; this is a standard extension of the usual notion of
  590. reduction modulo P for integers. If x == p/q (written in lowest
  591. terms), the reduction is interpreted as the reduction of p times
  592. the inverse of the reduction of q, all modulo P; if q is exactly
  593. divisible by P then define the reduction to be infinity. So we've
  594. got a well-defined map
  595. reduce : { rational numbers } -> { 0, 1, 2, ..., P-1, infinity }.
  596. (2) Now for a rational number x, define hash(x) by:
  597. reduce(x) if x >= 0
  598. -reduce(-x) if x < 0
  599. If the result of the reduction is infinity (this is impossible for
  600. integers, floats and Decimals) then use the predefined hash value
  601. _PyHASH_INF for x >= 0, or -_PyHASH_INF for x < 0, instead.
  602. _PyHASH_INF, -_PyHASH_INF and _PyHASH_NAN are also used for the
  603. hashes of float and Decimal infinities and nans.
  604. A selling point for the above strategy is that it makes it possible
  605. to compute hashes of decimal and binary floating-point numbers
  606. efficiently, even if the exponent of the binary or decimal number
  607. is large. The key point is that
  608. reduce(x * y) == reduce(x) * reduce(y) (modulo _PyHASH_MODULUS)
  609. provided that {reduce(x), reduce(y)} != {0, infinity}. The reduction of a
  610. binary or decimal float is never infinity, since the denominator is a power
  611. of 2 (for binary) or a divisor of a power of 10 (for decimal). So we have,
  612. for nonnegative x,
  613. reduce(x * 2**e) == reduce(x) * reduce(2**e) % _PyHASH_MODULUS
  614. reduce(x * 10**e) == reduce(x) * reduce(10**e) % _PyHASH_MODULUS
  615. and reduce(10**e) can be computed efficiently by the usual modular
  616. exponentiation algorithm. For reduce(2**e) it's even better: since
  617. P is of the form 2**n-1, reduce(2**e) is 2**(e mod n), and multiplication
  618. by 2**(e mod n) modulo 2**n-1 just amounts to a rotation of bits.
  619. */
  620. Py_hash_t
  621. _Py_HashDouble(double v)
  622. {
  623. int e, sign;
  624. double m;
  625. Py_uhash_t x, y;
  626. if (!Py_IS_FINITE(v)) {
  627. if (Py_IS_INFINITY(v))
  628. return v > 0 ? _PyHASH_INF : -_PyHASH_INF;
  629. else
  630. return _PyHASH_NAN;
  631. }
  632. m = frexp(v, &e);
  633. sign = 1;
  634. if (m < 0) {
  635. sign = -1;
  636. m = -m;
  637. }
  638. /* process 28 bits at a time; this should work well both for binary
  639. and hexadecimal floating point. */
  640. x = 0;
  641. while (m) {
  642. x = ((x << 28) & _PyHASH_MODULUS) | x >> (_PyHASH_BITS - 28);
  643. m *= 268435456.0; /* 2**28 */
  644. e -= 28;
  645. y = (Py_uhash_t)m; /* pull out integer part */
  646. m -= y;
  647. x += y;
  648. if (x >= _PyHASH_MODULUS)
  649. x -= _PyHASH_MODULUS;
  650. }
  651. /* adjust for the exponent; first reduce it modulo _PyHASH_BITS */
  652. e = e >= 0 ? e % _PyHASH_BITS : _PyHASH_BITS-1-((-1-e) % _PyHASH_BITS);
  653. x = ((x << e) & _PyHASH_MODULUS) | x >> (_PyHASH_BITS - e);
  654. x = x * sign;
  655. if (x == (Py_uhash_t)-1)
  656. x = (Py_uhash_t)-2;
  657. return (Py_hash_t)x;
  658. }
  659. Py_hash_t
  660. _Py_HashPointer(void *p)
  661. {
  662. Py_hash_t x;
  663. size_t y = (size_t)p;
  664. /* bottom 3 or 4 bits are likely to be 0; rotate y by 4 to avoid
  665. excessive hash collisions for dicts and sets */
  666. y = (y >> 4) | (y << (8 * SIZEOF_VOID_P - 4));
  667. x = (Py_hash_t)y;
  668. if (x == -1)
  669. x = -2;
  670. return x;
  671. }
  672. Py_hash_t
  673. _Py_HashBytes(unsigned char *p, Py_ssize_t len)
  674. {
  675. Py_uhash_t x;
  676. Py_ssize_t i;
  677. /*
  678. We make the hash of the empty string be 0, rather than using
  679. (prefix ^ suffix), since this slightly obfuscates the hash secret
  680. */
  681. #ifdef Py_DEBUG
  682. assert(_Py_HashSecret_Initialized);
  683. #endif
  684. if (len == 0) {
  685. return 0;
  686. }
  687. x = (Py_uhash_t) _Py_HashSecret.prefix;
  688. x ^= (Py_uhash_t) *p << 7;
  689. for (i = 0; i < len; i++)
  690. x = (_PyHASH_MULTIPLIER * x) ^ (Py_uhash_t) *p++;
  691. x ^= (Py_uhash_t) len;
  692. x ^= (Py_uhash_t) _Py_HashSecret.suffix;
  693. if (x == -1)
  694. x = -2;
  695. return x;
  696. }
  697. Py_hash_t
  698. PyObject_HashNotImplemented(PyObject *v)
  699. {
  700. PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
  701. Py_TYPE(v)->tp_name);
  702. return -1;
  703. }
  704. _Py_HashSecret_t _Py_HashSecret;
  705. Py_hash_t
  706. PyObject_Hash(PyObject *v)
  707. {
  708. PyTypeObject *tp = Py_TYPE(v);
  709. if (tp->tp_hash != NULL)
  710. return (*tp->tp_hash)(v);
  711. /* To keep to the general practice that inheriting
  712. * solely from object in C code should work without
  713. * an explicit call to PyType_Ready, we implicitly call
  714. * PyType_Ready here and then check the tp_hash slot again
  715. */
  716. if (tp->tp_dict == NULL) {
  717. if (PyType_Ready(tp) < 0)
  718. return -1;
  719. if (tp->tp_hash != NULL)
  720. return (*tp->tp_hash)(v);
  721. }
  722. /* Otherwise, the object can't be hashed */
  723. return PyObject_HashNotImplemented(v);
  724. }
  725. PyObject *
  726. PyObject_GetAttrString(PyObject *v, const char *name)
  727. {
  728. PyObject *w, *res;
  729. if (Py_TYPE(v)->tp_getattr != NULL)
  730. return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
  731. w = PyUnicode_InternFromString(name);
  732. if (w == NULL)
  733. return NULL;
  734. res = PyObject_GetAttr(v, w);
  735. Py_DECREF(w);
  736. return res;
  737. }
  738. int
  739. PyObject_HasAttrString(PyObject *v, const char *name)
  740. {
  741. PyObject *res = PyObject_GetAttrString(v, name);
  742. if (res != NULL) {
  743. Py_DECREF(res);
  744. return 1;
  745. }
  746. PyErr_Clear();
  747. return 0;
  748. }
  749. int
  750. PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
  751. {
  752. PyObject *s;
  753. int res;
  754. if (Py_TYPE(v)->tp_setattr != NULL)
  755. return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
  756. s = PyUnicode_InternFromString(name);
  757. if (s == NULL)
  758. return -1;
  759. res = PyObject_SetAttr(v, s, w);
  760. Py_XDECREF(s);
  761. return res;
  762. }
  763. int
  764. _PyObject_IsAbstract(PyObject *obj)
  765. {
  766. int res;
  767. PyObject* isabstract;
  768. _Py_IDENTIFIER(__isabstractmethod__);
  769. if (obj == NULL)
  770. return 0;
  771. isabstract = _PyObject_GetAttrId(obj, &PyId___isabstractmethod__);
  772. if (isabstract == NULL) {
  773. if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
  774. PyErr_Clear();
  775. return 0;
  776. }
  777. return -1;
  778. }
  779. res = PyObject_IsTrue(isabstract);
  780. Py_DECREF(isabstract);
  781. return res;
  782. }
  783. PyObject *
  784. _PyObject_GetAttrId(PyObject *v, _Py_Identifier *name)
  785. {
  786. PyObject *result;
  787. PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
  788. if (!oname)
  789. return NULL;
  790. result = PyObject_GetAttr(v, oname);
  791. return result;
  792. }
  793. int
  794. _PyObject_HasAttrId(PyObject *v, _Py_Identifier *name)
  795. {
  796. int result;
  797. PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
  798. if (!oname)
  799. return -1;
  800. result = PyObject_HasAttr(v, oname);
  801. return result;
  802. }
  803. int
  804. _PyObject_SetAttrId(PyObject *v, _Py_Identifier *name, PyObject *w)
  805. {
  806. int result;
  807. PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
  808. if (!oname)
  809. return -1;
  810. result = PyObject_SetAttr(v, oname, w);
  811. return result;
  812. }
  813. PyObject *
  814. PyObject_GetAttr(PyObject *v, PyObject *name)
  815. {
  816. PyTypeObject *tp = Py_TYPE(v);
  817. if (!PyUnicode_Check(name)) {
  818. PyErr_Format(PyExc_TypeError,
  819. "attribute name must be string, not '%.200s'",
  820. name->ob_type->tp_name);
  821. return NULL;
  822. }
  823. if (tp->tp_getattro != NULL)
  824. return (*tp->tp_getattro)(v, name);
  825. if (tp->tp_getattr != NULL) {
  826. char *name_str = _PyUnicode_AsString(name);
  827. if (name_str == NULL)
  828. return NULL;
  829. return (*tp->tp_getattr)(v, name_str);
  830. }
  831. PyErr_Format(PyExc_AttributeError,
  832. "'%.50s' object has no attribute '%U'",
  833. tp->tp_name, name);
  834. return NULL;
  835. }
  836. int
  837. PyObject_HasAttr(PyObject *v, PyObject *name)
  838. {
  839. PyObject *res = PyObject_GetAttr(v, name);
  840. if (res != NULL) {
  841. Py_DECREF(res);
  842. return 1;
  843. }
  844. PyErr_Clear();
  845. return 0;
  846. }
  847. int
  848. PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
  849. {
  850. PyTypeObject *tp = Py_TYPE(v);
  851. int err;
  852. if (!PyUnicode_Check(name)) {
  853. PyErr_Format(PyExc_TypeError,
  854. "attribute name must be string, not '%.200s'",
  855. name->ob_type->tp_name);
  856. return -1;
  857. }
  858. Py_INCREF(name);
  859. PyUnicode_InternInPlace(&name);
  860. if (tp->tp_setattro != NULL) {
  861. err = (*tp->tp_setattro)(v, name, value);
  862. Py_DECREF(name);
  863. return err;
  864. }
  865. if (tp->tp_setattr != NULL) {
  866. char *name_str = _PyUnicode_AsString(name);
  867. if (name_str == NULL)
  868. return -1;
  869. err = (*tp->tp_setattr)(v, name_str, value);
  870. Py_DECREF(name);
  871. return err;
  872. }
  873. Py_DECREF(name);
  874. assert(name->ob_refcnt >= 1);
  875. if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
  876. PyErr_Format(PyExc_TypeError,
  877. "'%.100s' object has no attributes "
  878. "(%s .%U)",
  879. tp->tp_name,
  880. value==NULL ? "del" : "assign to",
  881. name);
  882. else
  883. PyErr_Format(PyExc_TypeError,
  884. "'%.100s' object has only read-only attributes "
  885. "(%s .%U)",
  886. tp->tp_name,
  887. value==NULL ? "del" : "assign to",
  888. name);
  889. return -1;
  890. }
  891. /* Helper to get a pointer to an object's __dict__ slot, if any */
  892. PyObject **
  893. _PyObject_GetDictPtr(PyObject *obj)
  894. {
  895. Py_ssize_t dictoffset;
  896. PyTypeObject *tp = Py_TYPE(obj);
  897. dictoffset = tp->tp_dictoffset;
  898. if (dictoffset == 0)
  899. return NULL;
  900. if (dictoffset < 0) {
  901. Py_ssize_t tsize;
  902. size_t size;
  903. tsize = ((PyVarObject *)obj)->ob_size;
  904. if (tsize < 0)
  905. tsize = -tsize;
  906. size = _PyObject_VAR_SIZE(tp, tsize);
  907. dictoffset += (long)size;
  908. assert(dictoffset > 0);
  909. assert(dictoffset % SIZEOF_VOID_P == 0);
  910. }
  911. return (PyObject **) ((char *)obj + dictoffset);
  912. }
  913. PyObject *
  914. PyObject_SelfIter(PyObject *obj)
  915. {
  916. Py_INCREF(obj);
  917. return obj;
  918. }
  919. /* Convenience function to get a builtin from its name */
  920. PyObject *
  921. _PyObject_GetBuiltin(const char *name)
  922. {
  923. PyObject *mod, *attr;
  924. mod = PyImport_ImportModule("builtins");
  925. if (mod == NULL)
  926. return NULL;
  927. attr = PyObject_GetAttrString(mod, name);
  928. Py_DECREF(mod);
  929. return attr;
  930. }
  931. /* Helper used when the __next__ method is removed from a type:
  932. tp_iternext is never NULL and can be safely called without checking
  933. on every iteration.
  934. */
  935. PyObject *
  936. _PyObject_NextNotImplemented(PyObject *self)
  937. {
  938. PyErr_Format(PyExc_TypeError,
  939. "'%.200s' object is not iterable",
  940. Py_TYPE(self)->tp_name);
  941. return NULL;
  942. }
  943. /* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
  944. PyObject *
  945. _PyObject_GenericGetAttrWithDict(PyObject *obj, PyObject *name, PyObject *dict)
  946. {
  947. PyTypeObject *tp = Py_TYPE(obj);
  948. PyObject *descr = NULL;
  949. PyObject *res = NULL;
  950. descrgetfunc f;
  951. Py_ssize_t dictoffset;
  952. PyObject **dictptr;
  953. if (!PyUnicode_Check(name)){
  954. PyErr_Format(PyExc_TypeError,
  955. "attribute name must be string, not '%.200s'",
  956. name->ob_type->tp_name);
  957. return NULL;
  958. }
  959. else
  960. Py_INCREF(name);
  961. if (tp->tp_dict == NULL) {
  962. if (PyType_Ready(tp) < 0)
  963. goto done;
  964. }
  965. descr = _PyType_Lookup(tp, name);
  966. Py_XINCREF(descr);
  967. f = NULL;
  968. if (descr != NULL) {
  969. f = descr->ob_type->tp_descr_get;
  970. if (f != NULL && PyDescr_IsData(descr)) {
  971. res = f(descr, obj, (PyObject *)obj->ob_type);
  972. goto done;
  973. }
  974. }
  975. if (dict == NULL) {
  976. /* Inline _PyObject_GetDictPtr */
  977. dictoffset = tp->tp_dictoffset;
  978. if (dictoffset != 0) {
  979. if (dictoffset < 0) {
  980. Py_ssize_t tsize;
  981. size_t size;
  982. tsize = ((PyVarObject *)obj)->ob_size;
  983. if (tsize < 0)
  984. tsize = -tsize;
  985. size = _PyObject_VAR_SIZE(tp, tsize);
  986. dictoffset += (long)size;
  987. assert(dictoffset > 0);
  988. assert(dictoffset % SIZEOF_VOID_P == 0);
  989. }
  990. dictptr = (PyObject **) ((char *)obj + dictoffset);
  991. dict = *dictptr;
  992. }
  993. }
  994. if (dict != NULL) {
  995. Py_INCREF(dict);
  996. res = PyDict_GetItem(dict, name);
  997. if (res != NULL) {
  998. Py_INCREF(res);
  999. Py_DECREF(dict);
  1000. goto done;
  1001. }
  1002. Py_DECREF(dict);
  1003. }
  1004. if (f != NULL) {
  1005. res = f(descr, obj, (PyObject *)Py_TYPE(obj));
  1006. goto done;
  1007. }
  1008. if (descr != NULL) {
  1009. res = descr;
  1010. descr = NULL;
  1011. goto done;
  1012. }
  1013. PyErr_Format(PyExc_AttributeError,
  1014. "'%.50s' object has no attribute '%U'",
  1015. tp->tp_name, name);
  1016. done:
  1017. Py_XDECREF(descr);
  1018. Py_DECREF(name);
  1019. return res;
  1020. }
  1021. PyObject *
  1022. PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
  1023. {
  1024. return _PyObject_GenericGetAttrWithDict(obj, name, NULL);
  1025. }
  1026. int
  1027. _PyObject_GenericSetAttrWithDict(PyObject *obj, PyObject *name,
  1028. PyObject *value, PyObject *dict)
  1029. {
  1030. PyTypeObject *tp = Py_TYPE(obj);
  1031. PyObject *descr;
  1032. descrsetfunc f;
  1033. PyObject **dictptr;
  1034. int res = -1;
  1035. if (!PyUnicode_Check(name)){
  1036. PyErr_Format(PyExc_TypeError,
  1037. "attribute name must be string, not '%.200s'",
  1038. name->ob_type->tp_name);
  1039. return -1;
  1040. }
  1041. if (tp->tp_dict == NULL && PyType_Ready(tp) < 0)
  1042. return -1;
  1043. Py_INCREF(name);
  1044. descr = _PyType_Lookup(tp, name);
  1045. Py_XINCREF(descr);
  1046. f = NULL;
  1047. if (descr != NULL) {
  1048. f = descr->ob_type->tp_descr_set;
  1049. if (f != NULL && PyDescr_IsData(descr)) {
  1050. res = f(descr, obj, value);
  1051. goto done;
  1052. }
  1053. }
  1054. if (dict == NULL) {
  1055. dictptr = _PyObject_GetDictPtr(obj);
  1056. if (dictptr != NULL) {
  1057. res = _PyObjectDict_SetItem(Py_TYPE(obj), dictptr, name, value);
  1058. if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
  1059. PyErr_SetObject(PyExc_AttributeError, name);
  1060. goto done;
  1061. }
  1062. }
  1063. if (dict != NULL) {
  1064. Py_INCREF(dict);
  1065. if (value == NULL)
  1066. res = PyDict_DelItem(dict, name);
  1067. else
  1068. res = PyDict_SetItem(dict, name, value);
  1069. Py_DECREF(dict);
  1070. if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
  1071. PyErr_SetObject(PyExc_AttributeError, name);
  1072. goto done;
  1073. }
  1074. if (f != NULL) {
  1075. res = f(descr, obj, value);
  1076. goto done;
  1077. }
  1078. if (descr == NULL) {
  1079. PyErr_Format(PyExc_AttributeError,
  1080. "'%.100s' object has no attribute '%U'",
  1081. tp->tp_name, name);
  1082. goto done;
  1083. }
  1084. PyErr_Format(PyExc_AttributeError,
  1085. "'%.50s' object attribute '%U' is read-only",
  1086. tp->tp_name, name);
  1087. done:
  1088. Py_XDECREF(descr);
  1089. Py_DECREF(name);
  1090. return res;
  1091. }
  1092. int
  1093. PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
  1094. {
  1095. return _PyObject_GenericSetAttrWithDict(obj, name, value, NULL);
  1096. }
  1097. int
  1098. PyObject_GenericSetDict(PyObject *obj, PyObject *value, void *context)
  1099. {
  1100. PyObject *dict, **dictptr = _PyObject_GetDictPtr(obj);
  1101. if (dictptr == NULL) {
  1102. PyErr_SetString(PyExc_AttributeError,
  1103. "This object has no __dict__");
  1104. return -1;
  1105. }
  1106. if (value == NULL) {
  1107. PyErr_SetString(PyExc_TypeError, "cannot delete __dict__");
  1108. return -1;
  1109. }
  1110. if (!PyDict_Check(value)) {
  1111. PyErr_Format(PyExc_TypeError,
  1112. "__dict__ must be set to a dictionary, "
  1113. "not a '%.200s'", Py_TYPE(value)->tp_name);
  1114. return -1;
  1115. }
  1116. dict = *dictptr;
  1117. Py_XINCREF(value);
  1118. *dictptr = value;
  1119. Py_XDECREF(dict);
  1120. return 0;
  1121. }
  1122. /* Test a value used as condition, e.g., in a for or if statement.
  1123. Return -1 if an error occurred */
  1124. int
  1125. PyObject_IsTrue(PyObject *v)
  1126. {
  1127. Py_ssize_t res;
  1128. if (v == Py_True)
  1129. return 1;
  1130. if (v == Py_False)
  1131. return 0;
  1132. if (v == Py_None)
  1133. return 0;
  1134. else if (v->ob_type->tp_as_number != NULL &&
  1135. v->ob_type->tp_as_number->nb_bool != NULL)
  1136. res = (*v->ob_type->tp_as_number->nb_bool)(v);
  1137. else if (v->ob_type->tp_as_mapping != NULL &&
  1138. v->ob_type->tp_as_mapping->mp_length != NULL)
  1139. res = (*v->ob_type->tp_as_mapping->mp_length)(v);
  1140. else if (v->ob_type->tp_as_sequence != NULL &&
  1141. v->ob_type->tp_as_sequence->sq_length != NULL)
  1142. res = (*v->ob_type->tp_as_sequence->sq_length)(v);
  1143. else
  1144. return 1;
  1145. /* if it is negative, it should be either -1 or -2 */
  1146. return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
  1147. }
  1148. /* equivalent of 'not v'
  1149. Return -1 if an error occurred */
  1150. int
  1151. PyObject_Not(PyObject *v)
  1152. {
  1153. int res;
  1154. res = PyObject_IsTrue(v);
  1155. if (res < 0)
  1156. return res;
  1157. return res == 0;
  1158. }
  1159. /* Test whether an object can be called */
  1160. int
  1161. PyCallable_Check(PyObject *x)
  1162. {
  1163. if (x == NULL)
  1164. return 0;
  1165. return x->ob_type->tp_call != NULL;
  1166. }
  1167. /* Helper for PyObject_Dir without arguments: returns the local scope. */
  1168. static PyObject *
  1169. _dir_locals(void)
  1170. {
  1171. PyObject *names;
  1172. PyObject *locals = PyEval_GetLocals();
  1173. if (locals == NULL) {
  1174. PyErr_SetString(PyExc_SystemError, "frame does not exist");
  1175. return NULL;
  1176. }
  1177. names = PyMapping_Keys(locals);
  1178. if (!names)
  1179. return NULL;
  1180. if (!PyList_Check(names)) {
  1181. PyErr_Format(PyExc_TypeError,
  1182. "dir(): expected keys() of locals to be a list, "
  1183. "not '%.200s'", Py_TYPE(names)->tp_name);
  1184. Py_DECREF(names);
  1185. return NULL;
  1186. }
  1187. if (PyList_Sort(names)) {
  1188. Py_DECREF(names);
  1189. return NULL;
  1190. }
  1191. /* the locals don't need to be DECREF'd */
  1192. return names;
  1193. }
  1194. /* Helper for PyObject_Dir: object introspection. */
  1195. static PyObject *
  1196. _dir_object(PyObject *obj)
  1197. {
  1198. PyObject *result, *sorted;
  1199. _Py_IDENTIFIER(__dir__);
  1200. PyObject *dirfunc = _PyObject_LookupSpecial(obj, &PyId___dir__);
  1201. assert(obj);
  1202. if (dirfunc == NULL) {
  1203. if (!PyErr_Occurred())
  1204. PyErr_SetString(PyExc_TypeError, "object does not provide __dir__");
  1205. return NULL;
  1206. }
  1207. /* use __dir__ */
  1208. result = PyObject_CallFunctionObjArgs(dirfunc, NULL);
  1209. Py_DECREF(dirfunc);
  1210. if (result == NULL)
  1211. return NULL;
  1212. /* return sorted(result) */
  1213. sorted = PySequence_List(result);
  1214. Py_DECREF(result);
  1215. if (sorted == NULL)
  1216. return NULL;
  1217. if (PyList_Sort(sorted)) {
  1218. Py_DECREF(sorted);
  1219. return NULL;
  1220. }
  1221. return sorted;
  1222. }
  1223. /* Implementation of dir() -- if obj is NULL, returns the names in the current
  1224. (local) scope. Otherwise, performs introspection of the object: returns a
  1225. sorted list of attribute names (supposedly) accessible from the object
  1226. */
  1227. PyObject *
  1228. PyObject_Dir(PyObject *obj)
  1229. {
  1230. return (obj == NULL) ? _dir_locals() : _dir_object(obj);
  1231. }
  1232. /*
  1233. None is a non-NULL undefined value.
  1234. There is (and should be!) no way to create other objects of this type,
  1235. so there is exactly one (which is indestructible, by the way).
  1236. */
  1237. /* ARGSUSED */
  1238. static PyObject *
  1239. none_repr(PyObject *op)
  1240. {
  1241. return PyUnicode_FromString("None");
  1242. }
  1243. /* ARGUSED */
  1244. static void
  1245. none_dealloc(PyObject* ignore)
  1246. {
  1247. /* This should never get called, but we also don't want to SEGV if
  1248. * we accidentally decref None out of existence.
  1249. */
  1250. Py_FatalError("deallocating None");
  1251. }
  1252. static PyObject *
  1253. none_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
  1254. {
  1255. if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_Size(kwargs))) {
  1256. PyErr_SetString(PyExc_TypeError, "NoneType takes no arguments");
  1257. return NULL;
  1258. }
  1259. Py_RETURN_NONE;
  1260. }
  1261. static int
  1262. none_bool(PyObject *v)
  1263. {
  1264. return 0;
  1265. }
  1266. static PyNumberMethods none_as_number = {
  1267. 0, /* nb_add */
  1268. 0, /* nb_subtract */
  1269. 0, /* nb_multiply */
  1270. 0, /* nb_remainder */
  1271. 0, /* nb_divmod */
  1272. 0, /* nb_power */
  1273. 0, /* nb_negative */
  1274. 0, /* nb_positive */
  1275. 0, /* nb_absolute */
  1276. (inquiry)none_bool, /* nb_bool */
  1277. 0, /* nb_invert */
  1278. 0, /* nb_lshift */
  1279. 0, /* nb_rshift */
  1280. 0, /* nb_and */
  1281. 0, /* nb_xor */
  1282. 0, /* nb_or */
  1283. 0, /* nb_int */
  1284. 0, /* nb_reserved */
  1285. 0, /* nb_float */
  1286. 0, /* nb_inplace_add */
  1287. 0, /* nb_inplace_subtract */
  1288. 0, /* nb_inplace_multiply */
  1289. 0, /* nb_inplace_remainder */
  1290. 0, /* nb_inplace_power */
  1291. 0, /* nb_inplace_lshift */
  1292. 0, /* nb_inplace_rshift */
  1293. 0, /* nb_inplace_and */
  1294. 0, /* nb_inplace_xor */
  1295. 0, /* nb_inplace_or */
  1296. 0, /* nb_floor_divide */
  1297. 0, /* nb_true_divide */
  1298. 0, /* nb_inplace_floor_divide */
  1299. 0, /* nb_inplace_true_divide */
  1300. 0, /* nb_index */
  1301. };
  1302. static PyTypeObject PyNone_Type = {
  1303. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  1304. "NoneType",
  1305. 0,
  1306. 0,
  1307. none_dealloc, /*tp_dealloc*/ /*never called*/
  1308. 0, /*tp_print*/
  1309. 0, /*tp_getattr*/
  1310. 0, /*tp_setattr*/
  1311. 0, /*tp_reserved*/
  1312. none_repr, /*tp_repr*/
  1313. &none_as_number, /*tp_as_number*/
  1314. 0, /*tp_as_sequence*/
  1315. 0, /*tp_as_mapping*/
  1316. 0, /*tp_hash */
  1317. 0, /*tp_call */
  1318. 0, /*tp_str */
  1319. 0, /*tp_getattro */
  1320. 0, /*tp_setattro */
  1321. 0, /*tp_as_buffer */
  1322. Py_TPFLAGS_DEFAULT, /*tp_flags */
  1323. 0, /*tp_doc */
  1324. 0, /*tp_traverse */
  1325. 0, /*tp_clear */
  1326. 0, /*tp_richcompare */
  1327. 0, /*tp_weaklistoffset */
  1328. 0, /*tp_iter */
  1329. 0, /*tp_iternext */
  1330. 0, /*tp_methods */
  1331. 0, /*tp_members */
  1332. 0, /*tp_getset */
  1333. 0, /*tp_base */
  1334. 0, /*tp_dict */
  1335. 0, /*tp_descr_get */
  1336. 0, /*tp_descr_set */
  1337. 0, /*tp_dictoffset */
  1338. 0, /*tp_init */
  1339. 0, /*tp_alloc */
  1340. none_new, /*tp_new */
  1341. };
  1342. PyObject _Py_NoneStruct = {
  1343. _PyObject_EXTRA_INIT
  1344. 1, &PyNone_Type
  1345. };
  1346. /* NotImplemented is an object that can be used to signal that an
  1347. operation is not implemented for the given type combination. */
  1348. static PyObject *
  1349. NotImplemented_repr(PyObject *op)
  1350. {
  1351. return PyUnicode_FromString("NotImplemented");
  1352. }
  1353. static PyObject *
  1354. notimplemented_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
  1355. {
  1356. if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_Size(kwargs))) {
  1357. PyErr_SetString(PyExc_TypeError, "NotImplementedType takes no arguments");
  1358. return NULL;
  1359. }
  1360. Py_RETURN_NOTIMPLEMENTED;
  1361. }
  1362. static PyTypeObject PyNotImplemented_Type = {
  1363. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  1364. "NotImplementedType",
  1365. 0,
  1366. 0,
  1367. none_dealloc, /*tp_dealloc*/ /*never called*/
  1368. 0, /*tp_print*/
  1369. 0, /*tp_getattr*/
  1370. 0, /*tp_setattr*/
  1371. 0, /*tp_reserved*/
  1372. NotImplemented_repr, /*tp_repr*/
  1373. 0, /*tp_as_number*/
  1374. 0, /*tp_as_sequence*/
  1375. 0, /*tp_as_mapping*/
  1376. 0, /*tp_hash */
  1377. 0, /*tp_call */
  1378. 0, /*tp_str */
  1379. 0, /*tp_getattro */
  1380. 0, /*tp_setattro */
  1381. 0, /*tp_as_buffer */
  1382. Py_TPFLAGS_DEFAULT, /*tp_flags */
  1383. 0, /*tp_doc */
  1384. 0, /*tp_traverse */
  1385. 0, /*tp_clear */
  1386. 0, /*tp_richcompare */
  1387. 0, /*tp_weaklistoffset */
  1388. 0, /*tp_iter */
  1389. 0, /*tp_iternext */
  1390. 0, /*tp_methods */
  1391. 0, /*tp_members */
  1392. 0, /*tp_getset */
  1393. 0, /*tp_base */
  1394. 0, /*tp_dict */
  1395. 0, /*tp_descr_get */
  1396. 0, /*tp_descr_set */
  1397. 0, /*tp_dictoffset */
  1398. 0, /*tp_init */
  1399. 0, /*tp_alloc */
  1400. notimplemented_new, /*tp_new */
  1401. };
  1402. PyObject _Py_NotImplementedStruct = {
  1403. _PyObject_EXTRA_INIT
  1404. 1, &PyNotImplemented_Type
  1405. };
  1406. void
  1407. _Py_ReadyTypes(void)
  1408. {
  1409. if (PyType_Ready(&PyType_Type) < 0)
  1410. Py_FatalError("Can't initialize type type");
  1411. if (PyType_Ready(&_PyWeakref_RefType) < 0)
  1412. Py_FatalError("Can't initialize weakref type");
  1413. if (PyType_Ready(&_PyWeakref_CallableProxyType) < 0)
  1414. Py_FatalError("Can't initialize callable weakref proxy type");
  1415. if (PyType_Ready(&_PyWeakref_ProxyType) < 0)
  1416. Py_FatalError("Can't initialize weakref proxy type");
  1417. if (PyType_Ready(&PyBool_Type) < 0)
  1418. Py_FatalError("Can't initialize bool type");
  1419. if (PyType_Ready(&PyByteArray_Type) < 0)
  1420. Py_FatalError("Can't initialize bytearray type");
  1421. if (PyType_Ready(&PyBytes_Type) < 0)
  1422. Py_FatalError("Can't initialize 'str'");
  1423. if (PyType_Ready(&PyList_Type) < 0)
  1424. Py_FatalError("Can't initialize list type");
  1425. if (PyType_Ready(&PyNone_Type) < 0)
  1426. Py_FatalError("Can't initialize None type");
  1427. if (PyType_Ready(&PyNotImplemented_Type) < 0)
  1428. Py_FatalError("Can't initialize NotImplemented type");
  1429. if (PyType_Ready(&PyTraceBack_Type) < 0)
  1430. Py_FatalError("Can't initialize traceback type");
  1431. if (PyType_Ready(&PySuper_Type) < 0)
  1432. Py_FatalError("Can't initialize super type");
  1433. if (PyType_Ready(&PyBaseObject_Type) < 0)
  1434. Py_FatalError("Can't initialize object type");
  1435. if (PyType_Ready(&PyRange_Type) < 0)
  1436. Py_FatalError("Can't initialize range type");
  1437. if (PyType_Ready(&PyDict_Type) < 0)
  1438. Py_FatalError("Can't initialize dict type");
  1439. if (PyType_Ready(&PySet_Type) < 0)
  1440. Py_FatalError("Can't initialize set type");
  1441. if (PyType_Ready(&PyUnicode_Type) < 0)
  1442. Py_FatalError("Can't initialize str type");
  1443. if (PyType_Ready(&PySlice_Type) < 0)
  1444. Py_FatalError("Can't initialize slice type");
  1445. if (PyType_Ready(&PyStaticMethod_Type) < 0)
  1446. Py_FatalError("Can't initialize static method type");
  1447. if (PyType_Ready(&PyComplex_Type) < 0)
  1448. Py_FatalError("Can't initialize complex type");
  1449. if (PyType_Ready(&PyFloat_Type) < 0)
  1450. Py_FatalError("Can't initialize float type");
  1451. if (PyType_Ready(&PyLong_Type) < 0)
  1452. Py_FatalError("Can't initialize int type");
  1453. if (PyType_Ready(&PyFrozenSet_Type) < 0)
  1454. Py_FatalError("Can't initialize frozenset type");
  1455. if (PyType_Ready(&PyProperty_Type) < 0)
  1456. Py_FatalError("Can't initialize property type");
  1457. if (PyType_Ready(&_PyManagedBuffer_Type) < 0)
  1458. Py_FatalError("Can't initialize managed buffer type");
  1459. if (PyType_Ready(&PyMemoryView_Type) < 0)
  1460. Py_FatalError("Can't initialize memoryview type");
  1461. if (PyType_Ready(&PyTuple_Type) < 0)
  1462. Py_FatalError("Can't initialize tuple type");
  1463. if (PyType_Ready(&PyEnum_Type) < 0)
  1464. Py_FatalError("Can't initialize enumerate type");
  1465. if (PyType_Ready(&PyReversed_Type) < 0)
  1466. Py_FatalError("Can't initialize reversed type");
  1467. if (PyType_Ready(&PyStdPrinter_Type) < 0)
  1468. Py_FatalError("Can't initialize StdPrinter");
  1469. if (PyType_Ready(&PyCode_Type) < 0)
  1470. Py_FatalError("Can't initialize code type");
  1471. if (PyType_Ready(&PyFrame_Type) < 0)
  1472. Py_FatalError("Can't initialize frame type");
  1473. if (PyType_Ready(&PyCFunction_Type) < 0)
  1474. Py_FatalError("Can't initialize builtin function type");
  1475. if (PyType_Ready(&PyMethod_Type) < 0)
  1476. Py_FatalError("Can't initialize method type");
  1477. if (PyType_Ready(&PyFunction_Type) < 0)
  1478. Py_FatalError("Can't initialize function type");
  1479. if (PyType_Ready(&PyDictProxy_Type) < 0)
  1480. Py_FatalError("Can't initialize dict proxy type");
  1481. if (PyType_Ready(&PyGen_Type) < 0)
  1482. Py_FatalError("Can't initialize generator type");
  1483. if (PyType_Ready(&PyGetSetDescr_Type) < 0)
  1484. Py_FatalError("Can't initialize get-set descriptor type");
  1485. if (PyType_Ready(&PyWrapperDescr_Type) < 0)
  1486. Py_FatalError("Can't initialize wrapper type");
  1487. if (PyType_Ready(&_PyMethodWrapper_Type) < 0)
  1488. Py_FatalError("Can't initialize method wrapper type");
  1489. if (PyType_Ready(&PyEllipsis_Type) < 0)
  1490. Py_FatalError("Can't initialize ellipsis type");
  1491. if (PyType_Ready(&PyMemberDescr_Type) < 0)
  1492. Py_FatalError("Can't initialize member descriptor type");
  1493. if (PyType_Ready(&PyFilter_Type) < 0)
  1494. Py_FatalError("Can't initialize filter type");
  1495. if (PyType_Ready(&PyMap_Type) < 0)
  1496. Py_FatalError("Can't initialize map type");
  1497. if (PyType_Ready(&PyZip_Type) < 0)
  1498. Py_FatalError("Can't initialize zip type");
  1499. }
  1500. #ifdef Py_TRACE_REFS
  1501. void
  1502. _Py_NewReference(PyObject *op)
  1503. {
  1504. _Py_INC_REFTOTAL;
  1505. op->ob_refcnt = 1;
  1506. _Py_AddToAllObjects(op, 1);
  1507. _Py_INC_TPALLOCS(op);
  1508. }
  1509. void
  1510. _Py_ForgetReference(register PyObject *op)
  1511. {
  1512. #ifdef SLOW_UNREF_CHECK
  1513. register PyObject *p;
  1514. #endif
  1515. if (op->ob_refcnt < 0)
  1516. Py_FatalError("UNREF negative refcnt");
  1517. if (op == &refchain ||
  1518. op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op) {
  1519. fprintf(stderr, "* ob\n");
  1520. _PyObject_Dump(op);
  1521. fprintf(stderr, "* op->_ob_prev->_ob_next\n");
  1522. _PyObject_Dump(op->_ob_prev->_ob_next);
  1523. fprintf(stderr, "* op->_ob_next->_ob_prev\n");
  1524. _PyObject_Dump(op->_ob_next->_ob_prev);
  1525. Py_FatalError("UNREF invalid object");
  1526. }
  1527. #ifdef SLOW_UNREF_CHECK
  1528. for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
  1529. if (p == op)
  1530. break;
  1531. }
  1532. if (p == &refchain) /* Not found */
  1533. Py_FatalError("UNREF unknown object");
  1534. #endif
  1535. op->_ob_next->_ob_prev = op->_ob_prev;
  1536. op->_ob_prev->_ob_next = op->_ob_next;
  1537. op->_ob_next = op->_ob_prev = NULL;
  1538. _Py_INC_TPFREES(op);
  1539. }
  1540. void
  1541. _Py_Dealloc(PyObject *op)
  1542. {
  1543. destructor dealloc = Py_TYPE(op)->tp_dealloc;
  1544. _Py_ForgetReference(op);
  1545. (*dealloc)(op);
  1546. }
  1547. /* Print all live objects. Because PyObject_Print is called, the
  1548. * interpreter must be in a healthy state.
  1549. */
  1550. void
  1551. _Py_PrintReferences(FILE *fp)
  1552. {
  1553. PyObject *op;
  1554. fprintf(fp, "Remaining objects:\n");
  1555. for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
  1556. fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt);
  1557. if (PyObject_Print(op, fp, 0) != 0)
  1558. PyErr_Clear();
  1559. putc('\n', fp);
  1560. }
  1561. }
  1562. /* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
  1563. * doesn't make any calls to the Python C API, so is always safe to call.
  1564. */
  1565. void
  1566. _Py_PrintReferenceAddresses(FILE *fp)
  1567. {
  1568. PyObject *op;
  1569. fprintf(fp, "Remaining object addresses:\n");
  1570. for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
  1571. fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op,
  1572. op->ob_refcnt, Py_TYPE(op)->tp_name);
  1573. }
  1574. PyObject *
  1575. _Py_GetObjects(PyObject *self, PyObject *args)
  1576. {
  1577. int i, n;
  1578. PyObject *t = NULL;
  1579. PyObject *res, *op;
  1580. if (!PyArg_ParseTuple(args, "i|O", &n, &t))
  1581. return NULL;
  1582. op = refchain._ob_next;
  1583. res = PyList_New(0);
  1584. if (res == NULL)
  1585. return NULL;
  1586. for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
  1587. while (op == self || op == args || op == res || op == t ||
  1588. (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) {
  1589. op = op->_ob_next;
  1590. if (op == &refchain)
  1591. return res;
  1592. }
  1593. if (PyList_Append(res, op) < 0) {
  1594. Py_DECREF(res);
  1595. return NULL;
  1596. }
  1597. op = op->_ob_next;
  1598. }
  1599. return res;
  1600. }
  1601. #endif
  1602. /* Hack to force loading of pycapsule.o */
  1603. PyTypeObject *_PyCapsule_hack = &PyCapsule_Type;
  1604. /* Hack to force loading of abstract.o */
  1605. Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
  1606. /* Python's malloc wrappers (see pymem.h) */
  1607. void *
  1608. PyMem_Malloc(size_t nbytes)
  1609. {
  1610. return PyMem_MALLOC(nbytes);
  1611. }
  1612. void *
  1613. PyMem_Realloc(void *p, size_t nbytes)
  1614. {
  1615. return PyMem_REALLOC(p, nbytes);
  1616. }
  1617. void
  1618. PyMem_Free(void *p)
  1619. {
  1620. PyMem_FREE(p);
  1621. }
  1622. /* These methods are used to control infinite recursion in repr, str, print,
  1623. etc. Container objects that may recursively contain themselves,
  1624. e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
  1625. Py_ReprLeave() to avoid infinite recursion.
  1626. Py_ReprEnter() returns 0 the first time it is called for a particular
  1627. object and 1 every time thereafter. It returns -1 if an exception
  1628. occurred. Py_ReprLeave() has no return value.
  1629. See dictobject.c and listobject.c for examples of use.
  1630. */
  1631. #define KEY "Py_Repr"
  1632. int
  1633. Py_ReprEnter(PyObject *obj)
  1634. {
  1635. PyObject *dict;
  1636. PyObject *list;
  1637. Py_ssize_t i;
  1638. dict = PyThreadState_GetDict();
  1639. if (dict == NULL)
  1640. return 0;
  1641. list = PyDict_GetItemString(dict, KEY);
  1642. if (list == NULL) {
  1643. list = PyList_New(0);
  1644. if (list == NULL)
  1645. return -1;
  1646. if (PyDict_SetItemString(dict, KEY, list) < 0)
  1647. return -1;
  1648. Py_DECREF(list);
  1649. }
  1650. i = PyList_GET_SIZE(list);
  1651. while (--i >= 0) {
  1652. if (PyList_GET_ITEM(list, i) == obj)
  1653. return 1;
  1654. }
  1655. PyList_Append(list, obj);
  1656. return 0;
  1657. }
  1658. void
  1659. Py_ReprLeave(PyObject *obj)
  1660. {
  1661. PyObject *dict;
  1662. PyObject *list;
  1663. Py_ssize_t i;
  1664. dict = PyThreadState_GetDict();
  1665. if (dict == NULL)
  1666. return;
  1667. list = PyDict_GetItemString(dict, KEY);
  1668. if (list == NULL || !PyList_Check(list))
  1669. return;
  1670. i = PyList_GET_SIZE(list);
  1671. /* Count backwards because we always expect obj to be list[-1] */
  1672. while (--i >= 0) {
  1673. if (PyList_GET_ITEM(list, i) == obj) {
  1674. PyList_SetSlice(list, i, i + 1, NULL);
  1675. break;
  1676. }
  1677. }
  1678. }
  1679. /* Trashcan support. */
  1680. /* Current call-stack depth of tp_dealloc calls. */
  1681. int _PyTrash_delete_nesting = 0;
  1682. /* List of objects that still need to be cleaned up, singly linked via their
  1683. * gc headers' gc_prev pointers.
  1684. */
  1685. PyObject *_PyTrash_delete_later = NULL;
  1686. /* Add op to the _PyTrash_delete_later list. Called when the current
  1687. * call-stack depth gets large. op must be a currently untracked gc'ed
  1688. * object, with refcount 0. Py_DECREF must already have been called on it.
  1689. */
  1690. void
  1691. _PyTrash_deposit_object(PyObject *op)
  1692. {
  1693. assert(PyObject_IS_GC(op));
  1694. assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
  1695. assert(op->ob_refcnt == 0);
  1696. _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
  1697. _PyTrash_delete_later = op;
  1698. }
  1699. /* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
  1700. * the call-stack unwinds again.
  1701. */
  1702. void
  1703. _PyTrash_destroy_chain(void)
  1704. {
  1705. while (_PyTrash_delete_later) {
  1706. PyObject *op = _PyTrash_delete_later;
  1707. destructor dealloc = Py_TYPE(op)->tp_dealloc;
  1708. _PyTrash_delete_later =
  1709. (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
  1710. /* Call the deallocator directly. This used to try to
  1711. * fool Py_DECREF into calling it indirectly, but
  1712. * Py_DECREF was already called on this object, and in
  1713. * assorted non-release builds calling Py_DECREF again ends
  1714. * up distorting allocation statistics.
  1715. */
  1716. assert(op->ob_refcnt == 0);
  1717. ++_PyTrash_delete_nesting;
  1718. (*dealloc)(op);
  1719. --_PyTrash_delete_nesting;
  1720. }
  1721. }
  1722. #ifndef Py_TRACE_REFS
  1723. /* For Py_LIMITED_API, we need an out-of-line version of _Py_Dealloc.
  1724. Define this here, so we can undefine the macro. */
  1725. #undef _Py_Dealloc
  1726. PyAPI_FUNC(void) _Py_Dealloc(PyObject *);
  1727. void
  1728. _Py_Dealloc(PyObject *op)
  1729. {
  1730. _Py_INC_TPFREES(op) _Py_COUNT_ALLOCS_COMMA
  1731. (*Py_TYPE(op)->tp_dealloc)(op);
  1732. }
  1733. #endif
  1734. #ifdef __cplusplus
  1735. }
  1736. #endif