Merged revisions 67654,67676-67677,67681,67692,67725,67761,67784-67785,67787-67788,67802,67848-67850,67862-67864,67880,67882 via svnmerge from

svn+ssh://pythondev@svn.python.org/python/trunk

........
  r67654 | georg.brandl | 2008-12-07 16:42:09 -0600 (Sun, 07 Dec 2008) | 2 lines

  #4457: rewrite __import__() documentation.
........
  r67676 | benjamin.peterson | 2008-12-08 20:03:03 -0600 (Mon, 08 Dec 2008) | 1 line

  specify how things are copied
........
  r67677 | benjamin.peterson | 2008-12-08 20:05:11 -0600 (Mon, 08 Dec 2008) | 1 line

  revert unrelated change to installer script
........
  r67681 | jeremy.hylton | 2008-12-09 15:03:10 -0600 (Tue, 09 Dec 2008) | 2 lines

  Add simple unittests for Request
........
  r67692 | amaury.forgeotdarc | 2008-12-10 18:03:42 -0600 (Wed, 10 Dec 2008) | 2 lines

  #1030250: correctly pass the dry_run option to the mkpath() function.
........
  r67725 | benjamin.peterson | 2008-12-12 22:02:20 -0600 (Fri, 12 Dec 2008) | 1 line

  fix incorrect example
........
  r67761 | benjamin.peterson | 2008-12-14 11:26:04 -0600 (Sun, 14 Dec 2008) | 1 line

  fix missing bracket
........
  r67784 | georg.brandl | 2008-12-15 02:33:58 -0600 (Mon, 15 Dec 2008) | 2 lines

  #4446: document "platforms" argument for setup().
........
  r67785 | georg.brandl | 2008-12-15 02:36:11 -0600 (Mon, 15 Dec 2008) | 2 lines

  #4611: fix typo.
........
  r67787 | georg.brandl | 2008-12-15 02:58:59 -0600 (Mon, 15 Dec 2008) | 2 lines

  #4578: fix has_key() usage in compiler package.
........
  r67788 | georg.brandl | 2008-12-15 03:07:39 -0600 (Mon, 15 Dec 2008) | 2 lines

  #4568: remove limitation in varargs callback example.
........
  r67802 | amaury.forgeotdarc | 2008-12-15 16:29:14 -0600 (Mon, 15 Dec 2008) | 4 lines

  #3632: the "pyo" macro from gdbinit can now run when the GIL is released.

  Patch by haypo.
........
  r67848 | benjamin.peterson | 2008-12-18 20:28:56 -0600 (Thu, 18 Dec 2008) | 1 line

  fix typo
........
  r67849 | benjamin.peterson | 2008-12-18 20:31:35 -0600 (Thu, 18 Dec 2008) | 1 line

  _call_method -> _callmethod and _get_value to _getvalue
........
  r67850 | raymond.hettinger | 2008-12-19 03:06:07 -0600 (Fri, 19 Dec 2008) | 9 lines

  Fix-up and clean-up docs for int.bit_length().

  * Replace dramatic footnote with in-line comment about possible round-off errors in logarithms of large numbers.
  * Add comments to the pure python code equivalent.
  * replace floor() with int() in the mathematical equivalent so the type is correct (should be an int, not a float).
  * add abs() to the mathematical equivalent so that it matches the previous line that it is supposed to be equivalent to.
  * make one combined example with a negative input.
........
  r67862 | benjamin.peterson | 2008-12-19 20:48:02 -0600 (Fri, 19 Dec 2008) | 1 line

  copy sentence from docstring
........
  r67863 | benjamin.peterson | 2008-12-19 20:51:26 -0600 (Fri, 19 Dec 2008) | 1 line

  add headings
........
  r67864 | benjamin.peterson | 2008-12-19 20:57:19 -0600 (Fri, 19 Dec 2008) | 1 line

  beef up docstring
........
  r67880 | benjamin.peterson | 2008-12-20 16:49:24 -0600 (Sat, 20 Dec 2008) | 1 line

  remove redundant sentence
