Commit Graph

258 Commits

Author SHA1 Message Date
Tim Peters 7571a0fbcf Improved new Py_TRACE_REFS gimmicks.
Arranged that all the objects exposed by __builtin__ appear in the list
of all objects.  I basically peed away two days tracking down a mystery
leak in sys.gettotalrefcount() in a ZODB app (== tons of code), because
the object leaking the references didn't appear in the sys.getobjects(0)
list.  The object happened to be False.  Now False is in the list, along
with other popular & previously missing leak candidates (like None).
Alas, we still don't have a choke point covering *all* Python objects,
so the list of all objects may still be incomplete.
2003-03-23 17:52:28 +00:00
Tim Peters 36eb4dfb81 Refactored some of the Py_TRACE_REFS code. New private API function
_Py_AddToAllObjects() that simply inserts an object at the front of
the doubly-linked list of all objects.  Changed PyType_Ready() (the
 closest thing we've got to a choke point for type objects) to call
that.
2003-03-23 03:33:13 +00:00
Tim Peters 3e40c7ff5b Oops! Used a wrong preprocessor symbol. 2003-03-23 03:04:32 +00:00
Tim Peters 78be7993b6 When Py_TRACE_REFS is defined, a list of all live objects is maintained in
a doubly-linked list, exposed by sys.getobjects().  Unfortunately, it's not
really all live objects, and it seems my fate to bump into programs where
sys.gettotalrefcount() keeps going up but where the reference leaks aren't
accounted for by anything in the list of all objects.

This patch helps a little:  if COUNT_ALLOCS is also defined, from now on
type objects will also appear in this list, provided at least one object
of a type has been allocated.
2003-03-23 02:51:01 +00:00
Raymond Hettinger 1da1dbf458 Renamed PyObject_GenericGetIter to PyObject_SelfIter
to more accurately describe what the function does.

Suggested by Thomas Wouters.
2003-03-17 19:46:11 +00:00
Raymond Hettinger 0153826964 Created PyObject_GenericGetIter().
Factors out the common case of returning self.
2003-03-17 08:24:35 +00:00
Guido van Rossum 90195e2616 PyObject_Generic{Get,Set}Attr:
Don't access tp_descr_{get,set} of a descriptor without checking the
flag bits of the descriptor's type.  While we know that the main type
(the type of the object whose attribute is being accessed) has all the
right flag bits (or else PyObject_Generic{Get,Set}Attr wouldn't be
called), we don't know that for its class attributes!

Will backport to 2.2.
2003-02-19 03:19:29 +00:00
Guido van Rossum fb50d3ffa1 default_3way_compare(): use PyNumber_Check(), rather than testing for
tp_as_number directly.
2003-02-18 16:40:09 +00:00
Tim Peters 18e7083cda SF bug 681122: Built-in function dir() causes refcount leak in baseclasses.
merge_class_dict():  This was missing a decref.

Bugfix candidate.
2003-02-05 19:35:19 +00:00
Tim Peters 4440f22e98 Recursive compare machinery: The code that intended to exempt tuples
was broken because new-in-2.3 code added a tp_as_mapping slot to tuples.
Repaired that.

Added basic docs to check_recursion().

The code that intended to exempt tuples and strings was also broken here,
and in 2.2:  these should use PyXYZ_CheckExact(), not PyXYZ_Check() -- we
can't know whether subclass instances are immutable.  This part (and this
part alone) is a bugfix candidate.
2003-01-20 16:54:59 +00:00
Neal Norwitz 1a9975014f Fix SF bug #667147, Segmentation fault printing str subclass
Fix infinite recursion which occurred when printing an object
whose __str__() returned self.

Will backport
2003-01-13 20:13:12 +00:00
Neil Schemenauer 89350a41b9 Remove _Py_ResetReferences. Fixes bug #529750 "Circular reference makes
Py_Init crash".  refchain cannot be cleared because objects can live across
Py_Finalize() and Py_Initialize() if they are kept alive by circular
references.
2002-11-17 17:52:44 +00:00
Guido van Rossum 6e08c1460c PyObject_Init[Var] is almost always called from the PyObject_NEW[_VAR]
macros.  The 'op' argument is then the result from PyObject_MALLOC,
and that can of course be NULL.  In that case, PyObject_Init[Var]
would raise a SystemError with "NULL object passed to
PyObject_Init[Var]".  But there's nothing the caller of the macro can
do about this.  So PyObject_Init[Var] should call just PyErr_NoMemory.

