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.

2131 lines
59 KiB

36 years ago
36 years ago
36 years ago
36 years ago
24 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. ........
20 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...
26 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
36 years ago
36 years ago
36 years ago
35 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
Issue #24400: Introduce a distinct type for 'async def' coroutines. Summary of changes: 1. Coroutines now have a distinct, separate from generators type at the C level: PyGen_Type, and a new typedef PyCoroObject. PyCoroObject shares the initial segment of struct layout with PyGenObject, making it possible to reuse existing generators machinery. The new type is exposed as 'types.CoroutineType'. As a consequence of having a new type, CO_GENERATOR flag is no longer applied to coroutines. 2. Having a separate type for coroutines made it possible to add an __await__ method to the type. Although it is not used by the interpreter (see details on that below), it makes coroutines naturally (without using __instancecheck__) conform to collections.abc.Coroutine and collections.abc.Awaitable ABCs. [The __instancecheck__ is still used for generator-based coroutines, as we don't want to add __await__ for generators.] 3. Add new opcode: GET_YIELD_FROM_ITER. The opcode is needed to allow passing native coroutines to the YIELD_FROM opcode. Before this change, 'yield from o' expression was compiled to: (o) GET_ITER LOAD_CONST YIELD_FROM Now, we use GET_YIELD_FROM_ITER instead of GET_ITER. The reason for adding a new opcode is that GET_ITER is used in some contexts (such as 'for .. in' loops) where passing a coroutine object is invalid. 4. Add two new introspection functions to the inspec module: getcoroutinestate(c) and getcoroutinelocals(c). 5. inspect.iscoroutine(o) is updated to test if 'o' is a native coroutine object. Before this commit it used abc.Coroutine, and it was requested to update inspect.isgenerator(o) to use abc.Generator; it was decided, however, that inspect functions should really be tailored for checking for native types. 6. sys.set_coroutine_wrapper(w) API is updated to work with only native coroutines. Since types.coroutine decorator supports any type of callables now, it would be confusing that it does not work for all types of coroutines. 7. Exceptions logic in generators C implementation was updated to raise clearer messages for coroutines: Before: TypeError("generator raised StopIteration") After: TypeError("coroutine raised StopIteration")
11 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
  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. _Py_IDENTIFIER(Py_Repr);
  8. _Py_IDENTIFIER(__bytes__);
  9. _Py_IDENTIFIER(__dir__);
  10. _Py_IDENTIFIER(__isabstractmethod__);
  11. _Py_IDENTIFIER(builtins);
  12. #ifdef Py_REF_DEBUG
  13. Py_ssize_t _Py_RefTotal;
  14. Py_ssize_t
  15. _Py_GetRefTotal(void)
  16. {
  17. PyObject *o;
  18. Py_ssize_t total = _Py_RefTotal;
  19. o = _PySet_Dummy;
  20. if (o != NULL)
  21. total -= o->ob_refcnt;
  22. return total;
  23. }
  24. void
  25. _PyDebug_PrintTotalRefs(void) {
  26. PyObject *xoptions, *value;
  27. _Py_IDENTIFIER(showrefcount);
  28. xoptions = PySys_GetXOptions();
  29. if (xoptions == NULL)
  30. return;
  31. value = _PyDict_GetItemId(xoptions, &PyId_showrefcount);
  32. if (value == Py_True)
  33. fprintf(stderr,
  34. "[%" PY_FORMAT_SIZE_T "d refs, "
  35. "%" PY_FORMAT_SIZE_T "d blocks]\n",
  36. _Py_GetRefTotal(), _Py_GetAllocatedBlocks());
  37. }
  38. #endif /* Py_REF_DEBUG */
  39. /* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
  40. These are used by the individual routines for object creation.
  41. Do not call them otherwise, they do not initialize the object! */
  42. #ifdef Py_TRACE_REFS
  43. /* Head of circular doubly-linked list of all objects. These are linked
  44. * together via the _ob_prev and _ob_next members of a PyObject, which
  45. * exist only in a Py_TRACE_REFS build.
  46. */
  47. static PyObject refchain = {&refchain, &refchain};
  48. /* Insert op at the front of the list of all objects. If force is true,
  49. * op is added even if _ob_prev and _ob_next are non-NULL already. If
  50. * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
  51. * force should be true if and only if op points to freshly allocated,
  52. * uninitialized memory, or you've unlinked op from the list and are
  53. * relinking it into the front.
  54. * Note that objects are normally added to the list via _Py_NewReference,
  55. * which is called by PyObject_Init. Not all objects are initialized that
  56. * way, though; exceptions include statically allocated type objects, and
  57. * statically allocated singletons (like Py_True and Py_None).
  58. */
  59. void
  60. _Py_AddToAllObjects(PyObject *op, int force)
  61. {
  62. #ifdef Py_DEBUG
  63. if (!force) {
  64. /* If it's initialized memory, op must be in or out of
  65. * the list unambiguously.
  66. */
  67. assert((op->_ob_prev == NULL) == (op->_ob_next == NULL));
  68. }
  69. #endif
  70. if (force || op->_ob_prev == NULL) {
  71. op->_ob_next = refchain._ob_next;
  72. op->_ob_prev = &refchain;
  73. refchain._ob_next->_ob_prev = op;
  74. refchain._ob_next = op;
  75. }
  76. }
  77. #endif /* Py_TRACE_REFS */
  78. #ifdef COUNT_ALLOCS
  79. static PyTypeObject *type_list;
  80. /* All types are added to type_list, at least when
  81. they get one object created. That makes them
  82. immortal, which unfortunately contributes to
  83. garbage itself. If unlist_types_without_objects
  84. is set, they will be removed from the type_list
  85. once the last object is deallocated. */
  86. static int unlist_types_without_objects;
  87. extern Py_ssize_t tuple_zero_allocs, fast_tuple_allocs;
  88. extern Py_ssize_t quick_int_allocs, quick_neg_int_allocs;
  89. extern Py_ssize_t null_strings, one_strings;
  90. void
  91. dump_counts(FILE* f)
  92. {
  93. PyTypeObject *tp;
  94. PyObject *xoptions, *value;
  95. _Py_IDENTIFIER(showalloccount);
  96. xoptions = PySys_GetXOptions();
  97. if (xoptions == NULL)
  98. return;
  99. value = _PyDict_GetItemId(xoptions, &PyId_showalloccount);
  100. if (value != Py_True)
  101. return;
  102. for (tp = type_list; tp; tp = tp->tp_next)
  103. fprintf(f, "%s alloc'd: %" PY_FORMAT_SIZE_T "d, "
  104. "freed: %" PY_FORMAT_SIZE_T "d, "
  105. "max in use: %" PY_FORMAT_SIZE_T "d\n",
  106. tp->tp_name, tp->tp_allocs, tp->tp_frees,
  107. tp->tp_maxalloc);
  108. fprintf(f, "fast tuple allocs: %" PY_FORMAT_SIZE_T "d, "
  109. "empty: %" PY_FORMAT_SIZE_T "d\n",
  110. fast_tuple_allocs, tuple_zero_allocs);
  111. fprintf(f, "fast int allocs: pos: %" PY_FORMAT_SIZE_T "d, "
  112. "neg: %" PY_FORMAT_SIZE_T "d\n",
  113. quick_int_allocs, quick_neg_int_allocs);
  114. fprintf(f, "null strings: %" PY_FORMAT_SIZE_T "d, "
  115. "1-strings: %" PY_FORMAT_SIZE_T "d\n",
  116. null_strings, one_strings);
  117. }
  118. PyObject *
  119. get_counts(void)
  120. {
  121. PyTypeObject *tp;
  122. PyObject *result;
  123. PyObject *v;
  124. result = PyList_New(0);
  125. if (result == NULL)
  126. return NULL;
  127. for (tp = type_list; tp; tp = tp->tp_next) {
  128. v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs,
  129. tp->tp_frees, tp->tp_maxalloc);
  130. if (v == NULL) {
  131. Py_DECREF(result);
  132. return NULL;
  133. }
  134. if (PyList_Append(result, v) < 0) {
  135. Py_DECREF(v);
  136. Py_DECREF(result);
  137. return NULL;
  138. }
  139. Py_DECREF(v);
  140. }
  141. return result;
  142. }
  143. void
  144. inc_count(PyTypeObject *tp)
  145. {
  146. if (tp->tp_next == NULL && tp->tp_prev == NULL) {
  147. /* first time; insert in linked list */
  148. if (tp->tp_next != NULL) /* sanity check */
  149. Py_FatalError("XXX inc_count sanity check");
  150. if (type_list)
  151. type_list->tp_prev = tp;
  152. tp->tp_next = type_list;
  153. /* Note that as of Python 2.2, heap-allocated type objects
  154. * can go away, but this code requires that they stay alive
  155. * until program exit. That's why we're careful with
  156. * refcounts here. type_list gets a new reference to tp,
  157. * while ownership of the reference type_list used to hold
  158. * (if any) was transferred to tp->tp_next in the line above.
  159. * tp is thus effectively immortal after this.
  160. */
  161. Py_INCREF(tp);
  162. type_list = tp;
  163. #ifdef Py_TRACE_REFS
  164. /* Also insert in the doubly-linked list of all objects,
  165. * if not already there.
  166. */
  167. _Py_AddToAllObjects((PyObject *)tp, 0);
  168. #endif
  169. }
  170. tp->tp_allocs++;
  171. if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
  172. tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
  173. }
  174. void dec_count(PyTypeObject *tp)
  175. {
  176. tp->tp_frees++;
  177. if (unlist_types_without_objects &&
  178. tp->tp_allocs == tp->tp_frees) {
  179. /* unlink the type from type_list */
  180. if (tp->tp_prev)
  181. tp->tp_prev->tp_next = tp->tp_next;
  182. else
  183. type_list = tp->tp_next;
  184. if (tp->tp_next)
  185. tp->tp_next->tp_prev = tp->tp_prev;
  186. tp->tp_next = tp->tp_prev = NULL;
  187. Py_DECREF(tp);
  188. }
  189. }
  190. #endif
  191. #ifdef Py_REF_DEBUG
  192. /* Log a fatal error; doesn't return. */
  193. void
  194. _Py_NegativeRefcount(const char *fname, int lineno, PyObject *op)
  195. {
  196. char buf[300];
  197. PyOS_snprintf(buf, sizeof(buf),
  198. "%s:%i object at %p has negative ref count "
  199. "%" PY_FORMAT_SIZE_T "d",
  200. fname, lineno, op, op->ob_refcnt);
  201. Py_FatalError(buf);
  202. }
  203. #endif /* Py_REF_DEBUG */
  204. void
  205. Py_IncRef(PyObject *o)
  206. {
  207. Py_XINCREF(o);
  208. }
  209. void
  210. Py_DecRef(PyObject *o)
  211. {
  212. Py_XDECREF(o);
  213. }
  214. PyObject *
  215. PyObject_Init(PyObject *op, PyTypeObject *tp)
  216. {
  217. if (op == NULL)
  218. return PyErr_NoMemory();
  219. /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
  220. Py_TYPE(op) = tp;
  221. _Py_NewReference(op);
  222. return op;
  223. }
  224. PyVarObject *
  225. PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
  226. {
  227. if (op == NULL)
  228. return (PyVarObject *) PyErr_NoMemory();
  229. /* Any changes should be reflected in PyObject_INIT_VAR */
  230. op->ob_size = size;
  231. Py_TYPE(op) = tp;
  232. _Py_NewReference((PyObject *)op);
  233. return op;
  234. }
  235. PyObject *
  236. _PyObject_New(PyTypeObject *tp)
  237. {
  238. PyObject *op;
  239. op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
  240. if (op == NULL)
  241. return PyErr_NoMemory();
  242. return PyObject_INIT(op, tp);
  243. }
  244. PyVarObject *
  245. _PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
  246. {
  247. PyVarObject *op;
  248. const size_t size = _PyObject_VAR_SIZE(tp, nitems);
  249. op = (PyVarObject *) PyObject_MALLOC(size);
  250. if (op == NULL)
  251. return (PyVarObject *)PyErr_NoMemory();
  252. return PyObject_INIT_VAR(op, tp, nitems);
  253. }
  254. void
  255. PyObject_CallFinalizer(PyObject *self)
  256. {
  257. PyTypeObject *tp = Py_TYPE(self);
  258. /* The former could happen on heaptypes created from the C API, e.g.
  259. PyType_FromSpec(). */
  260. if (!PyType_HasFeature(tp, Py_TPFLAGS_HAVE_FINALIZE) ||
  261. tp->tp_finalize == NULL)
  262. return;
  263. /* tp_finalize should only be called once. */
  264. if (PyType_IS_GC(tp) && _PyGC_FINALIZED(self))
  265. return;
  266. tp->tp_finalize(self);
  267. if (PyType_IS_GC(tp))
  268. _PyGC_SET_FINALIZED(self, 1);
  269. }
  270. int
  271. PyObject_CallFinalizerFromDealloc(PyObject *self)
  272. {
  273. Py_ssize_t refcnt;
  274. /* Temporarily resurrect the object. */
  275. if (self->ob_refcnt != 0) {
  276. Py_FatalError("PyObject_CallFinalizerFromDealloc called on "
  277. "object with a non-zero refcount");
  278. }
  279. self->ob_refcnt = 1;
  280. PyObject_CallFinalizer(self);
  281. /* Undo the temporary resurrection; can't use DECREF here, it would
  282. * cause a recursive call.
  283. */
  284. assert(self->ob_refcnt > 0);
  285. if (--self->ob_refcnt == 0)
  286. return 0; /* this is the normal path out */
  287. /* tp_finalize resurrected it! Make it look like the original Py_DECREF
  288. * never happened.
  289. */
  290. refcnt = self->ob_refcnt;
  291. _Py_NewReference(self);
  292. self->ob_refcnt = refcnt;
  293. if (PyType_IS_GC(Py_TYPE(self))) {
  294. assert(_PyGC_REFS(self) != _PyGC_REFS_UNTRACKED);
  295. }
  296. /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
  297. * we need to undo that. */
  298. _Py_DEC_REFTOTAL;
  299. /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
  300. * chain, so no more to do there.
  301. * If COUNT_ALLOCS, the original decref bumped tp_frees, and
  302. * _Py_NewReference bumped tp_allocs: both of those need to be
  303. * undone.
  304. */
  305. #ifdef COUNT_ALLOCS
  306. --Py_TYPE(self)->tp_frees;
  307. --Py_TYPE(self)->tp_allocs;
  308. #endif
  309. return -1;
  310. }
  311. int
  312. PyObject_Print(PyObject *op, FILE *fp, int flags)
  313. {
  314. int ret = 0;
  315. if (PyErr_CheckSignals())
  316. return -1;
  317. #ifdef USE_STACKCHECK
  318. if (PyOS_CheckStack()) {
  319. PyErr_SetString(PyExc_MemoryError, "stack overflow");
  320. return -1;
  321. }
  322. #endif
  323. clearerr(fp); /* Clear any previous error condition */
  324. if (op == NULL) {
  325. Py_BEGIN_ALLOW_THREADS
  326. fprintf(fp, "<nil>");
  327. Py_END_ALLOW_THREADS
  328. }
  329. else {
  330. if (op->ob_refcnt <= 0)
  331. /* XXX(twouters) cast refcount to long until %zd is
  332. universally available */
  333. Py_BEGIN_ALLOW_THREADS
  334. fprintf(fp, "<refcnt %ld at %p>",
  335. (long)op->ob_refcnt, op);
  336. Py_END_ALLOW_THREADS
  337. else {
  338. PyObject *s;
  339. if (flags & Py_PRINT_RAW)
  340. s = PyObject_Str(op);
  341. else
  342. s = PyObject_Repr(op);
  343. if (s == NULL)
  344. ret = -1;
  345. else if (PyBytes_Check(s)) {
  346. fwrite(PyBytes_AS_STRING(s), 1,
  347. PyBytes_GET_SIZE(s), fp);
  348. }
  349. else if (PyUnicode_Check(s)) {
  350. PyObject *t;
  351. t = PyUnicode_AsEncodedString(s, "utf-8", "backslashreplace");
  352. if (t == NULL)
  353. ret = 0;
  354. else {
  355. fwrite(PyBytes_AS_STRING(t), 1,
  356. PyBytes_GET_SIZE(t), fp);
  357. Py_DECREF(t);
  358. }
  359. }
  360. else {
  361. PyErr_Format(PyExc_TypeError,
  362. "str() or repr() returned '%.100s'",
  363. s->ob_type->tp_name);
  364. ret = -1;
  365. }
  366. Py_XDECREF(s);
  367. }
  368. }
  369. if (ret == 0) {
  370. if (ferror(fp)) {
  371. PyErr_SetFromErrno(PyExc_OSError);
  372. clearerr(fp);
  373. ret = -1;
  374. }
  375. }
  376. return ret;
  377. }
  378. /* For debugging convenience. Set a breakpoint here and call it from your DLL */
  379. void
  380. _Py_BreakPoint(void)
  381. {
  382. }
  383. /* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
  384. void
  385. _PyObject_Dump(PyObject* op)
  386. {
  387. if (op == NULL)
  388. fprintf(stderr, "NULL\n");
  389. else {
  390. #ifdef WITH_THREAD
  391. PyGILState_STATE gil;
  392. #endif
  393. PyObject *error_type, *error_value, *error_traceback;
  394. fprintf(stderr, "object : ");
  395. #ifdef WITH_THREAD
  396. gil = PyGILState_Ensure();
  397. #endif
  398. PyErr_Fetch(&error_type, &error_value, &error_traceback);
  399. (void)PyObject_Print(op, stderr, 0);
  400. PyErr_Restore(error_type, error_value, error_traceback);
  401. #ifdef WITH_THREAD
  402. PyGILState_Release(gil);
  403. #endif
  404. /* XXX(twouters) cast refcount to long until %zd is
  405. universally available */
  406. fprintf(stderr, "\n"
  407. "type : %s\n"
  408. "refcount: %ld\n"
  409. "address : %p\n",
  410. Py_TYPE(op)==NULL ? "NULL" : Py_TYPE(op)->tp_name,
  411. (long)op->ob_refcnt,
  412. op);
  413. }
  414. }
  415. PyObject *
  416. PyObject_Repr(PyObject *v)
  417. {
  418. PyObject *res;
  419. if (PyErr_CheckSignals())
  420. return NULL;
  421. #ifdef USE_STACKCHECK
  422. if (PyOS_CheckStack()) {
  423. PyErr_SetString(PyExc_MemoryError, "stack overflow");
  424. return NULL;
  425. }
  426. #endif
  427. if (v == NULL)
  428. return PyUnicode_FromString("<NULL>");
  429. if (Py_TYPE(v)->tp_repr == NULL)
  430. return PyUnicode_FromFormat("<%s object at %p>",
  431. v->ob_type->tp_name, v);
  432. #ifdef Py_DEBUG
  433. /* PyObject_Repr() must not be called with an exception set,
  434. because it can clear it (directly or indirectly) and so the
  435. caller loses its exception */
  436. assert(!PyErr_Occurred());
  437. #endif
  438. res = (*v->ob_type->tp_repr)(v);
  439. if (res == NULL)
  440. return NULL;
  441. if (!PyUnicode_Check(res)) {
  442. PyErr_Format(PyExc_TypeError,
  443. "__repr__ returned non-string (type %.200s)",
  444. res->ob_type->tp_name);
  445. Py_DECREF(res);
  446. return NULL;
  447. }
  448. #ifndef Py_DEBUG
  449. if (PyUnicode_READY(res) < 0)
  450. return NULL;
  451. #endif
  452. return res;
  453. }
  454. PyObject *
  455. PyObject_Str(PyObject *v)
  456. {
  457. PyObject *res;
  458. if (PyErr_CheckSignals())
  459. return NULL;
  460. #ifdef USE_STACKCHECK
  461. if (PyOS_CheckStack()) {
  462. PyErr_SetString(PyExc_MemoryError, "stack overflow");
  463. return NULL;
  464. }
  465. #endif
  466. if (v == NULL)
  467. return PyUnicode_FromString("<NULL>");
  468. if (PyUnicode_CheckExact(v)) {
  469. #ifndef Py_DEBUG
  470. if (PyUnicode_READY(v) < 0)
  471. return NULL;
  472. #endif
  473. Py_INCREF(v);
  474. return v;
  475. }
  476. if (Py_TYPE(v)->tp_str == NULL)
  477. return PyObject_Repr(v);
  478. #ifdef Py_DEBUG
  479. /* PyObject_Str() must not be called with an exception set,
  480. because it can clear it (directly or indirectly) and so the
  481. caller loses its exception */
  482. assert(!PyErr_Occurred());
  483. #endif
  484. /* It is possible for a type to have a tp_str representation that loops
  485. infinitely. */
  486. if (Py_EnterRecursiveCall(" while getting the str of an object"))
  487. return NULL;
  488. res = (*Py_TYPE(v)->tp_str)(v);
  489. Py_LeaveRecursiveCall();
  490. if (res == NULL)
  491. return NULL;
  492. if (!PyUnicode_Check(res)) {
  493. PyErr_Format(PyExc_TypeError,
  494. "__str__ returned non-string (type %.200s)",
  495. Py_TYPE(res)->tp_name);
  496. Py_DECREF(res);
  497. return NULL;
  498. }
  499. #ifndef Py_DEBUG
  500. if (PyUnicode_READY(res) < 0)
  501. return NULL;
  502. #endif
  503. assert(_PyUnicode_CheckConsistency(res, 1));
  504. return res;
  505. }
  506. PyObject *
  507. PyObject_ASCII(PyObject *v)
  508. {
  509. PyObject *repr, *ascii, *res;
  510. repr = PyObject_Repr(v);
  511. if (repr == NULL)
  512. return NULL;
  513. if (PyUnicode_IS_ASCII(repr))
  514. return repr;
  515. /* repr is guaranteed to be a PyUnicode object by PyObject_Repr */
  516. ascii = _PyUnicode_AsASCIIString(repr, "backslashreplace");
  517. Py_DECREF(repr);
  518. if (ascii == NULL)
  519. return NULL;
  520. res = PyUnicode_DecodeASCII(
  521. PyBytes_AS_STRING(ascii),
  522. PyBytes_GET_SIZE(ascii),
  523. NULL);
  524. Py_DECREF(ascii);
  525. return res;
  526. }
  527. PyObject *
  528. PyObject_Bytes(PyObject *v)
  529. {
  530. PyObject *result, *func;
  531. if (v == NULL)
  532. return PyBytes_FromString("<NULL>");
  533. if (PyBytes_CheckExact(v)) {
  534. Py_INCREF(v);
  535. return v;
  536. }
  537. func = _PyObject_LookupSpecial(v, &PyId___bytes__);
  538. if (func != NULL) {
  539. result = _PyObject_CallNoArg(func);
  540. Py_DECREF(func);
  541. if (result == NULL)
  542. return NULL;
  543. if (!PyBytes_Check(result)) {
  544. PyErr_Format(PyExc_TypeError,
  545. "__bytes__ returned non-bytes (type %.200s)",
  546. Py_TYPE(result)->tp_name);
  547. Py_DECREF(result);
  548. return NULL;
  549. }
  550. return result;
  551. }
  552. else if (PyErr_Occurred())
  553. return NULL;
  554. return PyBytes_FromObject(v);
  555. }
  556. /* For Python 3.0.1 and later, the old three-way comparison has been
  557. completely removed in favour of rich comparisons. PyObject_Compare() and
  558. PyObject_Cmp() are gone, and the builtin cmp function no longer exists.
  559. The old tp_compare slot has been renamed to tp_reserved, and should no
  560. longer be used. Use tp_richcompare instead.
  561. See (*) below for practical amendments.
  562. tp_richcompare gets called with a first argument of the appropriate type
  563. and a second object of an arbitrary type. We never do any kind of
  564. coercion.
  565. The tp_richcompare slot should return an object, as follows:
  566. NULL if an exception occurred
  567. NotImplemented if the requested comparison is not implemented
  568. any other false value if the requested comparison is false
  569. any other true value if the requested comparison is true
  570. The PyObject_RichCompare[Bool]() wrappers raise TypeError when they get
  571. NotImplemented.
  572. (*) Practical amendments:
  573. - If rich comparison returns NotImplemented, == and != are decided by
  574. comparing the object pointer (i.e. falling back to the base object
  575. implementation).
  576. */
  577. /* Map rich comparison operators to their swapped version, e.g. LT <--> GT */
  578. int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
  579. static const char * const opstrings[] = {"<", "<=", "==", "!=", ">", ">="};
  580. /* Perform a rich comparison, raising TypeError when the requested comparison
  581. operator is not supported. */
  582. static PyObject *
  583. do_richcompare(PyObject *v, PyObject *w, int op)
  584. {
  585. richcmpfunc f;
  586. PyObject *res;
  587. int checked_reverse_op = 0;
  588. if (v->ob_type != w->ob_type &&
  589. PyType_IsSubtype(w->ob_type, v->ob_type) &&
  590. (f = w->ob_type->tp_richcompare) != NULL) {
  591. checked_reverse_op = 1;
  592. res = (*f)(w, v, _Py_SwappedOp[op]);
  593. if (res != Py_NotImplemented)
  594. return res;
  595. Py_DECREF(res);
  596. }
  597. if ((f = v->ob_type->tp_richcompare) != NULL) {
  598. res = (*f)(v, w, op);
  599. if (res != Py_NotImplemented)
  600. return res;
  601. Py_DECREF(res);
  602. }
  603. if (!checked_reverse_op && (f = w->ob_type->tp_richcompare) != NULL) {
  604. res = (*f)(w, v, _Py_SwappedOp[op]);
  605. if (res != Py_NotImplemented)
  606. return res;
  607. Py_DECREF(res);
  608. }
  609. /* If neither object implements it, provide a sensible default
  610. for == and !=, but raise an exception for ordering. */
  611. switch (op) {
  612. case Py_EQ:
  613. res = (v == w) ? Py_True : Py_False;
  614. break;
  615. case Py_NE:
  616. res = (v != w) ? Py_True : Py_False;
  617. break;
  618. default:
  619. PyErr_Format(PyExc_TypeError,
  620. "'%s' not supported between instances of '%.100s' and '%.100s'",
  621. opstrings[op],
  622. v->ob_type->tp_name,
  623. w->ob_type->tp_name);
  624. return NULL;
  625. }
  626. Py_INCREF(res);
  627. return res;
  628. }
  629. /* Perform a rich comparison with object result. This wraps do_richcompare()
  630. with a check for NULL arguments and a recursion check. */
  631. PyObject *
  632. PyObject_RichCompare(PyObject *v, PyObject *w, int op)
  633. {
  634. PyObject *res;
  635. assert(Py_LT <= op && op <= Py_GE);
  636. if (v == NULL || w == NULL) {
  637. if (!PyErr_Occurred())
  638. PyErr_BadInternalCall();
  639. return NULL;
  640. }
  641. if (Py_EnterRecursiveCall(" in comparison"))
  642. return NULL;
  643. res = do_richcompare(v, w, op);
  644. Py_LeaveRecursiveCall();
  645. return res;
  646. }
  647. /* Perform a rich comparison with integer result. This wraps
  648. PyObject_RichCompare(), returning -1 for error, 0 for false, 1 for true. */
  649. int
  650. PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
  651. {
  652. PyObject *res;
  653. int ok;
  654. /* Quick result when objects are the same.
  655. Guarantees that identity implies equality. */
  656. if (v == w) {
  657. if (op == Py_EQ)
  658. return 1;
  659. else if (op == Py_NE)
  660. return 0;
  661. }
  662. res = PyObject_RichCompare(v, w, op);
  663. if (res == NULL)
  664. return -1;
  665. if (PyBool_Check(res))
  666. ok = (res == Py_True);
  667. else
  668. ok = PyObject_IsTrue(res);
  669. Py_DECREF(res);
  670. return ok;
  671. }
  672. Py_hash_t
  673. PyObject_HashNotImplemented(PyObject *v)
  674. {
  675. PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
  676. Py_TYPE(v)->tp_name);
  677. return -1;
  678. }
  679. Py_hash_t
  680. PyObject_Hash(PyObject *v)
  681. {
  682. PyTypeObject *tp = Py_TYPE(v);
  683. if (tp->tp_hash != NULL)
  684. return (*tp->tp_hash)(v);
  685. /* To keep to the general practice that inheriting
  686. * solely from object in C code should work without
  687. * an explicit call to PyType_Ready, we implicitly call
  688. * PyType_Ready here and then check the tp_hash slot again
  689. */
  690. if (tp->tp_dict == NULL) {
  691. if (PyType_Ready(tp) < 0)
  692. return -1;
  693. if (tp->tp_hash != NULL)
  694. return (*tp->tp_hash)(v);
  695. }
  696. /* Otherwise, the object can't be hashed */
  697. return PyObject_HashNotImplemented(v);
  698. }
  699. PyObject *
  700. PyObject_GetAttrString(PyObject *v, const char *name)
  701. {
  702. PyObject *w, *res;
  703. if (Py_TYPE(v)->tp_getattr != NULL)
  704. return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
  705. w = PyUnicode_FromString(name);
  706. if (w == NULL)
  707. return NULL;
  708. res = PyObject_GetAttr(v, w);
  709. Py_DECREF(w);
  710. return res;
  711. }
  712. int
  713. PyObject_HasAttrString(PyObject *v, const char *name)
  714. {
  715. PyObject *res = PyObject_GetAttrString(v, name);
  716. if (res != NULL) {
  717. Py_DECREF(res);
  718. return 1;
  719. }
  720. PyErr_Clear();
  721. return 0;
  722. }
  723. int
  724. PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
  725. {
  726. PyObject *s;
  727. int res;
  728. if (Py_TYPE(v)->tp_setattr != NULL)
  729. return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
  730. s = PyUnicode_InternFromString(name);
  731. if (s == NULL)
  732. return -1;
  733. res = PyObject_SetAttr(v, s, w);
  734. Py_XDECREF(s);
  735. return res;
  736. }
  737. int
  738. _PyObject_IsAbstract(PyObject *obj)
  739. {
  740. int res;
  741. PyObject* isabstract;
  742. if (obj == NULL)
  743. return 0;
  744. isabstract = _PyObject_GetAttrId(obj, &PyId___isabstractmethod__);
  745. if (isabstract == NULL) {
  746. if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
  747. PyErr_Clear();
  748. return 0;
  749. }
  750. return -1;
  751. }
  752. res = PyObject_IsTrue(isabstract);
  753. Py_DECREF(isabstract);
  754. return res;
  755. }
  756. PyObject *
  757. _PyObject_GetAttrId(PyObject *v, _Py_Identifier *name)
  758. {
  759. PyObject *result;
  760. PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
  761. if (!oname)
  762. return NULL;
  763. result = PyObject_GetAttr(v, oname);
  764. return result;
  765. }
  766. int
  767. _PyObject_HasAttrId(PyObject *v, _Py_Identifier *name)
  768. {
  769. int result;
  770. PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
  771. if (!oname)
  772. return -1;
  773. result = PyObject_HasAttr(v, oname);
  774. return result;
  775. }
  776. int
  777. _PyObject_SetAttrId(PyObject *v, _Py_Identifier *name, PyObject *w)
  778. {
  779. int result;
  780. PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
  781. if (!oname)
  782. return -1;
  783. result = PyObject_SetAttr(v, oname, w);
  784. return result;
  785. }
  786. PyObject *
  787. PyObject_GetAttr(PyObject *v, PyObject *name)
  788. {
  789. PyTypeObject *tp = Py_TYPE(v);
  790. if (!PyUnicode_Check(name)) {
  791. PyErr_Format(PyExc_TypeError,
  792. "attribute name must be string, not '%.200s'",
  793. name->ob_type->tp_name);
  794. return NULL;
  795. }
  796. if (tp->tp_getattro != NULL)
  797. return (*tp->tp_getattro)(v, name);
  798. if (tp->tp_getattr != NULL) {
  799. const char *name_str = PyUnicode_AsUTF8(name);
  800. if (name_str == NULL)
  801. return NULL;
  802. return (*tp->tp_getattr)(v, (char *)name_str);
  803. }
  804. PyErr_Format(PyExc_AttributeError,
  805. "'%.50s' object has no attribute '%U'",
  806. tp->tp_name, name);
  807. return NULL;
  808. }
  809. int
  810. PyObject_HasAttr(PyObject *v, PyObject *name)
  811. {
  812. PyObject *res = PyObject_GetAttr(v, name);
  813. if (res != NULL) {
  814. Py_DECREF(res);
  815. return 1;
  816. }
  817. PyErr_Clear();
  818. return 0;
  819. }
  820. int
  821. PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
  822. {
  823. PyTypeObject *tp = Py_TYPE(v);
  824. int err;
  825. if (!PyUnicode_Check(name)) {
  826. PyErr_Format(PyExc_TypeError,
  827. "attribute name must be string, not '%.200s'",
  828. name->ob_type->tp_name);
  829. return -1;
  830. }
  831. Py_INCREF(name);
  832. PyUnicode_InternInPlace(&name);
  833. if (tp->tp_setattro != NULL) {
  834. err = (*tp->tp_setattro)(v, name, value);
  835. Py_DECREF(name);
  836. return err;
  837. }
  838. if (tp->tp_setattr != NULL) {
  839. const char *name_str = PyUnicode_AsUTF8(name);
  840. if (name_str == NULL)
  841. return -1;
  842. err = (*tp->tp_setattr)(v, (char *)name_str, value);
  843. Py_DECREF(name);
  844. return err;
  845. }
  846. Py_DECREF(name);
  847. assert(name->ob_refcnt >= 1);
  848. if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
  849. PyErr_Format(PyExc_TypeError,
  850. "'%.100s' object has no attributes "
  851. "(%s .%U)",
  852. tp->tp_name,
  853. value==NULL ? "del" : "assign to",
  854. name);
  855. else
  856. PyErr_Format(PyExc_TypeError,
  857. "'%.100s' object has only read-only attributes "
  858. "(%s .%U)",
  859. tp->tp_name,
  860. value==NULL ? "del" : "assign to",
  861. name);
  862. return -1;
  863. }
  864. /* Helper to get a pointer to an object's __dict__ slot, if any */
  865. PyObject **
  866. _PyObject_GetDictPtr(PyObject *obj)
  867. {
  868. Py_ssize_t dictoffset;
  869. PyTypeObject *tp = Py_TYPE(obj);
  870. dictoffset = tp->tp_dictoffset;
  871. if (dictoffset == 0)
  872. return NULL;
  873. if (dictoffset < 0) {
  874. Py_ssize_t tsize;
  875. size_t size;
  876. tsize = ((PyVarObject *)obj)->ob_size;
  877. if (tsize < 0)
  878. tsize = -tsize;
  879. size = _PyObject_VAR_SIZE(tp, tsize);
  880. dictoffset += (long)size;
  881. assert(dictoffset > 0);
  882. assert(dictoffset % SIZEOF_VOID_P == 0);
  883. }
  884. return (PyObject **) ((char *)obj + dictoffset);
  885. }
  886. PyObject *
  887. PyObject_SelfIter(PyObject *obj)
  888. {
  889. Py_INCREF(obj);
  890. return obj;
  891. }
  892. /* Convenience function to get a builtin from its name */
  893. PyObject *
  894. _PyObject_GetBuiltin(const char *name)
  895. {
  896. PyObject *mod_name, *mod, *attr;
  897. mod_name = _PyUnicode_FromId(&PyId_builtins); /* borrowed */
  898. if (mod_name == NULL)
  899. return NULL;
  900. mod = PyImport_Import(mod_name);
  901. if (mod == NULL)
  902. return NULL;
  903. attr = PyObject_GetAttrString(mod, name);
  904. Py_DECREF(mod);
  905. return attr;
  906. }
  907. /* Helper used when the __next__ method is removed from a type:
  908. tp_iternext is never NULL and can be safely called without checking
  909. on every iteration.
  910. */
  911. PyObject *
  912. _PyObject_NextNotImplemented(PyObject *self)
  913. {
  914. PyErr_Format(PyExc_TypeError,
  915. "'%.200s' object is not iterable",
  916. Py_TYPE(self)->tp_name);
  917. return NULL;
  918. }
  919. /* Specialized version of _PyObject_GenericGetAttrWithDict
  920. specifically for the LOAD_METHOD opcode.
  921. Return 1 if a method is found, 0 if it's a regular attribute
  922. from __dict__ or something returned by using a descriptor
  923. protocol.
  924. `method` will point to the resolved attribute or NULL. In the
  925. latter case, an error will be set.
  926. */
  927. int
  928. _PyObject_GetMethod(PyObject *obj, PyObject *name, PyObject **method)
  929. {
  930. PyTypeObject *tp = Py_TYPE(obj);
  931. PyObject *descr;
  932. descrgetfunc f = NULL;
  933. PyObject **dictptr, *dict;
  934. PyObject *attr;
  935. int meth_found = 0;
  936. assert(*method == NULL);
  937. if (Py_TYPE(obj)->tp_getattro != PyObject_GenericGetAttr
  938. || !PyUnicode_Check(name)) {
  939. *method = PyObject_GetAttr(obj, name);
  940. return 0;
  941. }
  942. if (tp->tp_dict == NULL && PyType_Ready(tp) < 0)
  943. return 0;
  944. descr = _PyType_Lookup(tp, name);
  945. if (descr != NULL) {
  946. Py_INCREF(descr);
  947. if (PyFunction_Check(descr) ||
  948. (Py_TYPE(descr) == &PyMethodDescr_Type)) {
  949. meth_found = 1;
  950. } else {
  951. f = descr->ob_type->tp_descr_get;
  952. if (f != NULL && PyDescr_IsData(descr)) {
  953. *method = f(descr, obj, (PyObject *)obj->ob_type);
  954. Py_DECREF(descr);
  955. return 0;
  956. }
  957. }
  958. }
  959. dictptr = _PyObject_GetDictPtr(obj);
  960. if (dictptr != NULL && (dict = *dictptr) != NULL) {
  961. Py_INCREF(dict);
  962. attr = PyDict_GetItem(dict, name);
  963. if (attr != NULL) {
  964. Py_INCREF(attr);
  965. *method = attr;
  966. Py_DECREF(dict);
  967. Py_XDECREF(descr);
  968. return 0;
  969. }
  970. Py_DECREF(dict);
  971. }
  972. if (meth_found) {
  973. *method = descr;
  974. return 1;
  975. }
  976. if (f != NULL) {
  977. *method = f(descr, obj, (PyObject *)Py_TYPE(obj));
  978. Py_DECREF(descr);
  979. return 0;
  980. }
  981. if (descr != NULL) {
  982. *method = descr;
  983. return 0;
  984. }
  985. PyErr_Format(PyExc_AttributeError,
  986. "'%.50s' object has no attribute '%U'",
  987. tp->tp_name, name);
  988. return 0;
  989. }
  990. /* Generic GetAttr functions - put these in your tp_[gs]etattro slot. */
  991. PyObject *
  992. _PyObject_GenericGetAttrWithDict(PyObject *obj, PyObject *name, PyObject *dict)
  993. {
  994. /* Make sure the logic of _PyObject_GetMethod is in sync with
  995. this method.
  996. */
  997. PyTypeObject *tp = Py_TYPE(obj);
  998. PyObject *descr = NULL;
  999. PyObject *res = NULL;
  1000. descrgetfunc f;
  1001. Py_ssize_t dictoffset;
  1002. PyObject **dictptr;
  1003. if (!PyUnicode_Check(name)){
  1004. PyErr_Format(PyExc_TypeError,
  1005. "attribute name must be string, not '%.200s'",
  1006. name->ob_type->tp_name);
  1007. return NULL;
  1008. }
  1009. Py_INCREF(name);
  1010. if (tp->tp_dict == NULL) {
  1011. if (PyType_Ready(tp) < 0)
  1012. goto done;
  1013. }
  1014. descr = _PyType_Lookup(tp, name);
  1015. f = NULL;
  1016. if (descr != NULL) {
  1017. Py_INCREF(descr);
  1018. f = descr->ob_type->tp_descr_get;
  1019. if (f != NULL && PyDescr_IsData(descr)) {
  1020. res = f(descr, obj, (PyObject *)obj->ob_type);
  1021. goto done;
  1022. }
  1023. }
  1024. if (dict == NULL) {
  1025. /* Inline _PyObject_GetDictPtr */
  1026. dictoffset = tp->tp_dictoffset;
  1027. if (dictoffset != 0) {
  1028. if (dictoffset < 0) {
  1029. Py_ssize_t tsize;
  1030. size_t size;
  1031. tsize = ((PyVarObject *)obj)->ob_size;
  1032. if (tsize < 0)
  1033. tsize = -tsize;
  1034. size = _PyObject_VAR_SIZE(tp, tsize);
  1035. assert(size <= PY_SSIZE_T_MAX);
  1036. dictoffset += (Py_ssize_t)size;
  1037. assert(dictoffset > 0);
  1038. assert(dictoffset % SIZEOF_VOID_P == 0);
  1039. }
  1040. dictptr = (PyObject **) ((char *)obj + dictoffset);
  1041. dict = *dictptr;
  1042. }
  1043. }
  1044. if (dict != NULL) {
  1045. Py_INCREF(dict);
  1046. res = PyDict_GetItem(dict, name);
  1047. if (res != NULL) {
  1048. Py_INCREF(res);
  1049. Py_DECREF(dict);
  1050. goto done;
  1051. }
  1052. Py_DECREF(dict);
  1053. }
  1054. if (f != NULL) {
  1055. res = f(descr, obj, (PyObject *)Py_TYPE(obj));
  1056. goto done;
  1057. }
  1058. if (descr != NULL) {
  1059. res = descr;
  1060. descr = NULL;
  1061. goto done;
  1062. }
  1063. PyErr_Format(PyExc_AttributeError,
  1064. "'%.50s' object has no attribute '%U'",
  1065. tp->tp_name, name);
  1066. done:
  1067. Py_XDECREF(descr);
  1068. Py_DECREF(name);
  1069. return res;
  1070. }
  1071. PyObject *
  1072. PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
  1073. {
  1074. return _PyObject_GenericGetAttrWithDict(obj, name, NULL);
  1075. }
  1076. int
  1077. _PyObject_GenericSetAttrWithDict(PyObject *obj, PyObject *name,
  1078. PyObject *value, PyObject *dict)
  1079. {
  1080. PyTypeObject *tp = Py_TYPE(obj);
  1081. PyObject *descr;
  1082. descrsetfunc f;
  1083. PyObject **dictptr;
  1084. int res = -1;
  1085. if (!PyUnicode_Check(name)){
  1086. PyErr_Format(PyExc_TypeError,
  1087. "attribute name must be string, not '%.200s'",
  1088. name->ob_type->tp_name);
  1089. return -1;
  1090. }
  1091. if (tp->tp_dict == NULL && PyType_Ready(tp) < 0)
  1092. return -1;
  1093. Py_INCREF(name);
  1094. descr = _PyType_Lookup(tp, name);
  1095. if (descr != NULL) {
  1096. Py_INCREF(descr);
  1097. f = descr->ob_type->tp_descr_set;
  1098. if (f != NULL) {
  1099. res = f(descr, obj, value);
  1100. goto done;
  1101. }
  1102. }
  1103. if (dict == NULL) {
  1104. dictptr = _PyObject_GetDictPtr(obj);
  1105. if (dictptr == NULL) {
  1106. if (descr == NULL) {
  1107. PyErr_Format(PyExc_AttributeError,
  1108. "'%.100s' object has no attribute '%U'",
  1109. tp->tp_name, name);
  1110. }
  1111. else {
  1112. PyErr_Format(PyExc_AttributeError,
  1113. "'%.50s' object attribute '%U' is read-only",
  1114. tp->tp_name, name);
  1115. }
  1116. goto done;
  1117. }
  1118. res = _PyObjectDict_SetItem(tp, dictptr, name, value);
  1119. }
  1120. else {
  1121. Py_INCREF(dict);
  1122. if (value == NULL)
  1123. res = PyDict_DelItem(dict, name);
  1124. else
  1125. res = PyDict_SetItem(dict, name, value);
  1126. Py_DECREF(dict);
  1127. }
  1128. if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
  1129. PyErr_SetObject(PyExc_AttributeError, name);
  1130. done:
  1131. Py_XDECREF(descr);
  1132. Py_DECREF(name);
  1133. return res;
  1134. }
  1135. int
  1136. PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
  1137. {
  1138. return _PyObject_GenericSetAttrWithDict(obj, name, value, NULL);
  1139. }
  1140. int
  1141. PyObject_GenericSetDict(PyObject *obj, PyObject *value, void *context)
  1142. {
  1143. PyObject **dictptr = _PyObject_GetDictPtr(obj);
  1144. if (dictptr == NULL) {
  1145. PyErr_SetString(PyExc_AttributeError,
  1146. "This object has no __dict__");
  1147. return -1;
  1148. }
  1149. if (value == NULL) {
  1150. PyErr_SetString(PyExc_TypeError, "cannot delete __dict__");
  1151. return -1;
  1152. }
  1153. if (!PyDict_Check(value)) {
  1154. PyErr_Format(PyExc_TypeError,
  1155. "__dict__ must be set to a dictionary, "
  1156. "not a '%.200s'", Py_TYPE(value)->tp_name);
  1157. return -1;
  1158. }
  1159. Py_INCREF(value);
  1160. Py_XSETREF(*dictptr, value);
  1161. return 0;
  1162. }
  1163. /* Test a value used as condition, e.g., in a for or if statement.
  1164. Return -1 if an error occurred */
  1165. int
  1166. PyObject_IsTrue(PyObject *v)
  1167. {
  1168. Py_ssize_t res;
  1169. if (v == Py_True)
  1170. return 1;
  1171. if (v == Py_False)
  1172. return 0;
  1173. if (v == Py_None)
  1174. return 0;
  1175. else if (v->ob_type->tp_as_number != NULL &&
  1176. v->ob_type->tp_as_number->nb_bool != NULL)
  1177. res = (*v->ob_type->tp_as_number->nb_bool)(v);
  1178. else if (v->ob_type->tp_as_mapping != NULL &&
  1179. v->ob_type->tp_as_mapping->mp_length != NULL)
  1180. res = (*v->ob_type->tp_as_mapping->mp_length)(v);
  1181. else if (v->ob_type->tp_as_sequence != NULL &&
  1182. v->ob_type->tp_as_sequence->sq_length != NULL)
  1183. res = (*v->ob_type->tp_as_sequence->sq_length)(v);
  1184. else
  1185. return 1;
  1186. /* if it is negative, it should be either -1 or -2 */
  1187. return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
  1188. }
  1189. /* equivalent of 'not v'
  1190. Return -1 if an error occurred */
  1191. int
  1192. PyObject_Not(PyObject *v)
  1193. {
  1194. int res;
  1195. res = PyObject_IsTrue(v);
  1196. if (res < 0)
  1197. return res;
  1198. return res == 0;
  1199. }
  1200. /* Test whether an object can be called */
  1201. int
  1202. PyCallable_Check(PyObject *x)
  1203. {
  1204. if (x == NULL)
  1205. return 0;
  1206. return x->ob_type->tp_call != NULL;
  1207. }
  1208. /* Helper for PyObject_Dir without arguments: returns the local scope. */
  1209. static PyObject *
  1210. _dir_locals(void)
  1211. {
  1212. PyObject *names;
  1213. PyObject *locals;
  1214. locals = PyEval_GetLocals();
  1215. if (locals == NULL)
  1216. return NULL;
  1217. names = PyMapping_Keys(locals);
  1218. if (!names)
  1219. return NULL;
  1220. if (!PyList_Check(names)) {
  1221. PyErr_Format(PyExc_TypeError,
  1222. "dir(): expected keys() of locals to be a list, "
  1223. "not '%.200s'", Py_TYPE(names)->tp_name);
  1224. Py_DECREF(names);
  1225. return NULL;
  1226. }
  1227. if (PyList_Sort(names)) {
  1228. Py_DECREF(names);
  1229. return NULL;
  1230. }
  1231. /* the locals don't need to be DECREF'd */
  1232. return names;
  1233. }
  1234. /* Helper for PyObject_Dir: object introspection. */
  1235. static PyObject *
  1236. _dir_object(PyObject *obj)
  1237. {
  1238. PyObject *result, *sorted;
  1239. PyObject *dirfunc = _PyObject_LookupSpecial(obj, &PyId___dir__);
  1240. assert(obj);
  1241. if (dirfunc == NULL) {
  1242. if (!PyErr_Occurred())
  1243. PyErr_SetString(PyExc_TypeError, "object does not provide __dir__");
  1244. return NULL;
  1245. }
  1246. /* use __dir__ */
  1247. result = _PyObject_CallNoArg(dirfunc);
  1248. Py_DECREF(dirfunc);
  1249. if (result == NULL)
  1250. return NULL;
  1251. /* return sorted(result) */
  1252. sorted = PySequence_List(result);
  1253. Py_DECREF(result);
  1254. if (sorted == NULL)
  1255. return NULL;
  1256. if (PyList_Sort(sorted)) {
  1257. Py_DECREF(sorted);
  1258. return NULL;
  1259. }
  1260. return sorted;
  1261. }
  1262. /* Implementation of dir() -- if obj is NULL, returns the names in the current
  1263. (local) scope. Otherwise, performs introspection of the object: returns a
  1264. sorted list of attribute names (supposedly) accessible from the object
  1265. */
  1266. PyObject *
  1267. PyObject_Dir(PyObject *obj)
  1268. {
  1269. return (obj == NULL) ? _dir_locals() : _dir_object(obj);
  1270. }
  1271. /*
  1272. None is a non-NULL undefined value.
  1273. There is (and should be!) no way to create other objects of this type,
  1274. so there is exactly one (which is indestructible, by the way).
  1275. */
  1276. /* ARGSUSED */
  1277. static PyObject *
  1278. none_repr(PyObject *op)
  1279. {
  1280. return PyUnicode_FromString("None");
  1281. }
  1282. /* ARGUSED */
  1283. static void
  1284. none_dealloc(PyObject* ignore)
  1285. {
  1286. /* This should never get called, but we also don't want to SEGV if
  1287. * we accidentally decref None out of existence.
  1288. */
  1289. Py_FatalError("deallocating None");
  1290. }
  1291. static PyObject *
  1292. none_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
  1293. {
  1294. if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
  1295. PyErr_SetString(PyExc_TypeError, "NoneType takes no arguments");
  1296. return NULL;
  1297. }
  1298. Py_RETURN_NONE;
  1299. }
  1300. static int
  1301. none_bool(PyObject *v)
  1302. {
  1303. return 0;
  1304. }
  1305. static PyNumberMethods none_as_number = {
  1306. 0, /* nb_add */
  1307. 0, /* nb_subtract */
  1308. 0, /* nb_multiply */
  1309. 0, /* nb_remainder */
  1310. 0, /* nb_divmod */
  1311. 0, /* nb_power */
  1312. 0, /* nb_negative */
  1313. 0, /* nb_positive */
  1314. 0, /* nb_absolute */
  1315. (inquiry)none_bool, /* nb_bool */
  1316. 0, /* nb_invert */
  1317. 0, /* nb_lshift */
  1318. 0, /* nb_rshift */
  1319. 0, /* nb_and */
  1320. 0, /* nb_xor */
  1321. 0, /* nb_or */
  1322. 0, /* nb_int */
  1323. 0, /* nb_reserved */
  1324. 0, /* nb_float */
  1325. 0, /* nb_inplace_add */
  1326. 0, /* nb_inplace_subtract */
  1327. 0, /* nb_inplace_multiply */
  1328. 0, /* nb_inplace_remainder */
  1329. 0, /* nb_inplace_power */
  1330. 0, /* nb_inplace_lshift */
  1331. 0, /* nb_inplace_rshift */
  1332. 0, /* nb_inplace_and */
  1333. 0, /* nb_inplace_xor */
  1334. 0, /* nb_inplace_or */
  1335. 0, /* nb_floor_divide */
  1336. 0, /* nb_true_divide */
  1337. 0, /* nb_inplace_floor_divide */
  1338. 0, /* nb_inplace_true_divide */
  1339. 0, /* nb_index */
  1340. };
  1341. PyTypeObject _PyNone_Type = {
  1342. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  1343. "NoneType",
  1344. 0,
  1345. 0,
  1346. none_dealloc, /*tp_dealloc*/ /*never called*/
  1347. 0, /*tp_print*/
  1348. 0, /*tp_getattr*/
  1349. 0, /*tp_setattr*/
  1350. 0, /*tp_reserved*/
  1351. none_repr, /*tp_repr*/
  1352. &none_as_number, /*tp_as_number*/
  1353. 0, /*tp_as_sequence*/
  1354. 0, /*tp_as_mapping*/
  1355. 0, /*tp_hash */
  1356. 0, /*tp_call */
  1357. 0, /*tp_str */
  1358. 0, /*tp_getattro */
  1359. 0, /*tp_setattro */
  1360. 0, /*tp_as_buffer */
  1361. Py_TPFLAGS_DEFAULT, /*tp_flags */
  1362. 0, /*tp_doc */
  1363. 0, /*tp_traverse */
  1364. 0, /*tp_clear */
  1365. 0, /*tp_richcompare */
  1366. 0, /*tp_weaklistoffset */
  1367. 0, /*tp_iter */
  1368. 0, /*tp_iternext */
  1369. 0, /*tp_methods */
  1370. 0, /*tp_members */
  1371. 0, /*tp_getset */
  1372. 0, /*tp_base */
  1373. 0, /*tp_dict */
  1374. 0, /*tp_descr_get */
  1375. 0, /*tp_descr_set */
  1376. 0, /*tp_dictoffset */
  1377. 0, /*tp_init */
  1378. 0, /*tp_alloc */
  1379. none_new, /*tp_new */
  1380. };
  1381. PyObject _Py_NoneStruct = {
  1382. _PyObject_EXTRA_INIT
  1383. 1, &_PyNone_Type
  1384. };
  1385. /* NotImplemented is an object that can be used to signal that an
  1386. operation is not implemented for the given type combination. */
  1387. static PyObject *
  1388. NotImplemented_repr(PyObject *op)
  1389. {
  1390. return PyUnicode_FromString("NotImplemented");
  1391. }
  1392. static PyObject *
  1393. NotImplemented_reduce(PyObject *op)
  1394. {
  1395. return PyUnicode_FromString("NotImplemented");
  1396. }
  1397. static PyMethodDef notimplemented_methods[] = {
  1398. {"__reduce__", (PyCFunction)NotImplemented_reduce, METH_NOARGS, NULL},
  1399. {NULL, NULL}
  1400. };
  1401. static PyObject *
  1402. notimplemented_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
  1403. {
  1404. if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_GET_SIZE(kwargs))) {
  1405. PyErr_SetString(PyExc_TypeError, "NotImplementedType takes no arguments");
  1406. return NULL;
  1407. }
  1408. Py_RETURN_NOTIMPLEMENTED;
  1409. }
  1410. static void
  1411. notimplemented_dealloc(PyObject* ignore)
  1412. {
  1413. /* This should never get called, but we also don't want to SEGV if
  1414. * we accidentally decref NotImplemented out of existence.
  1415. */
  1416. Py_FatalError("deallocating NotImplemented");
  1417. }
  1418. PyTypeObject _PyNotImplemented_Type = {
  1419. PyVarObject_HEAD_INIT(&PyType_Type, 0)
  1420. "NotImplementedType",
  1421. 0,
  1422. 0,
  1423. notimplemented_dealloc, /*tp_dealloc*/ /*never called*/
  1424. 0, /*tp_print*/
  1425. 0, /*tp_getattr*/
  1426. 0, /*tp_setattr*/
  1427. 0, /*tp_reserved*/
  1428. NotImplemented_repr, /*tp_repr*/
  1429. 0, /*tp_as_number*/
  1430. 0, /*tp_as_sequence*/
  1431. 0, /*tp_as_mapping*/
  1432. 0, /*tp_hash */
  1433. 0, /*tp_call */
  1434. 0, /*tp_str */
  1435. 0, /*tp_getattro */
  1436. 0, /*tp_setattro */
  1437. 0, /*tp_as_buffer */
  1438. Py_TPFLAGS_DEFAULT, /*tp_flags */
  1439. 0, /*tp_doc */
  1440. 0, /*tp_traverse */
  1441. 0, /*tp_clear */
  1442. 0, /*tp_richcompare */
  1443. 0, /*tp_weaklistoffset */
  1444. 0, /*tp_iter */
  1445. 0, /*tp_iternext */
  1446. notimplemented_methods, /*tp_methods */
  1447. 0, /*tp_members */
  1448. 0, /*tp_getset */
  1449. 0, /*tp_base */
  1450. 0, /*tp_dict */
  1451. 0, /*tp_descr_get */
  1452. 0, /*tp_descr_set */
  1453. 0, /*tp_dictoffset */
  1454. 0, /*tp_init */
  1455. 0, /*tp_alloc */
  1456. notimplemented_new, /*tp_new */
  1457. };
  1458. PyObject _Py_NotImplementedStruct = {
  1459. _PyObject_EXTRA_INIT
  1460. 1, &_PyNotImplemented_Type
  1461. };
  1462. void
  1463. _Py_ReadyTypes(void)
  1464. {
  1465. if (PyType_Ready(&PyBaseObject_Type) < 0)
  1466. Py_FatalError("Can't initialize object type");
  1467. if (PyType_Ready(&PyType_Type) < 0)
  1468. Py_FatalError("Can't initialize type type");
  1469. if (PyType_Ready(&_PyWeakref_RefType) < 0)
  1470. Py_FatalError("Can't initialize weakref type");
  1471. if (PyType_Ready(&_PyWeakref_CallableProxyType) < 0)
  1472. Py_FatalError("Can't initialize callable weakref proxy type");
  1473. if (PyType_Ready(&_PyWeakref_ProxyType) < 0)
  1474. Py_FatalError("Can't initialize weakref proxy type");
  1475. if (PyType_Ready(&PyLong_Type) < 0)
  1476. Py_FatalError("Can't initialize int type");
  1477. if (PyType_Ready(&PyBool_Type) < 0)
  1478. Py_FatalError("Can't initialize bool type");
  1479. if (PyType_Ready(&PyByteArray_Type) < 0)
  1480. Py_FatalError("Can't initialize bytearray type");
  1481. if (PyType_Ready(&PyBytes_Type) < 0)
  1482. Py_FatalError("Can't initialize 'str'");
  1483. if (PyType_Ready(&PyList_Type) < 0)
  1484. Py_FatalError("Can't initialize list type");
  1485. if (PyType_Ready(&_PyNone_Type) < 0)
  1486. Py_FatalError("Can't initialize None type");
  1487. if (PyType_Ready(&_PyNotImplemented_Type) < 0)
  1488. Py_FatalError("Can't initialize NotImplemented type");
  1489. if (PyType_Ready(&PyTraceBack_Type) < 0)
  1490. Py_FatalError("Can't initialize traceback type");
  1491. if (PyType_Ready(&PySuper_Type) < 0)
  1492. Py_FatalError("Can't initialize super type");
  1493. if (PyType_Ready(&PyRange_Type) < 0)
  1494. Py_FatalError("Can't initialize range type");
  1495. if (PyType_Ready(&PyDict_Type) < 0)
  1496. Py_FatalError("Can't initialize dict type");
  1497. if (PyType_Ready(&PyDictKeys_Type) < 0)
  1498. Py_FatalError("Can't initialize dict keys type");
  1499. if (PyType_Ready(&PyDictValues_Type) < 0)
  1500. Py_FatalError("Can't initialize dict values type");
  1501. if (PyType_Ready(&PyDictItems_Type) < 0)
  1502. Py_FatalError("Can't initialize dict items type");
  1503. if (PyType_Ready(&PyODict_Type) < 0)
  1504. Py_FatalError("Can't initialize OrderedDict type");
  1505. if (PyType_Ready(&PyODictKeys_Type) < 0)
  1506. Py_FatalError("Can't initialize odict_keys type");
  1507. if (PyType_Ready(&PyODictItems_Type) < 0)
  1508. Py_FatalError("Can't initialize odict_items type");
  1509. if (PyType_Ready(&PyODictValues_Type) < 0)
  1510. Py_FatalError("Can't initialize odict_values type");
  1511. if (PyType_Ready(&PyODictIter_Type) < 0)
  1512. Py_FatalError("Can't initialize odict_keyiterator type");
  1513. if (PyType_Ready(&PySet_Type) < 0)
  1514. Py_FatalError("Can't initialize set type");
  1515. if (PyType_Ready(&PyUnicode_Type) < 0)
  1516. Py_FatalError("Can't initialize str type");
  1517. if (PyType_Ready(&PySlice_Type) < 0)
  1518. Py_FatalError("Can't initialize slice type");
  1519. if (PyType_Ready(&PyStaticMethod_Type) < 0)
  1520. Py_FatalError("Can't initialize static method type");
  1521. if (PyType_Ready(&PyComplex_Type) < 0)
  1522. Py_FatalError("Can't initialize complex type");
  1523. if (PyType_Ready(&PyFloat_Type) < 0)
  1524. Py_FatalError("Can't initialize float type");
  1525. if (PyType_Ready(&PyFrozenSet_Type) < 0)
  1526. Py_FatalError("Can't initialize frozenset type");
  1527. if (PyType_Ready(&PyProperty_Type) < 0)
  1528. Py_FatalError("Can't initialize property type");
  1529. if (PyType_Ready(&_PyManagedBuffer_Type) < 0)
  1530. Py_FatalError("Can't initialize managed buffer type");
  1531. if (PyType_Ready(&PyMemoryView_Type) < 0)
  1532. Py_FatalError("Can't initialize memoryview type");
  1533. if (PyType_Ready(&PyTuple_Type) < 0)
  1534. Py_FatalError("Can't initialize tuple type");
  1535. if (PyType_Ready(&PyEnum_Type) < 0)
  1536. Py_FatalError("Can't initialize enumerate type");
  1537. if (PyType_Ready(&PyReversed_Type) < 0)
  1538. Py_FatalError("Can't initialize reversed type");
  1539. if (PyType_Ready(&PyStdPrinter_Type) < 0)
  1540. Py_FatalError("Can't initialize StdPrinter");
  1541. if (PyType_Ready(&PyCode_Type) < 0)
  1542. Py_FatalError("Can't initialize code type");
  1543. if (PyType_Ready(&PyFrame_Type) < 0)
  1544. Py_FatalError("Can't initialize frame type");
  1545. if (PyType_Ready(&PyCFunction_Type) < 0)
  1546. Py_FatalError("Can't initialize builtin function type");
  1547. if (PyType_Ready(&PyMethod_Type) < 0)
  1548. Py_FatalError("Can't initialize method type");
  1549. if (PyType_Ready(&PyFunction_Type) < 0)
  1550. Py_FatalError("Can't initialize function type");
  1551. if (PyType_Ready(&PyDictProxy_Type) < 0)
  1552. Py_FatalError("Can't initialize dict proxy type");
  1553. if (PyType_Ready(&PyGen_Type) < 0)
  1554. Py_FatalError("Can't initialize generator type");
  1555. if (PyType_Ready(&PyGetSetDescr_Type) < 0)
  1556. Py_FatalError("Can't initialize get-set descriptor type");
  1557. if (PyType_Ready(&PyWrapperDescr_Type) < 0)
  1558. Py_FatalError("Can't initialize wrapper type");
  1559. if (PyType_Ready(&_PyMethodWrapper_Type) < 0)
  1560. Py_FatalError("Can't initialize method wrapper type");
  1561. if (PyType_Ready(&PyEllipsis_Type) < 0)
  1562. Py_FatalError("Can't initialize ellipsis type");
  1563. if (PyType_Ready(&PyMemberDescr_Type) < 0)
  1564. Py_FatalError("Can't initialize member descriptor type");
  1565. if (PyType_Ready(&_PyNamespace_Type) < 0)
  1566. Py_FatalError("Can't initialize namespace type");
  1567. if (PyType_Ready(&PyCapsule_Type) < 0)
  1568. Py_FatalError("Can't initialize capsule type");
  1569. if (PyType_Ready(&PyLongRangeIter_Type) < 0)
  1570. Py_FatalError("Can't initialize long range iterator type");
  1571. if (PyType_Ready(&PyCell_Type) < 0)
  1572. Py_FatalError("Can't initialize cell type");
  1573. if (PyType_Ready(&PyInstanceMethod_Type) < 0)
  1574. Py_FatalError("Can't initialize instance method type");
  1575. if (PyType_Ready(&PyClassMethodDescr_Type) < 0)
  1576. Py_FatalError("Can't initialize class method descr type");
  1577. if (PyType_Ready(&PyMethodDescr_Type) < 0)
  1578. Py_FatalError("Can't initialize method descr type");
  1579. if (PyType_Ready(&PyCallIter_Type) < 0)
  1580. Py_FatalError("Can't initialize call iter type");
  1581. if (PyType_Ready(&PySeqIter_Type) < 0)
  1582. Py_FatalError("Can't initialize sequence iterator type");
  1583. if (PyType_Ready(&PyCoro_Type) < 0)
  1584. Py_FatalError("Can't initialize coroutine type");
  1585. if (PyType_Ready(&_PyCoroWrapper_Type) < 0)
  1586. Py_FatalError("Can't initialize coroutine wrapper type");
  1587. }
  1588. #ifdef Py_TRACE_REFS
  1589. void
  1590. _Py_NewReference(PyObject *op)
  1591. {
  1592. _Py_INC_REFTOTAL;
  1593. op->ob_refcnt = 1;
  1594. _Py_AddToAllObjects(op, 1);
  1595. _Py_INC_TPALLOCS(op);
  1596. }
  1597. void
  1598. _Py_ForgetReference(PyObject *op)
  1599. {
  1600. #ifdef SLOW_UNREF_CHECK
  1601. PyObject *p;
  1602. #endif
  1603. if (op->ob_refcnt < 0)
  1604. Py_FatalError("UNREF negative refcnt");
  1605. if (op == &refchain ||
  1606. op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op) {
  1607. fprintf(stderr, "* ob\n");
  1608. _PyObject_Dump(op);
  1609. fprintf(stderr, "* op->_ob_prev->_ob_next\n");
  1610. _PyObject_Dump(op->_ob_prev->_ob_next);
  1611. fprintf(stderr, "* op->_ob_next->_ob_prev\n");
  1612. _PyObject_Dump(op->_ob_next->_ob_prev);
  1613. Py_FatalError("UNREF invalid object");
  1614. }
  1615. #ifdef SLOW_UNREF_CHECK
  1616. for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
  1617. if (p == op)
  1618. break;
  1619. }
  1620. if (p == &refchain) /* Not found */
  1621. Py_FatalError("UNREF unknown object");
  1622. #endif
  1623. op->_ob_next->_ob_prev = op->_ob_prev;
  1624. op->_ob_prev->_ob_next = op->_ob_next;
  1625. op->_ob_next = op->_ob_prev = NULL;
  1626. _Py_INC_TPFREES(op);
  1627. }
  1628. void
  1629. _Py_Dealloc(PyObject *op)
  1630. {
  1631. destructor dealloc = Py_TYPE(op)->tp_dealloc;
  1632. _Py_ForgetReference(op);
  1633. (*dealloc)(op);
  1634. }
  1635. /* Print all live objects. Because PyObject_Print is called, the
  1636. * interpreter must be in a healthy state.
  1637. */
  1638. void
  1639. _Py_PrintReferences(FILE *fp)
  1640. {
  1641. PyObject *op;
  1642. fprintf(fp, "Remaining objects:\n");
  1643. for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
  1644. fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt);
  1645. if (PyObject_Print(op, fp, 0) != 0)
  1646. PyErr_Clear();
  1647. putc('\n', fp);
  1648. }
  1649. }
  1650. /* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
  1651. * doesn't make any calls to the Python C API, so is always safe to call.
  1652. */
  1653. void
  1654. _Py_PrintReferenceAddresses(FILE *fp)
  1655. {
  1656. PyObject *op;
  1657. fprintf(fp, "Remaining object addresses:\n");
  1658. for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
  1659. fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op,
  1660. op->ob_refcnt, Py_TYPE(op)->tp_name);
  1661. }
  1662. PyObject *
  1663. _Py_GetObjects(PyObject *self, PyObject *args)
  1664. {
  1665. int i, n;
  1666. PyObject *t = NULL;
  1667. PyObject *res, *op;
  1668. if (!PyArg_ParseTuple(args, "i|O", &n, &t))
  1669. return NULL;
  1670. op = refchain._ob_next;
  1671. res = PyList_New(0);
  1672. if (res == NULL)
  1673. return NULL;
  1674. for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
  1675. while (op == self || op == args || op == res || op == t ||
  1676. (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) {
  1677. op = op->_ob_next;
  1678. if (op == &refchain)
  1679. return res;
  1680. }
  1681. if (PyList_Append(res, op) < 0) {
  1682. Py_DECREF(res);
  1683. return NULL;
  1684. }
  1685. op = op->_ob_next;
  1686. }
  1687. return res;
  1688. }
  1689. #endif
  1690. /* Hack to force loading of abstract.o */
  1691. Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
  1692. void
  1693. _PyObject_DebugTypeStats(FILE *out)
  1694. {
  1695. _PyCFunction_DebugMallocStats(out);
  1696. _PyDict_DebugMallocStats(out);
  1697. _PyFloat_DebugMallocStats(out);
  1698. _PyFrame_DebugMallocStats(out);
  1699. _PyList_DebugMallocStats(out);
  1700. _PyMethod_DebugMallocStats(out);
  1701. _PyTuple_DebugMallocStats(out);
  1702. }
  1703. /* These methods are used to control infinite recursion in repr, str, print,
  1704. etc. Container objects that may recursively contain themselves,
  1705. e.g. builtin dictionaries and lists, should use Py_ReprEnter() and
  1706. Py_ReprLeave() to avoid infinite recursion.
  1707. Py_ReprEnter() returns 0 the first time it is called for a particular
  1708. object and 1 every time thereafter. It returns -1 if an exception
  1709. occurred. Py_ReprLeave() has no return value.
  1710. See dictobject.c and listobject.c for examples of use.
  1711. */
  1712. int
  1713. Py_ReprEnter(PyObject *obj)
  1714. {
  1715. PyObject *dict;
  1716. PyObject *list;
  1717. Py_ssize_t i;
  1718. dict = PyThreadState_GetDict();
  1719. /* Ignore a missing thread-state, so that this function can be called
  1720. early on startup. */
  1721. if (dict == NULL)
  1722. return 0;
  1723. list = _PyDict_GetItemId(dict, &PyId_Py_Repr);
  1724. if (list == NULL) {
  1725. list = PyList_New(0);
  1726. if (list == NULL)
  1727. return -1;
  1728. if (_PyDict_SetItemId(dict, &PyId_Py_Repr, list) < 0)
  1729. return -1;
  1730. Py_DECREF(list);
  1731. }
  1732. i = PyList_GET_SIZE(list);
  1733. while (--i >= 0) {
  1734. if (PyList_GET_ITEM(list, i) == obj)
  1735. return 1;
  1736. }
  1737. if (PyList_Append(list, obj) < 0)
  1738. return -1;
  1739. return 0;
  1740. }
  1741. void
  1742. Py_ReprLeave(PyObject *obj)
  1743. {
  1744. PyObject *dict;
  1745. PyObject *list;
  1746. Py_ssize_t i;
  1747. PyObject *error_type, *error_value, *error_traceback;
  1748. PyErr_Fetch(&error_type, &error_value, &error_traceback);
  1749. dict = PyThreadState_GetDict();
  1750. if (dict == NULL)
  1751. goto finally;
  1752. list = _PyDict_GetItemId(dict, &PyId_Py_Repr);
  1753. if (list == NULL || !PyList_Check(list))
  1754. goto finally;
  1755. i = PyList_GET_SIZE(list);
  1756. /* Count backwards because we always expect obj to be list[-1] */
  1757. while (--i >= 0) {
  1758. if (PyList_GET_ITEM(list, i) == obj) {
  1759. PyList_SetSlice(list, i, i + 1, NULL);
  1760. break;
  1761. }
  1762. }
  1763. finally:
  1764. /* ignore exceptions because there is no way to report them. */
  1765. PyErr_Restore(error_type, error_value, error_traceback);
  1766. }
  1767. /* Trashcan support. */
  1768. /* Current call-stack depth of tp_dealloc calls. */
  1769. int _PyTrash_delete_nesting = 0;
  1770. /* List of objects that still need to be cleaned up, singly linked via their
  1771. * gc headers' gc_prev pointers.
  1772. */
  1773. PyObject *_PyTrash_delete_later = NULL;
  1774. /* Add op to the _PyTrash_delete_later list. Called when the current
  1775. * call-stack depth gets large. op must be a currently untracked gc'ed
  1776. * object, with refcount 0. Py_DECREF must already have been called on it.
  1777. */
  1778. void
  1779. _PyTrash_deposit_object(PyObject *op)
  1780. {
  1781. assert(PyObject_IS_GC(op));
  1782. assert(_PyGC_REFS(op) == _PyGC_REFS_UNTRACKED);
  1783. assert(op->ob_refcnt == 0);
  1784. _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
  1785. _PyTrash_delete_later = op;
  1786. }
  1787. /* The equivalent API, using per-thread state recursion info */
  1788. void
  1789. _PyTrash_thread_deposit_object(PyObject *op)
  1790. {
  1791. PyThreadState *tstate = PyThreadState_GET();
  1792. assert(PyObject_IS_GC(op));
  1793. assert(_PyGC_REFS(op) == _PyGC_REFS_UNTRACKED);
  1794. assert(op->ob_refcnt == 0);
  1795. _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *) tstate->trash_delete_later;
  1796. tstate->trash_delete_later = op;
  1797. }
  1798. /* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
  1799. * the call-stack unwinds again.
  1800. */
  1801. void
  1802. _PyTrash_destroy_chain(void)
  1803. {
  1804. while (_PyTrash_delete_later) {
  1805. PyObject *op = _PyTrash_delete_later;
  1806. destructor dealloc = Py_TYPE(op)->tp_dealloc;
  1807. _PyTrash_delete_later =
  1808. (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
  1809. /* Call the deallocator directly. This used to try to
  1810. * fool Py_DECREF into calling it indirectly, but
  1811. * Py_DECREF was already called on this object, and in
  1812. * assorted non-release builds calling Py_DECREF again ends
  1813. * up distorting allocation statistics.
  1814. */
  1815. assert(op->ob_refcnt == 0);
  1816. ++_PyTrash_delete_nesting;
  1817. (*dealloc)(op);
  1818. --_PyTrash_delete_nesting;
  1819. }
  1820. }
  1821. /* The equivalent API, using per-thread state recursion info */
  1822. void
  1823. _PyTrash_thread_destroy_chain(void)
  1824. {
  1825. PyThreadState *tstate = PyThreadState_GET();
  1826. while (tstate->trash_delete_later) {
  1827. PyObject *op = tstate->trash_delete_later;
  1828. destructor dealloc = Py_TYPE(op)->tp_dealloc;
  1829. tstate->trash_delete_later =
  1830. (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
  1831. /* Call the deallocator directly. This used to try to
  1832. * fool Py_DECREF into calling it indirectly, but
  1833. * Py_DECREF was already called on this object, and in
  1834. * assorted non-release builds calling Py_DECREF again ends
  1835. * up distorting allocation statistics.
  1836. */
  1837. assert(op->ob_refcnt == 0);
  1838. ++tstate->trash_delete_nesting;
  1839. (*dealloc)(op);
  1840. --tstate->trash_delete_nesting;
  1841. }
  1842. }
  1843. #ifndef Py_TRACE_REFS
  1844. /* For Py_LIMITED_API, we need an out-of-line version of _Py_Dealloc.
  1845. Define this here, so we can undefine the macro. */
  1846. #undef _Py_Dealloc
  1847. PyAPI_FUNC(void) _Py_Dealloc(PyObject *);
  1848. void
  1849. _Py_Dealloc(PyObject *op)
  1850. {
  1851. _Py_INC_TPFREES(op) _Py_COUNT_ALLOCS_COMMA
  1852. (*Py_TYPE(op)->tp_dealloc)(op);
  1853. }
  1854. #endif
  1855. #ifdef __cplusplus
  1856. }
  1857. #endif