........
  r67882 | benjamin.peterson | 2008-12-20 16:59:49 -0600 (Sat, 20 Dec 2008) | 1 line

  add some recent releases to the list
........
This commit is contained in:
Benjamin Peterson 2008-12-21 00:06:59 +00:00
parent f767050cdc
commit 6ebe78f5cc
16 changed files with 168 additions and 93 deletions

View File

@ -561,6 +561,8 @@ This information includes:
+----------------------+---------------------------+-----------------+--------+ +----------------------+---------------------------+-----------------+--------+
| ``classifiers`` | a list of classifiers | list of strings | \(4) | | ``classifiers`` | a list of classifiers | list of strings | \(4) |
+----------------------+---------------------------+-----------------+--------+ +----------------------+---------------------------+-----------------+--------+
| ``platforms`` | a list of platforms | list of strings | |
+----------------------+---------------------------+-----------------+--------+
Notes: Notes:

View File

@ -882,7 +882,7 @@ memory and should be avoided completely. [#]_
The advantage of borrowing over owning a reference is that you don't need to The advantage of borrowing over owning a reference is that you don't need to
take care of disposing of the reference on all possible paths through the code take care of disposing of the reference on all possible paths through the code
--- in other words, with a borrowed reference you don't run the risk of leaking --- in other words, with a borrowed reference you don't run the risk of leaking
when a premature exit is taken. The disadvantage of borrowing over leaking is when a premature exit is taken. The disadvantage of borrowing over owning is
that there are some subtle situations where in seemingly correct code a borrowed that there are some subtle situations where in seemingly correct code a borrowed
reference can be used after the owner from which it was borrowed has in fact reference can be used after the owner from which it was borrowed has in fact
disposed of it. disposed of it.

View File

@ -677,11 +677,10 @@ indexes at which certain conditions are met::
if line.strip() == '': if line.strip() == '':
print('Blank line at line #%i' % i) print('Blank line at line #%i' % i)
``sorted(iterable, [key=None], [reverse=False])`` collects all the elements of
``sorted(iterable, [cmp=None], [key=None], [reverse=False)`` collects all the the iterable into a list, sorts the list, and returns the sorted result. The
elements of the iterable into a list, sorts the list, and returns the sorted ``key``, and ``reverse`` arguments are passed through to the constructed list's
result. The ``cmp``, ``key``, and ``reverse`` arguments are passed through to ``.sort()`` method. ::
the constructed list's ``.sort()`` method. ::
>>> import random >>> import random
>>> # Generate 8 random numbers between [0, 10000) >>> # Generate 8 random numbers between [0, 10000)

View File

@ -1172,47 +1172,64 @@ are always available. They are listed here in alphabetical order.
This is an advanced function that is not needed in everyday Python This is an advanced function that is not needed in everyday Python
programming. programming.
The function is invoked by the :keyword:`import` statement. It mainly exists This function is invoked by the :keyword:`import` statement. It can be
so that you can replace it with another function that has a compatible replaced (by importing the :mod:`builtins` module and assigning to
interface, in order to change the semantics of the :keyword:`import` ``builtins.__import__``) in order to change semantics of the
statement. See the built-in module :mod:`imp`, which defines some useful :keyword:`import` statement, but nowadays it is usually simpler to use import
operations out of which you can build your own :func:`__import__` function. hooks (see :pep:`302`). Direct use of :func:`__import__` is rare, except in
cases where you want to import a module whose name is only known at runtime.
For example, the statement ``import spam`` results in the following call: The function imports the module *name*, potentially using the given *globals*
``__import__('spam', globals(), locals(), [], -1)``; the statement and *locals* to determine how to interpret the name in a package context.
``from spam.ham import eggs`` results in ``__import__('spam.ham', globals(), The *fromlist* gives the names of objects or submodules that should be
locals(), ['eggs'], -1)``. Note that even though ``locals()`` and ``['eggs']`` imported from the module given by *name*. The standard implementation does
are passed in as arguments, the :func:`__import__` function does not set the not use its *locals* argument at all, and uses its *globals* only to
local variable named ``eggs``; this is done by subsequent code that is generated determine the package context of the :keyword:`import` statement.
for the import statement. (In fact, the standard implementation does not use
its *locals* argument at all, and uses its *globals* only to determine the *level* specifies whether to use absolute or relative imports. The default
package context of the :keyword:`import` statement.) is ``-1`` which indicates both absolute and relative imports will be
attempted. ``0`` means only perform absolute imports. Positive values for
*level* indicate the number of parent directories to search relative to the
directory of the module calling :func:`__import__`.
When the *name* variable is of the form ``package.module``, normally, the When the *name* variable is of the form ``package.module``, normally, the
top-level package (the name up till the first dot) is returned, *not* the top-level package (the name up till the first dot) is returned, *not* the
module named by *name*. However, when a non-empty *fromlist* argument is module named by *name*. However, when a non-empty *fromlist* argument is
given, the module named by *name* is returned. This is done for given, the module named by *name* is returned.
compatibility with the :term:`bytecode` generated for the different kinds of import
statement; when using ``import spam.ham.eggs``, the top-level package
:mod:`spam` must be placed in the importing namespace, but when using ``from
spam.ham import eggs``, the ``spam.ham`` subpackage must be used to find the
``eggs`` variable. As a workaround for this behavior, use :func:`getattr` to
extract the desired components. For example, you could define the following
helper::
def my_import(name): For example, the statement ``import spam`` results in bytecode resembling the
mod = __import__(name) following code::
components = name.split('.')
for comp in components[1:]: spam = __import__('spam', globals(), locals(), [], -1)
mod = getattr(mod, comp)
return mod
*level* specifies whether to use absolute or relative imports. The default is The statement ``import spam.ham`` results in this call::
``-1`` which indicates both absolute and relative imports will be attempted.
``0`` means only perform absolute imports. Positive values for *level* indicate
the number of parent directories to search relative to the directory of the
module calling :func:`__import__`.
spam = __import__('spam.ham', globals(), locals(), [], -1)
Note how :func:`__import__` returns the toplevel module here because this is
the object that is bound to a name by the :keyword:`import` statement.
On the other hand, the statement ``from spam.ham import eggs, sausage as
saus`` results in ::
_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], -1)
eggs = _temp.eggs
saus = _temp.sausage
Here, the ``spam.ham`` module is returned from :func:`__import__`. From this
object, the names to import are retrieved and assigned to their respective
names.
If you simply want to import a module (potentially within a package) by name,
you can get it from :data:`sys.modules`::
>>> import sys
>>> name = 'foo.bar.baz'
>>> __import__(name)
<module 'foo' from ...>
>>> baz = sys.modules[name]
>>> baz
<module 'foo.bar.baz' from ...>
.. rubric:: Footnotes .. rubric:: Footnotes

