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.

2277 lines
64 KiB

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