Will backport.
2002-10-11 20:37:24 +00:00
Guido van Rossum 6248f441ea Speedup for PyObject_IsTrue(): check for True and False first.
Because all built-in tests return bools now, this is the most common
path!
2002-08-24 06:31:34 +00:00
Guido van Rossum 81912d4764 Speedup for PyObject_RichCompareBool(): PyObject_RichCompare() almost
always returns a bool, so avoid calling PyObject_IsTrue() in that
case.
2002-08-24 05:33:28 +00:00
Guido van Rossum 056fbf422d Another modest speedup in PyObject_GenericGetAttr(): inline the call
to _PyType_Lookup().
2002-08-19 19:22:50 +00:00
Guido van Rossum c66ff4441e Inline call to _PyObject_GetDictPtr() in PyObject_GenericGetAttr().
This causes a modest speedup.
2002-08-19 16:50:48 +00:00
Martin v. Löwis 3f19b10ca5 Replace abort with Py_FatalError. 2002-08-07 16:21:51 +00:00
Mark Hammond a290527376 Excise DL_IMPORT/EXPORT from object.h, and related files. This patch
also adds 'extern' to PyAPI_DATA rather than at each declaration, as
discussed with Tim and Guido.
2002-07-29 13:42:14 +00:00
Tim Peters 3459251d5a object.h special-build macro minefield: renamed all the new lexical
helper macros to something saner, and used them appropriately in other
files too, to reduce #ifdef blocks.

classobject.c, instance_dealloc():  One of my worst Python Memories is
trying to fix this routine a few years ago when COUNT_ALLOCS was defined
but Py_TRACE_REFS wasn't.  The special-build code here is way too
complicated.  Now it's much simpler.  Difference:  in a Py_TRACE_REFS
build, the instance is no longer in the doubly-linked list of live
objects while its __del__ method is executing, and that may be visible
via sys.getobjects() called from a __del__ method.  Tough -- the object
is presumed dead while its __del__ is executing anyway, and not calling
_Py_NewReference() at the start allows enormous code simplification.

typeobject.c, call_finalizer():  The special-build instance_dealloc()
pain apparently spread to here too via cut-'n-paste, and this is much
simpler now too.  In addition, I didn't understand why this routine
was calling _PyObject_GC_TRACK() after a resurrection, since there's no
plausible way _PyObject_GC_UNTRACK() could have been called on the
object by this point.  I suspect it was left over from pasting the
instance_delloc() code.  Instead asserted that the object is still
tracked.  Caution:  I suspect we don't have a test that actually
exercises the subtype_dealloc() __del__-resurrected-me code.
2002-07-11 06:23:50 +00:00
Tim Peters 7c321a80f9 The Py_REF_DEBUG/COUNT_ALLOCS/Py_TRACE_REFS macro minefield: added
more trivial lexical helper macros so that uses of these guys expand
to nothing at all when they're not enabled.  This should help sub-
standard compilers that can't do a good job of optimizing away the
previous "(void)0" expressions.

Py_DECREF:  There's only one definition of this now.  Yay!  That
was that last one in the family defined multiple times in an #ifdef
maze.

Py_FatalError():  Changed the char* signature to const char*.

_Py_NegativeRefcount():  New helper function for the Py_REF_DEBUG
expansion of Py_DECREF.  Calling an external function cuts down on
the volume of generated code.  The previous inline expansion of abort()
didn't work as intended on Windows (the program often kept going, and
the error msg scrolled off the screen unseen).  _Py_NegativeRefcount
calls Py_FatalError instead, which captures our best knowledge of
how to abort effectively across platforms.
2002-07-09 02:57:01 +00:00
Tim Peters c6a3ff634a SF bug 578752: COUNT_ALLOCS vs heap types
Repair segfaults and infinite loops in COUNT_ALLOCS builds in the
presence of new-style (heap-allocated) classes/types.

Bugfix candidate.  I'll backport this to 2.2.  It's irrelevant in 2.1.
2002-07-08 22:11:52 +00:00
Tim Peters 4be93d0e84 Rearranged and added comments to object.h, to clarify many things
that have taken me "too long" to reverse-engineer over the years.
Vastly reduced the nesting level and redundancy of #ifdef-ery.
Took a light stab at repairing comments that are no longer true.

sys_gettotalrefcount():  Changed to enable under Py_REF_DEBUG.
It was enabled under Py_TRACE_REFS, which was much heavier than
necessary.  sys.gettotalrefcount() is now available in a
Py_REF_DEBUG-only build.
2002-07-07 19:59:50 +00:00
Tim Peters a6269a8ec5 Removed 3 unlikely #includes that were only needed for the non-gc flavor
of the trashcan code.
2002-07-07 16:52:50 +00:00
Tim Peters 803526b9e2 Trashcan cleanup: Now that cyclic gc is always there, the trashcan
mechanism is no longer evil:  it no longer plays dangerous games with
the type pointer or refcounts, and objects in extension modules can play
along too without needing to edit the core first.