View File

@ -21,8 +21,9 @@ was generated in the first place.
The following functions are provided by this module. Except when explicitly The following functions are provided by this module. Except when explicitly
noted otherwise, all return values are floats. noted otherwise, all return values are floats.
Number-theoretic and representation functions:
Number-theoretic and representation functions
---------------------------------------------
.. function:: ceil(x) .. function:: ceil(x)
@ -110,8 +111,8 @@ Number-theoretic and representation functions:
.. function:: modf(x) .. function:: modf(x)
Return the fractional and integer parts of *x*. Both results carry the sign of Return the fractional and integer parts of *x*. Both results carry the sign
*x*, and both are floats. of *x* and are floats.
.. function:: trunc(x) .. function:: trunc(x)
@ -131,7 +132,9 @@ Python floats typically carry no more than 53 bits of precision (the same as the
platform C double type), in which case any float *x* with ``abs(x) >= 2**52`` platform C double type), in which case any float *x* with ``abs(x) >= 2**52``
necessarily has no fractional bits. necessarily has no fractional bits.
Power and logarithmic functions:
Power and logarithmic functions
-------------------------------
.. function:: exp(x) .. function:: exp(x)
@ -169,7 +172,8 @@ Power and logarithmic functions:
Return the square root of *x*. Return the square root of *x*.
Trigonometric functions: Trigonometric functions
-----------------------
.. function:: acos(x) .. function:: acos(x)
@ -217,7 +221,8 @@ Trigonometric functions:
Return the tangent of *x* radians. Return the tangent of *x* radians.
Angular conversion: Angular conversion
------------------
.. function:: degrees(x) .. function:: degrees(x)
@ -229,7 +234,8 @@ Angular conversion:
Converts angle *x* from degrees to radians. Converts angle *x* from degrees to radians.
Hyperbolic functions: Hyperbolic functions
--------------------
.. function:: acosh(x) .. function:: acosh(x)
@ -262,9 +268,8 @@ Hyperbolic functions:
Return the hyperbolic tangent of *x*. Return the hyperbolic tangent of *x*.
Constants
The module also defines two mathematical constants: =========
.. data:: pi .. data:: pi

View File

@ -1436,13 +1436,13 @@ itself. This means, for example, that one shared object can contain a second::
Proxy objects are instances of subclasses of :class:`BaseProxy`. Proxy objects are instances of subclasses of :class:`BaseProxy`.
.. method:: _call_method(methodname[, args[, kwds]]) .. method:: _callmethod(methodname[, args[, kwds]])
Call and return the result of a method of the proxy's referent. Call and return the result of a method of the proxy's referent.
If ``proxy`` is a proxy whose referent is ``obj`` then the expression :: If ``proxy`` is a proxy whose referent is ``obj`` then the expression ::
proxy._call_method(methodname, args, kwds) proxy._callmethod(methodname, args, kwds)
will evaluate the expression :: will evaluate the expression ::
@ -1455,26 +1455,26 @@ itself. This means, for example, that one shared object can contain a second::
argument of :meth:`BaseManager.register`. argument of :meth:`BaseManager.register`.
If an exception is raised by the call, then then is re-raised by If an exception is raised by the call, then then is re-raised by
:meth:`_call_method`. If some other exception is raised in the manager's :meth:`_callmethod`. If some other exception is raised in the manager's
process then this is converted into a :exc:`RemoteError` exception and is process then this is converted into a :exc:`RemoteError` exception and is
raised by :meth:`_call_method`. raised by :meth:`_callmethod`.
Note in particular that an exception will be raised if *methodname* has Note in particular that an exception will be raised if *methodname* has
not been *exposed* not been *exposed*
An example of the usage of :meth:`_call_method`:: An example of the usage of :meth:`_callmethod`::
>>> l = manager.list(range(10)) >>> l = manager.list(range(10))
>>> l._call_method('__len__') >>> l._callmethod('__len__')
10 10
>>> l._call_method('__getslice__', (2, 7)) # equiv to `l[2:7]` >>> l._callmethod('__getslice__', (2, 7)) # equiv to `l[2:7]`
[2, 3, 4, 5, 6] [2, 3, 4, 5, 6]
>>> l._call_method('__getitem__', (20,)) # equiv to `l[20]` >>> l._callmethod('__getitem__', (20,)) # equiv to `l[20]`
Traceback (most recent call last): Traceback (most recent call last):
... ...
IndexError: list index out of range IndexError: list index out of range
.. method:: _get_value() .. method:: _getvalue()
Return a copy of the referent. Return a copy of the referent.

View File