Rewrote all the comments to explain this, and (I hope) give clear
guidance to extension authors who do want to play along.  Documented
all the functions.  Added more asserts (it may no longer be evil, but
it's still dangerous <0.9 wink>).  Rearranged the generated code to
make it clearer, and to tolerate either the presence or absence of a
semicolon after the macros.  Rewrote _PyTrash_destroy_chain() to call
tp_dealloc directly; it was doing a Py_DECREF again, and that has all
sorts of obscure distorting effects in non-release builds (Py_DECREF
was already called on the object!).  Removed Christian's little "embedded
change log" comments -- that's what checkin messages are for, and since
it was impossible to correlate the comments with the code that changed,
I found them merely distracting.
2002-07-07 05:13:56 +00:00
Tim Peters 943382c8e5 Removed WITH_CYCLE_GC #ifdef-ery. Holes:
+ I'm not sure what to do about configure.in.  Left it alone.

+ Ditto pyexpat.c.  Fred or Martin will know what to do.
2002-07-07 03:59:34 +00:00
Neal Norwitz 4178515035 SF # 533070 Silence AIX C Compiler Warnings
Warning caused by using &func.  & is not necessary.
2002-06-13 21:42:51 +00:00
Neal Norwitz 51290d369d SF # 561244 Micro optimizations
Cleanup code a bit and return as early as possible.
2002-06-13 21:32:44 +00:00
Neal Norwitz 3f8dae73c7 Fix typo 2002-05-31 20:23:33 +00:00
Guido van Rossum a407300cd7 Implement the intention of SF patch 472523 (but coded differently).
In the past, an object's tp_compare could return any value.  In 2.2
the docs were tightened to require it to return -1, 0 or 1; and -1 for
an error.

We now issue a warning if the value is not in this range.  When an
exception is raised, we allow -1 or -2 as return value, since -2 will
the recommended return value for errors in the future.  (Eventually
tp_compare will also be allowed to return +2, to indicate
NotImplemented; but that can only be implemented once we know all
extensions return a value in [-2...1].  Or perhaps it will require the
type to set a flag bit.)

I haven't decided yet whether to backport this to 2.2.x.  The patch
applies fine.  But is it fair to start warning in 2.2.2 about code
that worked flawlessly in 2.2.1?
2002-05-31 20:03:54 +00:00
Guido van Rossum cacfc07d08 - A new type object, 'string', is added. This is a common base type
for 'str' and 'unicode', and can be used instead of
  types.StringTypes, e.g. to test whether something is "a string":
  isinstance(x, string) is True for Unicode and 8-bit strings.  This
  is an abstract base class and cannot be instantiated directly.
2002-05-24 19:01:59 +00:00
Guido van Rossum 4402241450 Jim Fulton reported a segfault in dir(). A heavily proxied object
returned a proxy for __class__ whose __bases__ was also a proxy.  The
merge_class_dict() helper for dir() assumed incorrectly that __bases__
would always be a tuple and used the in-line tuple API on the proxy.

I will backport this to 2.2 as well.
2002-05-13 18:29:46 +00:00
Guido van Rossum 517c7d4fd3 PyNumber_CoerceEx: this took a shortcut (not doing anything) when the
left and right type were of the same type and not classic instances.

This shortcut is dangerous for proxy types, because it means that
coerce(Proxy(1), Proxy(2.1)) leaves Proxy(1) unchanged rather than
turning it into Proxy(1.0).

In an ever-so-slight change of semantics, I now only take the shortcut
when the left and right types are of the same type and don't have the
CHECKTYPES feature.  It so happens that classic instances have this
flag, so the shortcut is still skipped in this case (i.e. nothing
changes for classic instances).  Proxies also have this flag set
(otherwise implementing numeric operations on proxies would become
nightmarish) and this means that the shortcut is also skipped there,
as desired.  It so happens that int, long and float also have this
flag set; that means that e.g. coerce(1, 1) will now invoke
int_coerce().  This is fine: int_coerce() can deal with this, and I'm
not worried about the performance; int_coerce() is only invoked when
the user explicitly calls coerce(), which should be rarer than rare.
2002-04-26 02:49:14 +00:00
Tim Peters af3e8de580 First stab at rationalizing the PyMem_ API. Mixing PyObject_xyz with
PyMem_{Del, DEL} doesn't work yet (compilation problems).

pyport.h:  _PyMem_EXTRA is gone.

pmem.h:  Repaired comments.  PyMem_{Malloc, MALLOC} and
PyMem_{Realloc, REALLOC} now make the same x-platform guarantees when
asking for 0 bytes, and when passing a NULL pointer to the latter.

object.c:  PyMem_{Malloc, Realloc} just call their macro versions
now, since the latter take care of the x-platform 0 and NULL stuff
by themselves now.

pypcre.c, grow_stack():  So sue me.  On two lines, this called
PyMem_RESIZE to grow a "const" area.  It's not legit to realloc a
const area, so the compiler warned given the new expansion of
PyMem_RESIZE.  It would have gotten the same warning before if it
had used PyMem_Resize() instead; the older macro version, but not the
function version, silently cast away the constness.  IMO that was a wrong
thing to do, and the docs say the macro versions of PyMem_xyz are
deprecated anyway.  If somebody else is resizing const areas with the
macro spelling, they'll get a warning when they recompile now too.
2002-04-12 07:22:56 +00:00
Neil Schemenauer bdf0eedb68 Move PyObject_Malloc and PyObject_Free to obmalloc.c. 2002-04-12 03:08:42 +00:00
Guido van Rossum 77f6a65eb0 Add the 'bool' type and its values 'False' and 'True', as described in
PEP 285.  Everything described in the PEP is here, and there is even
some documentation.  I had to fix 12 unit tests; all but one of these
were printing Boolean outcomes that changed from 0/1 to False/True.
(The exception is test_unicode.py, which did a type(x) == type(y)
style comparison.  I could've fixed that with a single line using
issubtype(x, type(y)), but instead chose to be explicit about those
places where a bool is expected.

Still to do: perhaps more documentation; change standard library
modules to return False/True from predicates.
2002-04-03 22:41:51 +00:00
Neil Schemenauer f589c059f4 If the GC is enabled then don't use the ob_type pointer to create a list
of trash objects.  Use the gc_prev pointer instead.
2002-03-29 03:05:54 +00:00
Tim Peters 1221c0a435 Build obmalloc.c directly instead of #include'ing from object.c.
Also move all _PyMalloc_XXX entry points into obmalloc.c.

The Windows build works fine.
The Unix build is changed here (Makefile.pre.in), but not tested.
No other platform's build process has been fiddled.
2002-03-23 00:20:15 +00:00
Neil Schemenauer a1a9c51a3e Add pymalloc object memory management functions. These must be
available even if pymalloc is disabled since extension modules might use
them.
2002-03-22 15:28:30 +00:00
Neil Schemenauer 25f3dc21b5 Drop the PyCore_* memory API. 2002-03-18 21:06:21 +00:00
Martin v. Löwis 0c160a08f2 Patch #517521: Consider byte strings before Unicode strings
in PyObject_Get/SetAttr.
2002-03-15 13:40:30 +00:00
Tim Peters a5d78cc208 Whether platform malloc(0) returns NULL has nothing to do with whether
platform realloc(p, 0) returns NULL, so MALLOC_ZERO_RETURNS_NULL can
be correctly undefined yet realloc(p, 0) can return NULL anyway.

Prevent realloc(p, 0) doing free(p) and returning NULL via a different
hack.  Would probably be better to get rid of MALLOC_ZERO_RETURNS_NULL
entirely.

Bugfix candidate.
2002-03-02 08:43:19 +00:00
Guido van Rossum 2eb0b87d14 SF patch 514641 (Naofumi Honda) - Negative ob_size of LongObjects
Due to the bizarre definition of _PyLong_Copy(), creating an instance
of a subclass of long with a negative value could cause core dumps
later on.  Unfortunately it looks like the behavior of _PyLong_Copy()
is quite intentional, so the fix is more work than feels comfortable.

This fix is almost, but not quite, the code that Naofumi Honda added;
in addition, I added a test case.
2002-03-01 22:24:49 +00:00
Guido van Rossum ebca9fc1ba PyObject_Generic{Get,Set}Attr(): ensure that the attribute name is a
string object (or a Unicode that's trivially converted to ASCII).

PyObject_GetAttr(): add an 'else' to the Unicode test like
PyObject_SetAttr() already has.
2001-12-04 15:54:53 +00:00
Tim Peters 67754e993e Rehabilitated the fast-path richcmp code, and sped it up. It wasn't
helping for types that defined tp_richcmp but not tp_compare, although
that's when it's most valuable, and strings moved into that category
since the fast path was first introduced.  Now it helps for same-type
non-Instance objects that define rich or 3-way compares.

For all the edits here, the rest just amounts to moving the fast path from
do_richcmp into PyObject_RichCompare, saving a layer of function call
(measurable on my box!).  This loses when NESTING_LIMIT is exceeded, but I
don't care about that (fast-paths are for normal cases, not pathologies).

Also added a tasteful <wink> label to get out of PyObject_RichCompare, as
the if/else nesting in this routine was getting incomprehensible.
2001-11-04 07:29:31 +00:00
Tim Peters c99213f993 No code change -- just trying to document the return conditions for all
the internal comparison routines.
2001-11-04 05:57:16 +00:00
Jeremy Hylton 39a362d9f4 cleanup indentation 2001-10-22 16:30:36 +00:00
Guido van Rossum b8c65bc27f SF patch #470578: Fixes to synchronize unicode() and str()
This patch implements what we have discussed on python-dev late in
    September: str(obj) and unicode(obj) should behave similar, while
    the old behaviour is retained for unicode(obj, encoding, errors).

    The patch also adds a new feature with which objects can provide
    unicode(obj) with input data: the __unicode__ method. Currently no
    new tp_unicode slot is implemented; this is left as option for the
    future.

    Note that PyUnicode_FromEncodedObject() no longer accepts Unicode
    objects as input. The API name already suggests that Unicode
    objects do not belong in the list of acceptable objects and the
    functionality was only needed because
    PyUnicode_FromEncodedObject() was being used directly by
    unicode(). The latter was changed in the discussed way:

    * unicode(obj) calls PyObject_Unicode()
    * unicode(obj, encoding, errors) calls PyUnicode_FromEncodedObject()

    One thing left open to discussion is whether to leave the
    PyUnicode_FromObject() API as a thin API extension on top of
    PyUnicode_FromEncodedObject() or to turn it into a (macro) alias
    for PyObject_Unicode() and deprecate it. Doing so would have some
    surprising consequences though, e.g.  u"abc" + 123 would turn out
    as u"abc123"...

[Marc-Andre didn't have time to check this in before the deadline.  I
hope this is OK, Marc-Andre!  You can still make changes and commit
them on the trunk after the branch has been made, but then please mail
Barry a context diff if you want the change to be merged into the
2.2b1 release branch.  GvR]
2001-10-19 02:01:31 +00:00
Tim Peters c993315b18 SF bug [#468061] __str__ ignored in str subclass.
object.c, PyObject_Str:  Don't try to optimize anything except exact
string objects here; in particular, let str subclasses go thru tp_str,
same as non-str objects.  This allows overrides of tp_str to take
effect.

stringobject.c:
+ string_print (str's tp_print):  If the argument isn't an exact string
  object, get one from PyObject_Str.

+ string_str (str's tp_str):  Make a genuine-string copy of the object if
  it's of a proper str subclass type.  str() applied to a str subclass
  that doesn't override __str__ ends up here.

test_descr.py:  New str_of_str_subclass() test.
2001-10-16 20:18:24 +00:00
Tim Peters f2a67daca2 Guido suggests, and I agree, to insist that SIZEOF_VOID_P be a power of 2.
This simplifies the rounding in _PyObject_VAR_SIZE, allows to restore the
pre-rounding calling sequence, and allows some nice little simplifications
in its callers.  I'm still making it return a size_t, though.
2001-10-07 03:54:51 +00:00
Tim Peters 6d483d3477 _PyObject_VAR_SIZE: always round up to a multiple-of-pointer-size value.
As Guido suggested, this makes the new subclassing code substantially
simpler.  But the mechanics of doing it w/ C macro semantics are a mess,
and _PyObject_VAR_SIZE has a new calling sequence now.

Question:  The PyObject_NEW_VAR macro appears to be part of the public API.
Regardless of what it expands to, the notion that it has to round up the
memory it allocates is new, and extensions containing the old
PyObject_NEW_VAR macro expansion (which was embedded in the
PyObject_NEW_VAR expansion) won't do this rounding.  But the rounding
isn't actually *needed* except for new-style instances with dict pointers
after a variable-length blob of embedded data.  So my guess is that we do
not need to bump the API version for this (as the rounding isn't needed
for anything an extension can do unless it's recompiled anyway).  What's
your guess?
2001-10-06 21:27:34 +00:00
Tim Peters 7254e5a3ed _PyObject_GetDictPtr():
+ Use the _PyObject_VAR_SIZE macro to compute object size.
+ Break the computation into lines convenient for debugger inspection.
+ Speed the round-up-to-pointer-size computation.
2001-10-06 17:45:17 +00:00
Fred Drake b3f0d349b6 PyObject_ClearWeakRefs() is now a real function instead of a function pointer;
the implementation is in Objects/weakrefobject.c.
2001-10-05 21:58:11 +00:00
Guido van Rossum 2ed6bf87c9 Merge branch changes (coercion, rich comparisons) into trunk. 2001-09-27 20:30:07 +00:00
Guido van Rossum dd4d1c4f5d _PyObject_GetDictPtr(): when the offset is negative, always align --
we can't trust that tp_basicsize is aligned.  Fixes SF bug #462848.
2001-09-20 13:38:22 +00:00
Guido van Rossum ab3b0343b8 Hopefully fix 3-way comparisons. This unfortunately adds yet another
hack, and it's even more disgusting than a PyInstance_Check() call.
If the tp_compare slot is the slot used for overrides in Python,
it's always called.

Add some tests that show what should work too.
2001-09-18 20:38:53 +00:00
Tim Peters 305b5857f6 PyObject_Dir(): Merge in __members__ and __methods__ too (if they exist,
and are lists, and then just the string elements (if any)).

There are good and bad reasons for this.  The good reason is to support
dir() "like before" on objects of extension types that haven't migrated
to the class introspection API yet.  The bad reason is that Python's own
method objects are such a type, and this is the quickest way to get their
im_self etc attrs to "show up" via dir().  It looks much messier to move
them to the new scheme, as their current getattr implementation presents
a view of their attrs that's a untion of their own attrs plus their
im_func's attrs.  In particular, methodobject.__dict__ actually returns
methodobject.im_func.__dict__, and if that's important to preserve it
doesn't seem to fit the class introspection model at all.
2001-09-17 02:38:46 +00:00
Tim Peters bc7e863ce2 merge_class_dict(): Clear the error if __bases__ doesn't exist. 2001-09-16 20:33:22 +00:00
Guido van Rossum 5f5512d246 _PyObject_Dump(): print the type of the object. This is by far the
most frequently interesting information IMO.  Also tidy up the output.
2001-09-14 15:50:08 +00:00
Tim Peters 5a49ade70e More on SF bug [#460020] bug or feature: unicode() and subclasses.
Repaired str(i) to return a genuine string when i is an instance of a str
subclass.  New PyString_CheckExact() macro.
2001-09-11 01:41:59 +00:00
Guido van Rossum 8dbd3d8c50 PyObject_Dir():
- use PyModule_Check() instead of PyObject_TypeCheck(), now we can.
  - don't assert that the __dict__ gotten out of a module is always
    a dictionary; check its type, and raise an exception if it's not.
2001-09-10 18:27:43 +00:00
Tim Peters 7eea37e831 At Guido's suggestion, here's a new C API function, PyObject_Dir(), like
__builtin__.dir().  Moved the guts from bltinmodule.c to object.c.
2001-09-04 22:08:56 +00:00
Guido van Rossum 393661d15f Add warning mode for classic division, almost exactly as specified in
PEP 238.  Changes:

- add a new flag variable Py_DivisionWarningFlag, declared in
  pydebug.h, defined in object.c, set in main.c, and used in
  {int,long,float,complex}object.c.  When this flag is set, the
  classic division operator issues a DeprecationWarning message.

- add a new API PyRun_SimpleStringFlags() to match
  PyRun_SimpleString().  The main() function calls this so that
  commands run with -c can also benefit from -Dnew.

- While I was at it, I changed the usage message in main() somewhat:
  alphabetized the options, split it in *four* parts to fit in under
  512 bytes (not that I still believe this is necessary -- doc strings
  elsewhere are much longer), and perhaps most visibly, don't display
  the full list of options on each command line error.  Instead, the
  full list is only displayed when -h is used, and otherwise a brief
  reminder of -h is displayed.  When -h is used, write to stdout so
  that you can do `python -h | more'.

Notes:

- I don't want to use the -W option to control whether the classic
  division warning is issued or not, because the machinery to decide
  whether to display the warning or not is very expensive (it involves
  calling into the warnings.py module).  You can use -Werror to turn
  the warnings into exceptions though.

- The -Dnew option doesn't select future division for all of the
  program -- only for the __main__ module.  I don't know if I'll ever
  change this -- it would require changes to the .pyc file magic
  number to do it right, and a more global notion of compiler flags.

- You can usefully combine -Dwarn and -Dnew: this gives the __main__
  module new division, and warns about classic division everywhere
  else.
2001-08-31 17:40:15 +00:00
Guido van Rossum 21922aa939 PyObject_Repr(): add missing ">" back at end of format string: "<%s
object at %p>".
2001-08-30 20:26:05 +00:00
Neil Schemenauer fd34369ecb Remove GC related code. It lives in gcmodule now. 2001-08-29 23:54:03 +00:00
Barry Warsaw 7ce3694a52 repr's converted to using PyString_FromFormat() instead of sprintf'ing
into a hardcoded char* buffer.

Closes patch #454743.
2001-08-24 18:34:26 +00:00
Martin v. Löwis 339d0f720e Patch #445762: Support --disable-unicode
- Do not compile unicodeobject, unicodectype, and unicodedata if Unicode is disabled
- check for Py_USING_UNICODE in all places that use Unicode functions
- disables unicode literals, and the builtin functions
- add the types.StringTypes list
- remove Unicode literals from most tests.
2001-08-17 18:39:25 +00:00
Guido van Rossum ba21a49f9d Add a function _Py_ReadyTypes() which initializes various and sundry
types -- currently Type, List, None and NotImplemented.  To be called
from Py_Initialize() instead of accumulating calls there.

Also rename type(None) to NoneType and type(NotImplemented) to
NotImplementedType -- naming the type identical to the object was
confusing.
2001-08-16 08:17:26 +00:00
Guido van Rossum 82fc51c19c Update to MvL's patch #424475 to avoid returning 2 when tp_compare
returns that.  (This fix is also by MvL; checkin it in because I want
to make more changes here.  I'm still not 100% satisfied -- see
comments attached to the patch.)
2001-08-16 08:02:45 +00:00
Guido van Rossum 528b7eb0b0 - Rename PyType_InitDict() to PyType_Ready().
- Add an explicit call to PyType_Ready(&PyList_Type) to pythonrun.c
  (just for the heck of it, really -- we should either explicitly
  ready all types, or none).
2001-08-07 17:24:28 +00:00
Tim Peters 6d6c1a35e0 Merge of descr-branch back into trunk. 2001-08-02 04:15:00 +00:00
Jeremy Hylton 3ce45389bd Add _PyUnicode_AsDefaultEncodedString to unicodeobject.h.
And remove all the extern decls in the middle of .c files.
Apparently, it was excluded from the header file because it is
intended for internal use by the interpreter.  It's still intended for
internal use and documented as such in the header file.
2001-07-30 22:34:24 +00:00
Guido van Rossum 3c29602d74 _Py_GetObjects(): GCC suggests to add () around && within || for some
code only compiled in debug mode, and I dutifully comply.
2001-07-14 17:58:00 +00:00
Martin v. Löwis 0163d6d6ef Patch #424475: Speed-up tp_compare usage, by special-casing the common
case of objects with equal types which support tp_compare. Give
type objects a tp_compare function.
Also add c<0 tests before a few PyErr_Occurred tests.
2001-06-09 07:34:05 +00:00
Tim Peters 5acbfcc164 Cosmetic: code under "else" clause was missing indent. 2001-05-11 03:36:45 +00:00
Tim Peters 6d60b2e762 SF bug #422108 - Error in rich comparisons.
2.1.1 bugfix candidate too.
Fix a bad (albeit unlikely) return value in try_rich_to_3way_compare().
Also document do_cmp()'s return values.
2001-05-07 20:53:51 +00:00
Tim Peters de9725f135 Make 'x in y' and 'x not in y' (PySequence_Contains) play nice w/ iterators.
NEEDS DOC CHANGES
A few more AttributeErrors turned into TypeErrors, but in test_contains
this time.
The full story for instance objects is pretty much unexplainable, because
instance_contains() tries its own flavor of iteration-based containment
testing first, and PySequence_Contains doesn't get a chance at it unless
instance_contains() blows up.  A consequence is that
    some_complex_number in some_instance
dies with a TypeError unless some_instance.__class__ defines __iter__ but
does not define __getitem__.
2001-05-05 10:06:17 +00:00
Fred Drake 6aebded915 The weakref support in PyObject_InitVar() as well; this should have come out
at the same time as it did from PyObject_Init() .
2001-05-03 20:04:33 +00:00
Fred Drake ba40ec42c8 Remove unnecessary intialization for the case of weakly-referencable objects;
the code necessary to accomplish this is simpler and faster if confined to
the object implementations, so we only do this there.

This causes no behaviorial changes beyond a (very slight) speedup.
2001-05-03 19:44:50 +00:00
Guido van Rossum 4f288ab7d6 Printing objects to a real file still wasn't done right: if the
object's type didn't define tp_print, there were still cases where the
full "print uses str() which falls back to repr()" semantics weren't
honored.  This resulted in

    >>> print None
    <None object at 0x80bd674>
    >>> print type(u'')
    <type object at 0x80c0a80>

Fixed this by always using the appropriate PyObject_Repr() or
PyObject_Str() call, rather than trying to emulate what they would do.

Also simplified PyObject_Str() to always fall back on PyObject_Repr()
when tp_str is not defined (rather than making an extra check for
instances with a __str__ method).  And got rid of the special case for
strings.
2001-05-01 16:53:37 +00:00
Guido van Rossum 3a80c4a29c (Adding this to the trunk as well.)
Fix a very old flaw in PyObject_Print().  Amazing!  When an object
type defines tp_str but not tp_repr, 'print x' to a real file
object would not call the tp_str slot but rather print a default style
representation: <foo object at 0x....>.  This even though 'print x' to
a file-like-object would correctly call the tp_str slot.
2001-04-27 21:35:01 +00:00
Marc-André Lemburg ae605341e3 Fixed ref count bug. Patch #411191. Found by Walter Dörwald. 2001-03-25 19:16:13 +00:00
Neil Schemenauer a35c688055 Add Vladimir Marangozov's object allocator. It is disabled by default. This
closes SF patch #401229.
2001-02-27 04:45:05 +00:00
Fred Drake b60654bc15 The return value from PyObject_ClearWeakRefs() is no longer meaningful,
so make it void.
2001-02-26 18:56:37 +00:00
Barry Warsaw eefb107a48 _PyObject_Dump(): If argument is NULL, print "NULL" instead of
crashing.
2001-02-22 22:39:18 +00:00
Guido van Rossum 2da0ea82ba In try_3way_to_rich_compare(), swap the call to default_3way_compare()
and the test for errors, so that an error in the default compare
doesn't go undetected.  This fixes SF Bug #132933 (submitted by
effbot) -- list.sort doesn't detect comparision errors.
2001-02-22 22:18:04 +00:00
Fred Drake 41deb1efc2 PEP 205, Weak References -- initial checkin. 2001-02-01 05:27:45 +00:00
Guido van Rossum d1f06b9b2f Check the Py_TPFLAGS_HAVE_RICHCOMPARE flag before using the
tp_richcompare field!  (Hopefully this will make Python 2.1 binary
compatible with certain Zope extensions. :-)
2001-01-24 22:14:43 +00:00
Barry Warsaw bbd89b66b1 PyObject_Dump() -> _PyObject_Dump()
PyGC_Dump() -> _PyGC_Dump()
2001-01-24 04:18:13 +00:00
Barry Warsaw 903138f775 PyObject_Dump(): Use %p format to print the address of the pointer.
PyGC_Dump(): Wrap this in a #ifdef WITH_CYCLE_GC.
2001-01-23 16:33:18 +00:00
Barry Warsaw 9bf16440f4 A few miscellaneous helpers.
PyObject_Dump(): New function that is useful when debugging Python's C
runtime.  In something like gdb it can be a pain to get some useful
information out of PyObject*'s.  This function prints the str() of the
object to stderr, along with the object's refcount and hex address.

PyGC_Dump(): Similar to PyObject_Dump() but knows how to cast from the
garbage collector prefix back to the PyObject* structure.

[See Misc/gdbinit for some useful gdb hooks]

none_dealloc(): Rather than SEGV if we accidentally decref None out of
existance, we assign None's and NotImplemented's destructor slot to
this function, which just calls abort().
2001-01-23 16:24:35 +00:00
Guido van Rossum 0871e9315e New special case in comparisons: None is smaller than any other object
(unless the object's type overrides this comparison).
2001-01-22 19:28:09 +00:00
Guido van Rossum 8f9143da33 Once again, numeric-smelling objects compare smaller than non-numeric
ones.
2001-01-22 15:59:32 +00:00
Neil Schemenauer d38855c35a Remove a smelly export. 2001-01-21 16:25:18 +00:00
Barry Warsaw b0e754d488 Tim chastens:
Barry, that comment belongs in the code, not in the checkin msg.
    The code *used* to do this correctly (as you well know, since you
    & I went thru considerable pain to fix this the first time).
    However, because the *reason* for the convolution wasn't recorded
    in the code as a comment, somebody threw it all away the first
    time it got reworked.

    c-code-isn't-often-self-explanatory-ly y'rs  - tim

default_3way_compare(): Stick the checkin message from 2.110 in a
comment.
2001-01-20 06:24:55 +00:00
Barry Warsaw 71ff8d5dc5 default_3way_compare(): When comparing the pointers, they must be cast
to integer types (i.e. Py_uintptr_t, our spelling of C9X's uintptr_t).
ANSI specifies that pointer compares other than == and != to
non-related structures are undefined.  This quiets an Insure
portability warning.
2001-01-20 06:08:10 +00:00
Guido van Rossum 41c3244875 Rich comparisons fallout: PyObject_Hash() should check for both
tp_compare and tp_richcompare NULL before deciding to do a quickie
based on the object address.  (Tim Peters discovered this.)
2001-01-18 23:33:37 +00:00
Guido van Rossum a3af41d564 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...
2001-01-18 22:07:06 +00:00
Guido van Rossum 2ffbf6b112 Deal properly (?) with comparing recursive datastructures.
- Use the compare nesting level and in-progress dictionary properly in
  PyObject_RichCompare().

- Change the in-progress code to use static variables instead of
  globals (both the nesting level and the key for the thread dict were
  globals but have no reason to be globals; the key can even be a
  function-static variable in get_inprogress_dict()).

- Rewrote try_rich_to_3way_compare() to benefit from the similarity of
  the three cases, making it table-driven.

- In try_rich_to_3way_compare(), test for EQ before LT and GT.  This
  turns out essential when comparing recursive UserList instances;
  with the old code, these would recurse into rich comparison three
  times for each nesting level up to NESTING_LIMIT/2, making the total
  number of calls in the order of 3**(NESTING_LIMIT/2)!

NOTE: I'm not 100% comfortable with this.  It works for the standard
test suite (which compares a few trivial recursive data structures
only), but I'm not sure that the in-progress dictionary is used
properly by the rich comparison code.  Jeremy suggested that maybe the
operation should be included in the dict.  Currently I presume that
objects in the dict are equal unless proven otherwise, and I set the
outcome for the rich comparison accordingly: true for operators EQ,
LE, GE, and false for the other three.  But Jeremy seems to think that
there may be counter-examples where this doesn't do the right thing.
2001-01-17 21:27:02 +00:00
Marc-André Lemburg ad7c98e264 This patch adds a new builtin unistr() which behaves like str()
except that it always returns Unicode objects.

A new C API PyObject_Unicode() is also provided.

This closes patch #101664.

Written by Marc-Andre Lemburg. Copyright assigned to Guido van Rossum.
2001-01-17 17:09:53 +00:00