@ -1625,36 +1625,33 @@ directly).
Nevertheless, here's a stab at a callback for an option with variable Nevertheless, here's a stab at a callback for an option with variable
arguments:: arguments::
def vararg_callback(option, opt_str, value, parser): def vararg_callback(option, opt_str, value, parser):
assert value is None assert value is None
done = 0 value = []
value = []
rargs = parser.rargs
while rargs:
arg = rargs[0]
# Stop if we hit an arg like "--foo", "-a", "-fx", "--file=f", def floatable(str):
# etc. Note that this also stops on "-3" or "-3.0", so if try:
# your option takes numeric values, you will need to handle float(str)
# this. return True
if ((arg[:2] == "--" and len(arg) > 2) or except ValueError:
(arg[:1] == "-" and len(arg) > 1 and arg[1] != "-")): return False
break
else:
value.append(arg)
del rargs[0]
setattr(parser.values, option.dest, value) for arg in parser.rargs:
# stop on --foo like options
if arg[:2] == "--" and len(arg) > 2:
break
# stop on -a, but not on -3 or -3.0
if arg[:1] == "-" and len(arg) > 1 and not floatable(arg):
break
value.append(arg)
del parser.rargs[:len(value)]
setattr(parser.values, option.dest, value))
[...] [...]
parser.add_option("-c", "--callback", dest="vararg_attr", parser.add_option("-c", "--callback", dest="vararg_attr",
action="callback", callback=vararg_callback) action="callback", callback=vararg_callback)
The main weakness with this particular implementation is that negative numbers
in the arguments following ``"-c"`` will be interpreted as further options
(probably causing an error), rather than as arguments to ``"-c"``. Fixing this
is left as an exercise for the reader.
.. _optparse-extending-optparse: .. _optparse-extending-optparse:

View File

@ -139,7 +139,7 @@ copying and removal. For operations on individual files, see also the
Recursively move a file or directory to another location. Recursively move a file or directory to another location.
If the destination is on the current filesystem, then simply use rename. If the destination is on the current filesystem, then simply use rename.
Otherwise, copy src to the dst and then remove src. Otherwise, copy src (with :func:`copy2`) to the dst and then remove src.
.. exception:: Error .. exception:: Error

View File

@ -52,10 +52,10 @@ The variables defined in the :mod:`signal` module are:
.. data:: SIG_DFL .. data:: SIG_DFL
This is one of two standard signal handling options; it will simply perform the This is one of two standard signal handling options; it will simply perform
default function for the signal. For example, on most systems the default the default function for the signal. For example, on most systems the
action for :const:`SIGQUIT` is to dump core and exit, while the default action default action for :const:`SIGQUIT` is to dump core and exit, while the
for :const:`SIGCLD` is to simply ignore it. default action for :const:`SIGCHLD` is to simply ignore it.
.. data:: SIG_IGN .. data:: SIG_IGN

View File

@ -442,7 +442,7 @@ Additional Methods on Integer Types
Equivalent to:: Equivalent to::
def bit_length(self): def bit_length(self):
s = bin(self) # binary representation: bin(-37) --> '-0b100101' s = bin(x) # binary representation: bin(-37) --> '-0b100101'
s = s.lstrip('-0b') # remove leading zeros and minus sign s = s.lstrip('-0b') # remove leading zeros and minus sign
return len(s) # len('100101') --> 6 return len(s) # len('100101') --> 6

View File

@ -738,7 +738,7 @@ The formatting template uses curly brackets (`{`, `}`) as special characters::
Curly brackets can be escaped by doubling them:: Curly brackets can be escaped by doubling them::
>>> format("Empty dict: {{}}") >>> "Empty dict: {{}}".format()
"Empty dict: {}" "Empty dict: {}"
Field names can be integers indicating positional arguments, such as Field names can be integers indicating positional arguments, such as

View File

@ -55,7 +55,10 @@ the various releases.
2.4.4 2.4.3 2006 PSF yes 2.4.4 2.4.3 2006 PSF yes
2.5 2.4 2006 PSF yes 2.5 2.4 2006 PSF yes
2.5.1 2.5 2007 PSF yes 2.5.1 2.5 2007 PSF yes
2.5.2 2.5.1 2008 PSF yes
2.5.3 2.5.2 2008 PSF yes
2.6 2.5 2008 PSF yes 2.6 2.5 2008 PSF yes
2.6.1 2.6 2008 PSF yes
3.0 2.6 2008 PSF yes 3.0 2.6 2008 PSF yes
Footnotes: Footnotes:

View File

@ -984,8 +984,8 @@ main (int argc, char **argv) {
def move_file(self, src, dst): def move_file(self, src, dst):
return move_file(src, dst, dry_run=self.dry_run) return move_file(src, dst, dry_run=self.dry_run)
def mkpath(self, name, mode=0o777): def mkpath (self, name, mode=0o777):
mkpath(name, mode, self.dry_run) mkpath(name, mode, dry_run=self.dry_run)
# Map a sys.platform/os.name ('posix', 'nt') to the default compiler # Map a sys.platform/os.name ('posix', 'nt') to the default compiler

View File

@ -1104,6 +1104,51 @@ class MiscTests(unittest.TestCase):
else: else:
self.assert_(False) self.assert_(False)
class RequestTests(unittest.TestCase):
def setUp(self):
self.get = Request("http://www.python.org/~jeremy/")
self.post = Request("http://www.python.org/~jeremy/",
"data",
headers={"X-Test": "test"})
def test_method(self):
self.assertEqual("POST", self.post.get_method())
self.assertEqual("GET", self.get.get_method())
def test_add_data(self):
self.assert_(not self.get.has_data())
self.assertEqual("GET", self.get.get_method())
self.get.add_data("spam")
self.assert_(self.get.has_data())
self.assertEqual("POST", self.get.get_method())
def test_get_full_url(self):
self.assertEqual("http://www.python.org/~jeremy/",
self.get.get_full_url())
def test_selector(self):
self.assertEqual("/~jeremy/", self.get.get_selector())
req = Request("http://www.python.org/")
self.assertEqual("/", req.get_selector())
def test_get_type(self):
self.assertEqual("http", self.get.get_type())
def test_get_host(self):
self.assertEqual("www.python.org", self.get.get_host())
def test_get_host_unquote(self):
req = Request("http://www.%70ython.org/")
self.assertEqual("www.python.org", req.get_host())
def test_proxy(self):
self.assert_(not self.get.has_proxy())
self.get.set_proxy("www.perl.org", "http")
self.assert_(self.get.has_proxy())
self.assertEqual("www.python.org", self.get.get_origin_req_host())
self.assertEqual("www.perl.org", self.get.get_host())
def test_main(verbose=None): def test_main(verbose=None):
from test import test_urllib2 from test import test_urllib2
@ -1112,7 +1157,8 @@ def test_main(verbose=None):
tests = (TrivialTests, tests = (TrivialTests,
OpenerDirectorTests, OpenerDirectorTests,
HandlerTests, HandlerTests,
MiscTests) MiscTests,
RequestTests)
support.run_unittest(*tests) support.run_unittest(*tests)
if __name__ == "__main__": if __name__ == "__main__":

View File

@ -685,7 +685,10 @@ error:
return NULL; return NULL;
} }
PyDoc_STRVAR(math_factorial_doc, "Return n!"); PyDoc_STRVAR(math_factorial_doc,
"factorial(x) -> Integral\n"
"\n"
"Find x!. Raise a ValueError if x is negative or non-integral.");
static PyObject * static PyObject *
math_trunc(PyObject *self, PyObject *number) math_trunc(PyObject *self, PyObject *number)
@ -837,7 +840,7 @@ PyDoc_STRVAR(math_modf_doc,
"modf(x)\n" "modf(x)\n"
"\n" "\n"
"Return the fractional and integer parts of x. Both results carry the sign\n" "Return the fractional and integer parts of x. Both results carry the sign\n"
"of x. The integer part is returned as a real."); "of x and are floats.");
/* A decent logarithm is easy to compute even for huge longs, but libm can't /* A decent logarithm is easy to compute even for huge longs, but libm can't
do that by itself -- loghelper can. func is log or log10, and name is do that by itself -- loghelper can. func is log or log10, and name is

View File

@ -344,8 +344,11 @@ _PyObject_Dump(PyObject* op)
if (op == NULL) if (op == NULL)
fprintf(stderr, "NULL\n"); fprintf(stderr, "NULL\n");
else { else {
PyGILState_STATE gil;
fprintf(stderr, "object : "); fprintf(stderr, "object : ");
gil = PyGILState_Ensure();
(void)PyObject_Print(op, stderr, 0); (void)PyObject_Print(op, stderr, 0);
PyGILState_Release(gil);
/* XXX(twouters) cast refcount to long until %zd is /* XXX(twouters) cast refcount to long until %zd is
universally available */ universally available */
fprintf(stderr, "\n" fprintf(stderr, "\n"