Merged revisions 55407-55513 via svnmerge from

svn+ssh://pythondev@svn.python.org/python/branches/p3yk

................
  r55413 | fred.drake | 2007-05-17 12:30:10 -0700 (Thu, 17 May 2007) | 1 line

  fix argument name in documentation; match the implementation
................
  r55430 | jack.diederich | 2007-05-18 06:39:59 -0700 (Fri, 18 May 2007) | 1 line

  Implements class decorators, PEP 3129.
................
  r55432 | guido.van.rossum | 2007-05-18 08:09:41 -0700 (Fri, 18 May 2007) | 2 lines

  obsubmit.
................
  r55434 | guido.van.rossum | 2007-05-18 09:39:10 -0700 (Fri, 18 May 2007) | 3 lines

  Fix bug in test_inspect.  (I presume this is how it should be fixed;
  Jack Diedrich, please verify.)
................
  r55460 | brett.cannon | 2007-05-20 00:31:57 -0700 (Sun, 20 May 2007) | 4 lines

  Remove the imageop module.  With imgfile already removed in Python 3.0 and
  rgbimg gone in Python 2.6 the unit tests themselves were made worthless.  Plus
  third-party libraries perform the same function much better.
................
  r55469 | neal.norwitz | 2007-05-20 11:28:20 -0700 (Sun, 20 May 2007) | 118 lines

  Merged revisions 55324-55467 via svnmerge from
  svn+ssh://pythondev@svn.python.org/python/trunk

  ........
    r55348 | georg.brandl | 2007-05-15 13:19:34 -0700 (Tue, 15 May 2007) | 4 lines

    HTML-escape the plain traceback in cgitb's HTML output, to prevent
    the traceback inadvertently or maliciously closing the comment and
    injecting HTML into the error page.
  ........
    r55372 | neal.norwitz | 2007-05-15 21:33:50 -0700 (Tue, 15 May 2007) | 6 lines

    Port rev 55353 from Guido:
    Add what looks like a necessary call to PyErr_NoMemory() when PyMem_MALLOC()
    fails.

    Will backport.
  ........
    r55377 | neal.norwitz | 2007-05-15 22:06:33 -0700 (Tue, 15 May 2007) | 1 line

    Mention removal of some directories for obsolete platforms
  ........
    r55380 | brett.cannon | 2007-05-15 22:50:03 -0700 (Tue, 15 May 2007) | 2 lines

    Change the maintainer of the BeOS port.
  ........
    r55383 | georg.brandl | 2007-05-16 06:44:18 -0700 (Wed, 16 May 2007) | 2 lines

    Bug #1719995: don't use deprecated method in sets example.
  ........
    r55386 | neal.norwitz | 2007-05-16 13:05:11 -0700 (Wed, 16 May 2007) | 5 lines

    Fix bug in marshal where bad data would cause a segfault due to
    lack of an infinite recursion check.

    Contributed by Damien Miller at Google.
  ........
    r55389 | brett.cannon | 2007-05-16 15:42:29 -0700 (Wed, 16 May 2007) | 6 lines

    Remove the gopherlib module.  It has been raising a DeprecationWarning since
    Python 2.5.

    Also remove gopher support from urllib/urllib2.  As both imported gopherlib the
    usage of the support would have raised a DeprecationWarning.
  ........
    r55394 | raymond.hettinger | 2007-05-16 18:08:04 -0700 (Wed, 16 May 2007) | 1 line

    calendar.py gets no benefit from xrange() instead of range()
  ........
    r55395 | brett.cannon | 2007-05-16 19:02:56 -0700 (Wed, 16 May 2007) | 3 lines

    Complete deprecation of BaseException.message.  Some subclasses were directly
    accessing the message attribute instead of using the descriptor.
  ........
    r55396 | neal.norwitz | 2007-05-16 23:11:36 -0700 (Wed, 16 May 2007) | 4 lines

    Reduce the max stack depth to see if this fixes the segfaults on
    Windows and some other boxes.  If this is successful, this rev should
    be backported.  I'm not sure how close to the limit we should push this.
  ........
    r55397 | neal.norwitz | 2007-05-16 23:23:50 -0700 (Wed, 16 May 2007) | 4 lines

    Set the depth to something very small to try to determine if the
    crashes on Windows are really due to the stack size or possibly
    some other problem.
  ........
    r55398 | neal.norwitz | 2007-05-17 00:04:46 -0700 (Thu, 17 May 2007) | 4 lines

    Last try for tweaking the max stack depth.  5000 was the original value,
    4000 didn't work either.  1000 does work on Windows.  If 2000 works,
    that will hopefully be a reasonable balance.
  ........
    r55412 | fred.drake | 2007-05-17 12:29:58 -0700 (Thu, 17 May 2007) | 1 line

    fix argument name in documentation; match the implementation
  ........
    r55427 | neal.norwitz | 2007-05-17 22:47:16 -0700 (Thu, 17 May 2007) | 1 line

    Verify neither dumps or loads overflow the stack and segfault.
  ........
    r55446 | collin.winter | 2007-05-18 16:11:24 -0700 (Fri, 18 May 2007) | 1 line

    Backport PEP 3110's new 'except' syntax to 2.6.
  ........
    r55448 | raymond.hettinger | 2007-05-18 18:11:16 -0700 (Fri, 18 May 2007) | 1 line

    Improvements to NamedTuple's implementation, tests, and documentation
  ........
    r55449 | raymond.hettinger | 2007-05-18 18:50:11 -0700 (Fri, 18 May 2007) | 1 line

    Fix beginner mistake -- don't mix spaces and tabs.
  ........
    r55450 | neal.norwitz | 2007-05-18 20:48:47 -0700 (Fri, 18 May 2007) | 1 line

    Clear data so random memory does not get freed.  Will backport.
  ........
    r55452 | neal.norwitz | 2007-05-18 21:34:55 -0700 (Fri, 18 May 2007) | 3 lines

    Whoops, need to pay attention to those test failures.
    Move the clear to *before* the first use, not after.
  ........
    r55453 | neal.norwitz | 2007-05-18 21:35:52 -0700 (Fri, 18 May 2007) | 1 line

    Give some clue as to what happened if the test fails.
  ........
    r55455 | georg.brandl | 2007-05-19 11:09:26 -0700 (Sat, 19 May 2007) | 2 lines

    Fix docstring for add_package in site.py.
  ........
    r55458 | brett.cannon | 2007-05-20 00:09:50 -0700 (Sun, 20 May 2007) | 2 lines

    Remove the rgbimg module.  It has been deprecated since Python 2.5.
  ........
    r55465 | nick.coghlan | 2007-05-20 04:12:49 -0700 (Sun, 20 May 2007) | 1 line

    Fix typo in example (should be backported, but my maintenance branch is woefully out of date)
  ........
................
  r55472 | brett.cannon | 2007-05-20 12:06:18 -0700 (Sun, 20 May 2007) | 2 lines

  Remove imageop from the Windows build process.
................
  r55486 | neal.norwitz | 2007-05-20 23:59:52 -0700 (Sun, 20 May 2007) | 1 line

  Remove callable() builtin
................
  r55506 | neal.norwitz | 2007-05-22 00:43:29 -0700 (Tue, 22 May 2007) | 78 lines

  Merged revisions 55468-55505 via svnmerge from
  svn+ssh://pythondev@svn.python.org/python/trunk

  ........
    r55468 | neal.norwitz | 2007-05-20 11:06:27 -0700 (Sun, 20 May 2007) | 1 line

    rotor is long gone.
  ........
    r55470 | neal.norwitz | 2007-05-20 11:43:00 -0700 (Sun, 20 May 2007) | 1 line

    Update directories/files at the top-level.
  ........
    r55471 | brett.cannon | 2007-05-20 12:05:06 -0700 (Sun, 20 May 2007) | 2 lines

    Try to remove rgbimg from Windows builds.
  ........
    r55474 | brett.cannon | 2007-05-20 16:17:38 -0700 (Sun, 20 May 2007) | 4 lines

    Remove the macfs module.  This led to the deprecation of macostools.touched();
    it completely relied on macfs and is a no-op on OS X according to code
    comments.
  ........
    r55476 | brett.cannon | 2007-05-20 16:56:18 -0700 (Sun, 20 May 2007) | 3 lines

    Move imgfile import to the global namespace to trigger an import error ASAP to
    prevent creation of a test file.
  ........
    r55477 | brett.cannon | 2007-05-20 16:57:38 -0700 (Sun, 20 May 2007) | 3 lines

    Cause posixfile to raise a DeprecationWarning.  Documented as deprecated since
    Ptyhon 1.5.
  ........
    r55479 | andrew.kuchling | 2007-05-20 17:03:15 -0700 (Sun, 20 May 2007) | 1 line

    Note removed modules
  ........
    r55481 | martin.v.loewis | 2007-05-20 21:35:47 -0700 (Sun, 20 May 2007) | 2 lines

    Add Alexandre Vassalotti.
  ........
    r55482 | george.yoshida | 2007-05-20 21:41:21 -0700 (Sun, 20 May 2007) | 4 lines

    fix against r55474 [Remove the macfs module]

    Remove "libmacfs.tex" from Makefile.deps and mac/mac.tex.
  ........
    r55487 | raymond.hettinger | 2007-05-21 01:13:35 -0700 (Mon, 21 May 2007) | 1 line

    Replace assertion with straight error-checking.
  ........
    r55489 | raymond.hettinger | 2007-05-21 09:40:10 -0700 (Mon, 21 May 2007) | 1 line

    Allow all alphanumeric and underscores in type and field names.
  ........
    r55490 | facundo.batista | 2007-05-21 10:32:32 -0700 (Mon, 21 May 2007) | 5 lines


    Added timeout support to HTTPSConnection, through the
    socket.create_connection function. Also added a small
    test for this, and updated NEWS file.
  ........
    r55495 | georg.brandl | 2007-05-21 13:34:16 -0700 (Mon, 21 May 2007) | 2 lines

    Patch #1686487: you can now pass any mapping after '**' in function calls.
  ........
    r55502 | neal.norwitz | 2007-05-21 23:03:36 -0700 (Mon, 21 May 2007) | 1 line

    Document new params to HTTPSConnection
  ........
    r55504 | neal.norwitz | 2007-05-22 00:16:10 -0700 (Tue, 22 May 2007) | 1 line

    Stop using METH_OLDARGS
  ........
    r55505 | neal.norwitz | 2007-05-22 00:16:44 -0700 (Tue, 22 May 2007) | 1 line

    Stop using METH_OLDARGS implicitly
  ........
................
This commit is contained in:
Guido van Rossum 2007-05-22 18:11:13 +00:00
parent dc19f09661
commit d59da4b432
102 changed files with 2081 additions and 4694 deletions

View File

@ -185,7 +185,7 @@ def test():
what = sys.argv[1]
if hasattr(proxy, what):
attr = getattr(proxy, what)
if callable(attr):
if hasattr(attr, '__call__'):
print attr(*sys.argv[2:])
else:
print repr(attr)

View File

@ -185,7 +185,6 @@ LIBFILES= $(MANSTYLES) $(INDEXSTYLES) $(COMMONTEX) \
lib/liburllib2.tex \
lib/libhttplib.tex \
lib/libftplib.tex \
lib/libgopherlib.tex \
lib/libnntplib.tex \
lib/liburlparse.tex \
lib/libhtmlparser.tex \
@ -197,9 +196,7 @@ LIBFILES= $(MANSTYLES) $(INDEXSTYLES) $(COMMONTEX) \
lib/libbinascii.tex \
lib/libmm.tex \
lib/libaudioop.tex \
lib/libimageop.tex \
lib/libaifc.tex \
lib/librgbimg.tex \
lib/libossaudiodev.tex \
lib/libcrypto.tex \
lib/libhashlib.tex \
@ -352,7 +349,6 @@ MACFILES= $(HOWTOSTYLES) $(INDEXSTYLES) $(COMMONTEX) \
mac/libaetools.tex \
mac/libaepack.tex \
mac/libaetypes.tex \
mac/libmacfs.tex \
mac/libmacos.tex \
mac/libmacostools.tex \
mac/libmacui.tex \

View File

@ -292,7 +292,6 @@ and how to embed it in other applications.
\input{liburllib2}
\input{libhttplib}
\input{libftplib}
\input{libgopherlib}
\input{libpoplib}
\input{libimaplib}
\input{libnntplib}
@ -317,13 +316,11 @@ and how to embed it in other applications.
\input{libmm} % Multimedia Services
\input{libaudioop}
\input{libimageop}
\input{libaifc}
\input{libsunau}
\input{libwave}
\input{libchunk}
\input{libcolorsys}
\input{librgbimg}
\input{libimghdr}
\input{libsndhdr}
\input{libossaudiodev}

View File

@ -378,14 +378,25 @@ Point(x=11, y=22)
The use cases are the same as those for tuples. The named factories
assign meaning to each tuple position and allow for more readable,
self-documenting code. Named tuples can also be used to assign field names
to tuples
returned by the \module{csv} or \module{sqlite3} modules. For example:
to tuples returned by the \module{csv} or \module{sqlite3} modules.
For example:
\begin{verbatim}
from itertools import starmap
import csv
EmployeeRecord = NamedTuple('EmployeeRecord', 'name age title department paygrade')
for tup in csv.reader(open("employees.csv", "rb")):
print EmployeeRecord(*tup)
for record in starmap(EmployeeRecord, csv.reader(open("employees.csv", "rb"))):
print record
\end{verbatim}
To cast an individual record stored as \class{list}, \class{tuple}, or some other
iterable type, use the star-operator to unpack the values:
\begin{verbatim}
>>> Color = NamedTuple('Color', 'name code')
>>> m = dict(red=1, green=2, blue=3)
>>> print Color(*m.popitem())
Color(name='blue', code=3)
\end{verbatim}
\end{funcdesc}

View File

@ -111,7 +111,7 @@ And lets you write code like this:
\begin{verbatim}
from __future__ import with_statement
from contextlib import closing
import codecs
import urllib
with closing(urllib.urlopen('http://www.python.org')) as page:
for line in page:

View File

@ -118,15 +118,6 @@ def my_import(name):
\constant{False}]{2.3}
\end{funcdesc}
\begin{funcdesc}{callable}{object}
Return true if the \var{object} argument appears callable, false if
not. If this returns true, it is still possible that a call fails,
but if it is false, calling \var{object} will never succeed. Note
that classes are callable (calling a class returns a new instance);
class instances are callable if they have a \method{__call__()}
method.
\end{funcdesc}
\begin{funcdesc}{chr}{i}
Return a string of one character whose \ASCII{} code is the integer
\var{i}. For example, \code{chr(97)} returns the string \code{'a'}.

View File

@ -1,36 +0,0 @@
\section{\module{gopherlib} ---
Gopher protocol client}
\declaremodule{standard}{gopherlib}
\modulesynopsis{Gopher protocol client (requires sockets).}
\deprecated{2.5}{The \code{gopher} protocol is not in active use
anymore.}
\indexii{Gopher}{protocol}
This module provides a minimal implementation of client side of the
Gopher protocol. It is used by the module \refmodule{urllib} to
handle URLs that use the Gopher protocol.
The module defines the following functions:
\begin{funcdesc}{send_selector}{selector, host\optional{, port}}
Send a \var{selector} string to the gopher server at \var{host} and
\var{port} (default \code{70}). Returns an open file object from
which the returned document can be read.
\end{funcdesc}
\begin{funcdesc}{send_query}{selector, query, host\optional{, port}}
Send a \var{selector} string and a \var{query} string to a gopher
server at \var{host} and \var{port} (default \code{70}). Returns an
open file object from which the returned document can be read.
\end{funcdesc}
Note that the data returned by the Gopher server can be of any type,
depending on the first character of the selector string. If the data
is text (first character of the selector is \samp{0}), lines are
terminated by CRLF, and the data is terminated by a line consisting of
a single \samp{.}, and a leading \samp{.} should be stripped from
lines that begin with \samp{..}. Directory listings (first character
of the selector is \samp{1}) are transferred using the same protocol.

View File

@ -51,7 +51,9 @@ the server at the same host and port:
\versionadded{2.0}
\end{classdesc}
\begin{classdesc}{HTTPSConnection}{host\optional{, port, key_file, cert_file}}
\begin{classdesc}{HTTPSConnection}{host\optional{, port\optional{,
key_file\optional{, cert_file\optional{,
strict\optional{, timeout}}}}}}
A subclass of \class{HTTPConnection} that uses SSL for communication with
secure servers. Default port is \code{443}.
\var{key_file} is

View File

@ -1,100 +0,0 @@
\section{\module{imageop} ---
Manipulate raw image data}
\declaremodule{builtin}{imageop}
\modulesynopsis{Manipulate raw image data.}
The \module{imageop} module contains some useful operations on images.
It operates on images consisting of 8 or 32 bit pixels stored in
Python strings. This is the same format as used by
\function{gl.lrectwrite()} and the \refmodule{imgfile} module.
The module defines the following variables and functions:
\begin{excdesc}{error}
This exception is raised on all errors, such as unknown number of bits
per pixel, etc.
\end{excdesc}
\begin{funcdesc}{crop}{image, psize, width, height, x0, y0, x1, y1}
Return the selected part of \var{image}, which should be
\var{width} by \var{height} in size and consist of pixels of
\var{psize} bytes. \var{x0}, \var{y0}, \var{x1} and \var{y1} are like
the \function{gl.lrectread()} parameters, i.e.\ the boundary is
included in the new image. The new boundaries need not be inside the
picture. Pixels that fall outside the old image will have their value
set to zero. If \var{x0} is bigger than \var{x1} the new image is
mirrored. The same holds for the y coordinates.
\end{funcdesc}
\begin{funcdesc}{scale}{image, psize, width, height, newwidth, newheight}
Return \var{image} scaled to size \var{newwidth} by \var{newheight}.
No interpolation is done, scaling is done by simple-minded pixel
duplication or removal. Therefore, computer-generated images or
dithered images will not look nice after scaling.
\end{funcdesc}
\begin{funcdesc}{tovideo}{image, psize, width, height}
Run a vertical low-pass filter over an image. It does so by computing
each destination pixel as the average of two vertically-aligned source
pixels. The main use of this routine is to forestall excessive
flicker if the image is displayed on a video device that uses
interlacing, hence the name.
\end{funcdesc}
\begin{funcdesc}{grey2mono}{image, width, height, threshold}
Convert a 8-bit deep greyscale image to a 1-bit deep image by
thresholding all the pixels. The resulting image is tightly packed and
is probably only useful as an argument to \function{mono2grey()}.
\end{funcdesc}
\begin{funcdesc}{dither2mono}{image, width, height}
Convert an 8-bit greyscale image to a 1-bit monochrome image using a
(simple-minded) dithering algorithm.
\end{funcdesc}
\begin{funcdesc}{mono2grey}{image, width, height, p0, p1}
Convert a 1-bit monochrome image to an 8 bit greyscale or color image.
All pixels that are zero-valued on input get value \var{p0} on output
and all one-value input pixels get value \var{p1} on output. To
convert a monochrome black-and-white image to greyscale pass the
values \code{0} and \code{255} respectively.
\end{funcdesc}
\begin{funcdesc}{grey2grey4}{image, width, height}
Convert an 8-bit greyscale image to a 4-bit greyscale image without
dithering.
\end{funcdesc}
\begin{funcdesc}{grey2grey2}{image, width, height}
Convert an 8-bit greyscale image to a 2-bit greyscale image without
dithering.
\end{funcdesc}
\begin{funcdesc}{dither2grey2}{image, width, height}
Convert an 8-bit greyscale image to a 2-bit greyscale image with
dithering. As for \function{dither2mono()}, the dithering algorithm
is currently very simple.
\end{funcdesc}
\begin{funcdesc}{grey42grey}{image, width, height}
Convert a 4-bit greyscale image to an 8-bit greyscale image.
\end{funcdesc}
\begin{funcdesc}{grey22grey}{image, width, height}
Convert a 2-bit greyscale image to an 8-bit greyscale image.
\end{funcdesc}
\begin{datadesc}{backward_compatible}
If set to 0, the functions in this module use a non-backward
compatible way of representing multi-byte pixels on little-endian
systems. The SGI for which this module was originally written is a
big-endian system, so setting this variable will have no effect.
However, the code wasn't originally intended to run on anything else,
so it made assumptions about byte order which are not universal.
Setting this variable to 0 will cause the byte order to be reversed on
little-endian systems, so that it then is the same as on big-endian
systems.
\end{datadesc}

View File

@ -1191,14 +1191,14 @@ OptionValueError if an invalid string is given.
The whole point of creating and populating an OptionParser is to call
its \method{parse{\_}args()} method:
\begin{verbatim}
(options, args) = parser.parse_args(args=None, options=None)
(options, args) = parser.parse_args(args=None, values=None)
\end{verbatim}
where the input parameters are
\begin{description}
\item[\code{args}]
the list of arguments to process (default: \code{sys.argv{[}1:]})
\item[\code{options}]
\item[\code{values}]
object to store option arguments in (default: a new instance of
optparse.Values)
\end{description}

View File

@ -1,54 +0,0 @@
\section{\module{rgbimg} ---
Read and write ``SGI RGB'' files}
\declaremodule{builtin}{rgbimg}
\modulesynopsis{Read and write image files in ``SGI RGB'' format (the module
is \emph{not} SGI specific though!).}
\deprecated{2.5}{This module is not maintained anymore and seems to be
unused.}
The \module{rgbimg} module allows Python programs to access SGI imglib image
files (also known as \file{.rgb} files). The module is far from
complete, but is provided anyway since the functionality that there is
enough in some cases. Currently, colormap files are not supported.
\note{This module is only built by default for 32-bit platforms; it is
not expected to work properly on other systems.}
The module defines the following variables and functions:
\begin{excdesc}{error}
This exception is raised on all errors, such as unsupported file type, etc.
\end{excdesc}
\begin{funcdesc}{sizeofimage}{file}
This function returns a tuple \code{(\var{x}, \var{y})} where
\var{x} and \var{y} are the size of the image in pixels.
Only 4 byte RGBA pixels, 3 byte RGB pixels, and 1 byte greyscale pixels
are currently supported.
\end{funcdesc}
\begin{funcdesc}{longimagedata}{file}
This function reads and decodes the image on the specified file, and
returns it as a Python string. The string has 4 byte RGBA pixels.
The bottom left pixel is the first in
the string. This format is suitable to pass to \function{gl.lrectwrite()},
for instance.
\end{funcdesc}
\begin{funcdesc}{longstoimage}{data, x, y, z, file}
This function writes the RGBA data in \var{data} to image
file \var{file}. \var{x} and \var{y} give the size of the image.
\var{z} is 1 if the saved image should be 1 byte greyscale, 3 if the
saved image should be 3 byte RGB data, or 4 if the saved images should
be 4 byte RGBA data. The input data always contains 4 bytes per pixel.
These are the formats returned by \function{gl.lrectread()}.
\end{funcdesc}
\begin{funcdesc}{ttob}{flag}
This function sets a global flag which defines whether the scan lines
of the image are read or written from bottom to top (flag is zero,
compatible with SGI GL) or from top to bottom (flag is one,
compatible with X). The default is zero.
\end{funcdesc}

View File

View File

@ -70,8 +70,8 @@ see the \function{urlencode()} function below.
The \function{urlopen()} function works transparently with proxies
which do not require authentication. In a \UNIX{} or Windows
environment, set the \envvar{http_proxy}, \envvar{ftp_proxy} or
\envvar{gopher_proxy} environment variables to a URL that identifies
environment, set the \envvar{http_proxy}, or \envvar{ftp_proxy}
environment variables to a URL that identifies
the proxy server before starting the Python interpreter. For example
(the \character{\%} is the command prompt):
@ -253,7 +253,7 @@ function uses \function{unquote()} to decode \var{path}.
\begin{classdesc}{URLopener}{\optional{proxies\optional{, **x509}}}
Base class for opening and reading URLs. Unless you need to support
opening objects using schemes other than \file{http:}, \file{ftp:},
\file{gopher:} or \file{file:}, you probably want to use
or \file{file:}, you probably want to use
\class{FancyURLopener}.
By default, the \class{URLopener} class sends a
@ -324,9 +324,8 @@ Restrictions:
\item
Currently, only the following protocols are supported: HTTP, (versions
0.9 and 1.0), Gopher (but not Gopher-+), FTP, and local files.
0.9 and 1.0), FTP, and local files.
\indexii{HTTP}{protocol}
\indexii{Gopher}{protocol}
\indexii{FTP}{protocol}
\item
@ -355,9 +354,7 @@ is the raw data returned by the server. This may be binary data
(such as an image), plain text or (for example) HTML\index{HTML}. The
HTTP\indexii{HTTP}{protocol} protocol provides type information in the
reply header, which can be inspected by looking at the
\mailheader{Content-Type} header. For the
Gopher\indexii{Gopher}{protocol} protocol, type information is encoded
in the URL; there is currently no easy way to extract it. If the
\mailheader{Content-Type} header. If the
returned data is HTML, you can use the module
\refmodule{htmllib}\refstmodindex{htmllib} to parse it.

View File

@ -86,11 +86,6 @@ non-exceptional file-like return value (the same thing that
HTTP errors, such as requests for authentication.
\end{excdesc}
\begin{excdesc}{GopherError}
A subclass of \exception{URLError}, this is the error raised by the
Gopher handler.
\end{excdesc}
The following classes are provided:
@ -241,10 +236,6 @@ Open FTP URLs, keeping a cache of open FTP connections to minimize
delays.
\end{classdesc}
\begin{classdesc}{GopherHandler}{}
Open gopher URLs.
\end{classdesc}
\begin{classdesc}{UnknownHandler}{}
A catch-all class to handle unknown URLs.
\end{classdesc}
@ -744,13 +735,6 @@ Set maximum number of cached connections to \var{m}.
\end{methoddesc}
\subsection{GopherHandler Objects \label{gopher-handler}}
\begin{methoddesc}[GopherHandler]{gopher_open}{req}
Open the gopher resource indicated by \var{req}.
\end{methoddesc}
\subsection{UnknownHandler Objects \label{unknown-handler-objects}}
\begin{methoddesc}[UnknownHandler]{unknown_open}{}

View File

@ -1,241 +0,0 @@
\section{\module{macfs} ---
Various file system services}
\declaremodule{standard}{macfs}
\platform{Mac}
\modulesynopsis{Support for FSSpec, the Alias Manager,
\program{finder} aliases, and the Standard File package.}
\deprecated{2.3}{The macfs module should be considered obsolete. For
\class{FSSpec}, \class{FSRef} and \class{Alias} handling use the
\module{Carbon.File} or \refmodule{Carbon.Folder} module. For file
dialogs use the \refmodule{EasyDialogs} module. Also, this module is
known to not work correctly with UFS partitions.}
This module provides access to Macintosh \class{FSSpec} handling, the
Alias Manager, \program{finder} aliases and the Standard File package.
\index{Macintosh Alias Manager}
\index{Alias Manager, Macintosh}
\index{Standard File}
Whenever a function or method expects a \var{file} argument, this
argument can be one of three things:\ (1) a full or partial Macintosh
pathname, (2) an \class{FSSpec} object or (3) a 3-tuple
\code{(\var{wdRefNum}, \var{parID}, \var{name})} as described in
\citetitle{Inside Macintosh:\ Files}. An \class{FSSpec} can point to
a non-existing file, as long as the folder containing the file exists.
Under MacPython the same is true for a pathname, but not under \UNIX-Python
because of the way pathnames and FSRefs works. See Apple's documentation
for details.
A description of aliases and the
Standard File package can also be found there.
\begin{funcdesc}{FSSpec}{file}
Create an \class{FSSpec} object for the specified file.
\end{funcdesc}
\begin{funcdesc}{RawFSSpec}{data}
Create an \class{FSSpec} object given the raw data for the \C{}
structure for the \class{FSSpec} as a string. This is mainly useful
if you have obtained an \class{FSSpec} structure over a network.
\end{funcdesc}
\begin{funcdesc}{RawAlias}{data}
Create an \class{Alias} object given the raw data for the \C{}
structure for the alias as a string. This is mainly useful if you
have obtained an \class{FSSpec} structure over a network.
\end{funcdesc}
\begin{funcdesc}{FInfo}{}
Create a zero-filled \class{FInfo} object.
\end{funcdesc}
\begin{funcdesc}{ResolveAliasFile}{file}
Resolve an alias file. Returns a 3-tuple \code{(\var{fsspec},
\var{isfolder}, \var{aliased})} where \var{fsspec} is the resulting
\class{FSSpec} object, \var{isfolder} is true if \var{fsspec} points
to a folder and \var{aliased} is true if the file was an alias in the
first place (otherwise the \class{FSSpec} object for the file itself
is returned).
\end{funcdesc}
\begin{funcdesc}{StandardGetFile}{\optional{type, \moreargs}}
Present the user with a standard ``open input file''
dialog. Optionally, you can pass up to four 4-character file types to limit
the files the user can choose from. The function returns an \class{FSSpec}
object and a flag indicating that the user completed the dialog
without cancelling.
\end{funcdesc}
\begin{funcdesc}{PromptGetFile}{prompt\optional{, type, \moreargs}}
Similar to \function{StandardGetFile()} but allows you to specify a
prompt which will be displayed at the top of the dialog.
\end{funcdesc}
\begin{funcdesc}{StandardPutFile}{prompt\optional{, default}}
Present the user with a standard ``open output file''
dialog. \var{prompt} is the prompt string, and the optional
\var{default} argument initializes the output file name. The function
returns an \class{FSSpec} object and a flag indicating that the user
completed the dialog without cancelling.
\end{funcdesc}
\begin{funcdesc}{GetDirectory}{\optional{prompt}}
Present the user with a non-standard ``select a directory'' dialog. You
have to first open the directory before clicking on the ``select current
directory'' button. \var{prompt} is the prompt string which will be
displayed at the top of the dialog. Return an \class{FSSpec} object and
a success-indicator.
\end{funcdesc}
\begin{funcdesc}{SetFolder}{\optional{fsspec}}
Set the folder that is initially presented to the user when one of
the file selection dialogs is presented. \var{fsspec} should point to
a file in the folder, not the folder itself (the file need not exist,
though). If no argument is passed the folder will be set to the
current directory, i.e. what \function{os.getcwd()} returns.
Note that starting with System 7.5 the user can change Standard File
behaviour with the ``general controls'' control panel, thereby making
this call inoperative.
\end{funcdesc}
\begin{funcdesc}{FindFolder}{where, which, create}
Locates one of the ``special'' folders that Mac OS knows about, such as
the trash or the Preferences folder. \var{where} is the disk to
search, \var{which} is the 4-character string specifying which folder to
locate. Setting \var{create} causes the folder to be created if it
does not exist. Returns a \code{(\var{vrefnum}, \var{dirid})} tuple.
The constants for \var{where} and \var{which} can be obtained from the
standard module \var{Carbon.Folders}.
\end{funcdesc}
\begin{funcdesc}{NewAliasMinimalFromFullPath}{pathname}
Return a minimal \class{alias} object that points to the given file, which
must be specified as a full pathname. This is the only way to create an
\class{Alias} pointing to a non-existing file.
\end{funcdesc}
\begin{funcdesc}{FindApplication}{creator}
Locate the application with 4-character creator code \var{creator}. The
function returns an \class{FSSpec} object pointing to the application.
\end{funcdesc}
\subsection{FSSpec Objects \label{fsspec-objects}}
\begin{memberdesc}[FSSpec]{data}
The raw data from the FSSpec object, suitable for passing
to other applications, for instance.
\end{memberdesc}
\begin{methoddesc}[FSSpec]{as_pathname}{}
Return the full pathname of the file described by the \class{FSSpec}
object.
\end{methoddesc}
\begin{methoddesc}[FSSpec]{as_tuple}{}
Return the \code{(\var{wdRefNum}, \var{parID}, \var{name})} tuple of
the file described by the \class{FSSpec} object.
\end{methoddesc}
\begin{methoddesc}[FSSpec]{NewAlias}{\optional{file}}
Create an Alias object pointing to the file described by this
FSSpec. If the optional \var{file} parameter is present the alias
will be relative to that file, otherwise it will be absolute.
\end{methoddesc}
\begin{methoddesc}[FSSpec]{NewAliasMinimal}{}
Create a minimal alias pointing to this file.
\end{methoddesc}
\begin{methoddesc}[FSSpec]{GetCreatorType}{}
Return the 4-character creator and type of the file.
\end{methoddesc}
\begin{methoddesc}[FSSpec]{SetCreatorType}{creator, type}
Set the 4-character creator and type of the file.
\end{methoddesc}
\begin{methoddesc}[FSSpec]{GetFInfo}{}
Return a \class{FInfo} object describing the finder info for the file.
\end{methoddesc}
\begin{methoddesc}[FSSpec]{SetFInfo}{finfo}
Set the finder info for the file to the values given as \var{finfo}
(an \class{FInfo} object).
\end{methoddesc}
\begin{methoddesc}[FSSpec]{GetDates}{}
Return a tuple with three floating point values representing the
creation date, modification date and backup date of the file.
\end{methoddesc}
\begin{methoddesc}[FSSpec]{SetDates}{crdate, moddate, backupdate}
Set the creation, modification and backup date of the file. The values
are in the standard floating point format used for times throughout
Python.
\end{methoddesc}
\subsection{Alias Objects \label{alias-objects}}
\begin{memberdesc}[Alias]{data}
The raw data for the Alias record, suitable for storing in a resource
or transmitting to other programs.
\end{memberdesc}
\begin{methoddesc}[Alias]{Resolve}{\optional{file}}
Resolve the alias. If the alias was created as a relative alias you
should pass the file relative to which it is. Return the FSSpec for
the file pointed to and a flag indicating whether the \class{Alias} object
itself was modified during the search process. If the file does
not exist but the path leading up to it does exist a valid fsspec
is returned.
\end{methoddesc}
\begin{methoddesc}[Alias]{GetInfo}{num}
An interface to the \C{} routine \cfunction{GetAliasInfo()}.
\end{methoddesc}
\begin{methoddesc}[Alias]{Update}{file\optional{, file2}}
Update the alias to point to the \var{file} given. If \var{file2} is
present a relative alias will be created.
\end{methoddesc}
Note that it is currently not possible to directly manipulate a
resource as an \class{Alias} object. Hence, after calling
\method{Update()} or after \method{Resolve()} indicates that the alias
has changed the Python program is responsible for getting the
\member{data} value from the \class{Alias} object and modifying the
resource.
\subsection{FInfo Objects \label{finfo-objects}}
See \citetitle{Inside Macintosh: Files} for a complete description of what
the various fields mean.
\begin{memberdesc}[FInfo]{Creator}
The 4-character creator code of the file.
\end{memberdesc}
\begin{memberdesc}[FInfo]{Type}
The 4-character type code of the file.
\end{memberdesc}
\begin{memberdesc}[FInfo]{Flags}
The finder flags for the file as 16-bit integer. The bit values in
\var{Flags} are defined in standard module \module{MACFS}.
\end{memberdesc}
\begin{memberdesc}[FInfo]{Location}
A Point giving the position of the file's icon in its folder.
\end{memberdesc}
\begin{memberdesc}[FInfo]{Fldr}
The folder the file is in (as an integer).
\end{memberdesc}

View File

@ -39,6 +39,7 @@ Tell the finder that some bits of finder-information such as creator
or type for file \var{dst} has changed. The file can be specified by
pathname or fsspec. This call should tell the finder to redraw the
files icon.
\deprecated{2.6}{The function is a no-op on OS X.}
\end{funcdesc}
\begin{datadesc}{BUFSIZ}

View File

@ -51,7 +51,6 @@ documented here:
\localmoduletable
\input{libmac}
\input{libmacfs}
\input{libmacic}
\input{libmacos}
\input{libmacostools}

View File

@ -660,7 +660,7 @@ It is unusual for both keyword arguments and the
this confusion does not arise.
If the syntax \samp{**expression} appears in the function call,
\samp{expression} must evaluate to a (subclass of) dictionary, the
\samp{expression} must evaluate to a mapping, the
contents of which are treated as additional keyword arguments. In the
case of a keyword appearing in both \samp{expression} and as an
explicit keyword argument, a \exception{TypeError} exception is

View File

@ -2696,9 +2696,9 @@ standard module \module{__builtin__}\refbimodindex{__builtin__}:
'UserWarning', 'ValueError', 'Warning', 'WindowsError',
'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__',
'__name__', 'abs', 'basestring', 'bool', 'buffer',
'callable', 'chr', 'classmethod', 'cmp', 'compile',
'chr', 'classmethod', 'cmp', 'compile',
'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod',
'enumerate', 'eval', 'exec', 'execfile', 'exit', 'file', 'filter', 'float',
'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float',
'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex',
'id', 'input', 'int', 'isinstance', 'issubclass', 'iter',
'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min',

View File

@ -147,6 +147,8 @@ stdscr.chgat(0,21, curses.A_BOLD)
(Contributed by Fabian Kreutz.)
\item The \module{gopherlib} module has been removed.
\item New function in the \module{heapq} module:
\function{merge(iter1, iter2, ...)}
takes any number of iterables that return data
@ -175,6 +177,10 @@ itertools.izip_longest([1,2,3], [1,2,3,4,5]) ->
(Contributed by Raymond Hettinger.)
\item The \module{macfs} module has been removed. This in turn
required the \function{macostools.touched()} function to be removed
because it depended on the \module{macfs} module.
% Patch #1490190
\item New functions in the \module{posix} module: \function{chflags()}
and \function{lchflags()} are wrappers for the corresponding system
@ -184,6 +190,8 @@ defined in the \module{stat} module; some possible values include
\constant{UF_APPEND} to indicate that data can only be appended to the
file. (Contributed by M. Levinson.)
\item The \module{rgbimg} module has been removed.
\item The \module{smtplib} module now supports SMTP over
SSL thanks to the addition of the \class{SMTP_SSL} class.
This class supports an interface identical to the existing \class{SMTP}

View File

@ -21,7 +21,8 @@ eval_input: testlist NEWLINE* ENDMARKER
decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
decorators: decorator+
funcdef: [decorators] 'def' NAME parameters ['->' test] ':' suite
decorated: decorators (classdef | funcdef)
funcdef: 'def' NAME parameters ['->' test] ':' suite
parameters: '(' [typedargslist] ')'
typedargslist: ((tfpdef ['=' test] ',')*
('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef)
@ -63,7 +64,7 @@ global_stmt: 'global' NAME (',' NAME)*
nonlocal_stmt: 'nonlocal' NAME (',' NAME)*
assert_stmt: 'assert' test [',' test]
compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef
compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated
if_stmt: 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
while_stmt: 'while' test ':' suite ['else' ':' suite]
for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite]

View File

@ -75,7 +75,7 @@ struct _stmt {
identifier name;
arguments_ty args;
asdl_seq *body;
asdl_seq *decorators;
asdl_seq *decorator_list;
expr_ty returns;
} FunctionDef;
@ -86,6 +86,7 @@ struct _stmt {
expr_ty starargs;
expr_ty kwargs;
asdl_seq *body;
asdl_seq *decorator_list;
} ClassDef;
struct {
@ -381,12 +382,13 @@ mod_ty _Py_Expression(expr_ty body, PyArena *arena);
mod_ty _Py_Suite(asdl_seq * body, PyArena *arena);
#define FunctionDef(a0, a1, a2, a3, a4, a5, a6, a7) _Py_FunctionDef(a0, a1, a2, a3, a4, a5, a6, a7)
stmt_ty _Py_FunctionDef(identifier name, arguments_ty args, asdl_seq * body,
asdl_seq * decorators, expr_ty returns, int lineno, int
col_offset, PyArena *arena);
#define ClassDef(a0, a1, a2, a3, a4, a5, a6, a7, a8) _Py_ClassDef(a0, a1, a2, a3, a4, a5, a6, a7, a8)
asdl_seq * decorator_list, expr_ty returns, int lineno,
int col_offset, PyArena *arena);
#define ClassDef(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9) _Py_ClassDef(a0, a1, a2, a3, a4, a5, a6, a7, a8, a9)
stmt_ty _Py_ClassDef(identifier name, asdl_seq * bases, asdl_seq * keywords,
expr_ty starargs, expr_ty kwargs, asdl_seq * body, int
lineno, int col_offset, PyArena *arena);
expr_ty starargs, expr_ty kwargs, asdl_seq * body,
asdl_seq * decorator_list, int lineno, int col_offset,
PyArena *arena);
#define Return(a0, a1, a2, a3) _Py_Return(a0, a1, a2, a3)
stmt_ty _Py_Return(expr_ty value, int lineno, int col_offset, PyArena *arena);
#define Delete(a0, a1, a2, a3) _Py_Delete(a0, a1, a2, a3)

View File

@ -3,78 +3,79 @@
#define eval_input 258
#define decorator 259
#define decorators 260
#define funcdef 261
#define parameters 262
#define typedargslist 263
#define tfpdef 264
#define varargslist 265
#define vfpdef 266
#define stmt 267
#define simple_stmt 268
#define small_stmt 269
#define expr_stmt 270
#define augassign 271
#define del_stmt 272
#define pass_stmt 273
#define flow_stmt 274
#define break_stmt 275
#define continue_stmt 276
#define return_stmt 277
#define yield_stmt 278
#define raise_stmt 279
#define import_stmt 280
#define import_name 281
#define import_from 282
#define import_as_name 283
#define dotted_as_name 284
#define import_as_names 285
#define dotted_as_names 286
#define dotted_name 287
#define global_stmt 288
#define nonlocal_stmt 289
#define assert_stmt 290
#define compound_stmt 291
#define if_stmt 292
#define while_stmt 293
#define for_stmt 294
#define try_stmt 295
#define with_stmt 296
#define with_var 297
#define except_clause 298
#define suite 299
#define test 300
#define test_nocond 301
#define lambdef 302
#define lambdef_nocond 303
#define or_test 304
#define and_test 305
#define not_test 306
#define comparison 307
#define comp_op 308
#define star_expr 309
#define expr 310
#define xor_expr 311
#define and_expr 312
#define shift_expr 313
#define arith_expr 314
#define term 315
#define factor 316
#define power 317
#define atom 318
#define testlist_comp 319
#define trailer 320
#define subscriptlist 321
#define subscript 322
#define sliceop 323
#define exprlist 324
#define testlist 325
#define dictorsetmaker 326
#define classdef 327
#define arglist 328
#define argument 329
#define comp_iter 330
#define comp_for 331
#define comp_if 332
#define testlist1 333
#define encoding_decl 334
#define yield_expr 335
#define decorated 261
#define funcdef 262
#define parameters 263
#define typedargslist 264
#define tfpdef 265
#define varargslist 266
#define vfpdef 267
#define stmt 268
#define simple_stmt 269
#define small_stmt 270
#define expr_stmt 271
#define augassign 272
#define del_stmt 273
#define pass_stmt 274
#define flow_stmt 275
#define break_stmt 276
#define continue_stmt 277
#define return_stmt 278
#define yield_stmt 279
#define raise_stmt 280
#define import_stmt 281
#define import_name 282
#define import_from 283
#define import_as_name 284
#define dotted_as_name 285
#define import_as_names 286
#define dotted_as_names 287
#define dotted_name 288
#define global_stmt 289
#define nonlocal_stmt 290
#define assert_stmt 291
#define compound_stmt 292
#define if_stmt 293
#define while_stmt 294
#define for_stmt 295
#define try_stmt 296
#define with_stmt 297
#define with_var 298
#define except_clause 299
#define suite 300
#define test 301
#define test_nocond 302
#define lambdef 303
#define lambdef_nocond 304
#define or_test 305
#define and_test 306
#define not_test 307
#define comparison 308
#define comp_op 309
#define star_expr 310
#define expr 311
#define xor_expr 312
#define and_expr 313
#define shift_expr 314
#define arith_expr 315
#define term 316
#define factor 317
#define power 318
#define atom 319
#define testlist_comp 320
#define trailer 321
#define subscriptlist 322
#define subscript 323
#define sliceop 324
#define exprlist 325
#define testlist 326
#define dictorsetmaker 327
#define classdef 328
#define arglist 329
#define argument 330
#define comp_iter 331
#define comp_for 332
#define comp_if 333
#define testlist1 334
#define encoding_decl 335
#define yield_expr 336

View File

@ -139,7 +139,7 @@ def list_public_methods(obj):
return [member for member in dir(obj)
if not member.startswith('_') and
callable(getattr(obj, member))]
hasattr(getattr(obj, member), '__call__')]
def remove_duplicates(lst):
"""remove_duplicates([2,2,2,1,3,3]) => [3,1,2]

View File

@ -511,14 +511,7 @@ def hexbin(inp, out):
ifp.close()
def _test():
if os.name == 'mac':
import macfs
fss, ok = macfs.PromptGetFile('File to convert:')
if not ok:
sys.exit(0)
fname = fss.as_pathname()
else:
fname = sys.argv[1]
fname = sys.argv[1]
binhex(fname, fname+'.hqx')
hexbin(fname+'.hqx', fname+'.viahqx')
#hexbin(fname, fname+'.unpacked')

View File

@ -118,7 +118,7 @@ class SimpleRecnoTestCase(unittest.TestCase):
assert not d.has_key(13)
data = d.get_both(26, "z" * 60)
assert data == "z" * 60
assert data == "z" * 60, 'was %r' % data
if verbose:
print(data)

View File

@ -183,7 +183,8 @@ function calls leading up to the error, in the order they occurred.</p>'''
%s
-->
''' % ''.join(traceback.format_exception(etype, evalue, etb))
''' % pydoc.html.escape(
''.join(traceback.format_exception(etype, evalue, etb)))
def text(einfo, context=5):
"""Return a plain text document describing a given traceback."""

View File

@ -24,30 +24,29 @@ def NamedTuple(typename, s):
"""
field_names = s.split()
nargs = len(field_names)
if not ''.join([typename] + field_names).replace('_', '').isalnum():
raise ValueError('Type names and field names can only contain alphanumeric characters and underscores')
argtxt = ', '.join(field_names)
reprtxt = ', '.join('%s=%%r' % name for name in field_names)
template = '''class %(typename)s(tuple):
'%(typename)s(%(argtxt)s)'
__slots__ = ()
def __new__(cls, %(argtxt)s):
return tuple.__new__(cls, (%(argtxt)s,))
def __repr__(self):
return '%(typename)s(%(reprtxt)s)' %% self
''' % locals()
for i, name in enumerate(field_names):
template += '\n %s = property(itemgetter(%d))\n' % (name, i)
m = dict(itemgetter=_itemgetter)
exec(template, m)
result = m[typename]
if hasattr(_sys, '_getframe'):
result.__module__ = _sys._getframe(1).f_globals['__name__']
return result
def __new__(cls, *args, **kwds):
if kwds:
try:
args += tuple(kwds[name] for name in field_names[len(args):])
except KeyError as name:
raise TypeError('%s missing required argument: %s' % (typename, name))
if len(args) != nargs:
raise TypeError('%s takes exactly %d arguments (%d given)' % (typename, nargs, len(args)))
return tuple.__new__(cls, args)
repr_template = '%s(%s)' % (typename, ', '.join('%s=%%r' % name for name in field_names))
m = dict(vars(tuple)) # pre-lookup superclass methods (for faster lookup)
m.update(__doc__= '%s(%s)' % (typename, ', '.join(field_names)),
__slots__ = (), # no per-instance dict (so instances are same size as tuples)
__new__ = __new__,
__repr__ = lambda self, _format=repr_template.__mod__: _format(self),
__module__ = _sys._getframe(1).f_globals['__name__'],
)
m.update((name, property(_itemgetter(index))) for index, name in enumerate(field_names))
return type(typename, (tuple,), m)
if __name__ == '__main__':

View File

@ -10,7 +10,7 @@ __all__ = ["pickle", "constructor",
dispatch_table = {}
def pickle(ob_type, pickle_function, constructor_ob=None):
if not callable(pickle_function):
if not hasattr(pickle_function, '__call__'):
raise TypeError("reduction functions must be callable")
dispatch_table[ob_type] = pickle_function
@ -20,7 +20,7 @@ def pickle(ob_type, pickle_function, constructor_ob=None):
constructor(constructor_ob)
def constructor(object):
if not callable(object):
if not hasattr(object, '__call__'):
raise TypeError("constructors must be callable")
# Example: provide pickling support for complex numbers.

View File

@ -569,7 +569,7 @@ Common commands: (see '--help-commands' for more)
#print "showing help for option %s of command %s" % \
# (help_option[0],cmd_class)
if callable(func):
if hasattr(func, '__call__'):
func()
else:
raise DistutilsClassError(

View File

@ -122,12 +122,12 @@ def search_function(encoding):
raise CodecRegistryError,\
'module "%s" (%s) failed to register' % \
(mod.__name__, mod.__file__)
if not callable(entry[0]) or \
not callable(entry[1]) or \
(entry[2] is not None and not callable(entry[2])) or \
(entry[3] is not None and not callable(entry[3])) or \
(len(entry) > 4 and entry[4] is not None and not callable(entry[4])) or \
(len(entry) > 5 and entry[5] is not None and not callable(entry[5])):
if not hasattr(entry[0], '__call__') or \
not hasattr(entry[1], '__call__') or \
(entry[2] is not None and not hasattr(entry[2], '__call__')) or \
(entry[3] is not None and not hasattr(entry[3], '__call__')) or \
(len(entry) > 4 and entry[4] is not None and not hasattr(entry[4], '__call__')) or \
(len(entry) > 5 and entry[5] is not None and not hasattr(entry[5], '__call__')):
raise CodecRegistryError,\
'incompatible codecs in module "%s" (%s)' % \
(mod.__name__, mod.__file__)

View File

@ -226,7 +226,7 @@ class FileInput:
self._mode = mode
if inplace and openhook:
raise ValueError("FileInput cannot use an opening hook in inplace mode")
elif openhook and not callable(openhook):
elif openhook and not hasattr(openhook, '__call__'):
raise ValueError("FileInput openhook must be callable")
self._openhook = openhook

View File

@ -1,209 +0,0 @@
"""Gopher protocol client interface."""
__all__ = ["send_selector","send_query"]
import warnings
warnings.warn("the gopherlib module is deprecated", DeprecationWarning,
stacklevel=2)
# Default selector, host and port
DEF_SELECTOR = '1/'
DEF_HOST = 'gopher.micro.umn.edu'
DEF_PORT = 70
# Recognized file types
A_TEXT = '0'
A_MENU = '1'
A_CSO = '2'
A_ERROR = '3'
A_MACBINHEX = '4'
A_PCBINHEX = '5'
A_UUENCODED = '6'
A_INDEX = '7'
A_TELNET = '8'
A_BINARY = '9'
A_DUPLICATE = '+'
A_SOUND = 's'
A_EVENT = 'e'
A_CALENDAR = 'c'
A_HTML = 'h'
A_TN3270 = 'T'
A_MIME = 'M'
A_IMAGE = 'I'
A_WHOIS = 'w'
A_QUERY = 'q'
A_GIF = 'g'
A_HTML = 'h' # HTML file
A_WWW = 'w' # WWW address
A_PLUS_IMAGE = ':'
A_PLUS_MOVIE = ';'
A_PLUS_SOUND = '<'
_names = dir()
_type_to_name_map = {}
def type_to_name(gtype):
"""Map all file types to strings; unknown types become TYPE='x'."""
global _type_to_name_map
if _type_to_name_map=={}:
for name in _names:
if name[:2] == 'A_':
_type_to_name_map[eval(name)] = name[2:]
if gtype in _type_to_name_map:
return _type_to_name_map[gtype]
return 'TYPE=%r' % (gtype,)
# Names for characters and strings
CRLF = '\r\n'
TAB = '\t'
def send_selector(selector, host, port = 0):
"""Send a selector to a given host and port, return a file with the reply."""
import socket
if not port:
i = host.find(':')
if i >= 0:
host, port = host[:i], int(host[i+1:])
if not port:
port = DEF_PORT
elif type(port) == type(''):
port = int(port)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.sendall(selector + CRLF)
s.shutdown(1)
return s.makefile('rb')
def send_query(selector, query, host, port = 0):
"""Send a selector and a query string."""
return send_selector(selector + '\t' + query, host, port)
def path_to_selector(path):
"""Takes a path as returned by urlparse and returns the appropriate selector."""
if path=="/":
return "/"
else:
return path[2:] # Cuts initial slash and data type identifier
def path_to_datatype_name(path):
"""Takes a path as returned by urlparse and maps it to a string.
See section 3.4 of RFC 1738 for details."""
if path=="/":
# No way to tell, although "INDEX" is likely
return "TYPE='unknown'"
else:
return type_to_name(path[1])
# The following functions interpret the data returned by the gopher
# server according to the expected type, e.g. textfile or directory
def get_directory(f):
"""Get a directory in the form of a list of entries."""
entries = []
while 1:
line = f.readline()
if not line:
print('(Unexpected EOF from server)')
break
if line[-2:] == CRLF:
line = line[:-2]
elif line[-1:] in CRLF:
line = line[:-1]
if line == '.':
break
if not line:
print('(Empty line from server)')
continue
gtype = line[0]
parts = line[1:].split(TAB)
if len(parts) < 4:
print('(Bad line from server: %r)' % (line,))
continue
if len(parts) > 4:
if parts[4:] != ['+']:
print('(Extra info from server:', end=' ')
print(parts[4:], ')')
else:
parts.append('')
parts.insert(0, gtype)
entries.append(parts)
return entries
def get_textfile(f):
"""Get a text file as a list of lines, with trailing CRLF stripped."""
lines = []
get_alt_textfile(f, lines.append)
return lines
def get_alt_textfile(f, func):
"""Get a text file and pass each line to a function, with trailing CRLF stripped."""
while 1:
line = f.readline()
if not line:
print('(Unexpected EOF from server)')
break
if line[-2:] == CRLF:
line = line[:-2]
elif line[-1:] in CRLF:
line = line[:-1]
if line == '.':
break
if line[:2] == '..':
line = line[1:]
func(line)
def get_binary(f):
"""Get a binary file as one solid data block."""
data = f.read()
return data
def get_alt_binary(f, func, blocksize):
"""Get a binary file and pass each block to a function."""
while 1:
data = f.read(blocksize)
if not data:
break
func(data)
def test():
"""Trivial test program."""
import sys
import getopt
opts, args = getopt.getopt(sys.argv[1:], '')
selector = DEF_SELECTOR
type = selector[0]
host = DEF_HOST
if args:
host = args[0]
args = args[1:]
if args:
type = args[0]
args = args[1:]
if len(type) > 1:
type, selector = type[0], type
else:
selector = ''
if args:
selector = args[0]
args = args[1:]
query = ''
if args:
query = args[0]
args = args[1:]
if type == A_INDEX:
f = send_query(selector, query, host)
else:
f = send_selector(selector, host)
if type == A_TEXT:
lines = get_textfile(f)
for item in lines: print(item)
elif type in (A_MENU, A_INDEX):
entries = get_directory(f)
for item in entries: print(item)
else:
data = get_binary(f)
print('binary data:', len(data), 'bytes:', repr(data[:100])[:40])
# Run the test when run as script
if __name__ == '__main__':
test()

View File

@ -39,7 +39,7 @@ class HMAC:
import hashlib
digestmod = hashlib.md5
if callable(digestmod):
if hasattr(digestmod, '__call__'):
self.digest_cons = digestmod
else:
self.digest_cons = lambda d='': digestmod.new(d)

View File

@ -1123,16 +1123,15 @@ class HTTPSConnection(HTTPConnection):
default_port = HTTPS_PORT
def __init__(self, host, port=None, key_file=None, cert_file=None,
strict=None):
HTTPConnection.__init__(self, host, port, strict)
strict=None, timeout=None):
HTTPConnection.__init__(self, host, port, strict, timeout)
self.key_file = key_file
self.cert_file = cert_file
def connect(self):
"Connect to a host on a given (SSL) port."
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((self.host, self.port))
sock = socket.create_connection((self.host, self.port), self.timeout)
ssl = socket.ssl(sock, self.key_file, self.cert_file)
self.sock = FakeSocket(sock, ssl)

View File

@ -572,7 +572,7 @@ def _getmethods(obj, methods):
# Adds names to dictionary argument 'methods'
for name in dir(obj):
attr = getattr(obj, name)
if callable(attr):
if hasattr(attr, '__call__'):
methods[name] = 1
if type(obj) == types.ClassType:
for super in obj.__bases__:
@ -581,7 +581,7 @@ def _getmethods(obj, methods):
def _getattributes(obj, attributes):
for name in dir(obj):
attr = getattr(obj, name)
if not callable(attr):
if not hasattr(attr, '__call__'):
attributes[name] = 1
class MethodProxy(object):

View File

@ -48,7 +48,7 @@ class ImportManager:
self.namespace['__import__'] = self.previous_importer
def add_suffix(self, suffix, importFunc):
assert callable(importFunc)
assert hasattr(importFunc, '__call__')
self.fs_imp.add_suffix(suffix, importFunc)
######################################################################
@ -539,7 +539,7 @@ class _FilesystemImporter(Importer):
self.suffixes = [ ]
def add_suffix(self, suffix, importFunc):
assert callable(importFunc)
assert hasattr(importFunc, '__call__')
self.suffixes.append((suffix, importFunc))
def import_from_dir(self, dir, fqname):

View File

@ -390,7 +390,7 @@ class TixWidget(Tkinter.Widget):
elif kw: cnf = kw
options = ()
for k, v in cnf.items():
if callable(v):
if hasattr(v, '__call__'):
v = self._register(v)
options = options + ('-'+k, v)
return master.tk.call(('image', 'create', imgtype,) + options)

View File

@ -1053,7 +1053,7 @@ class Misc:
for k, v in cnf.items():
if v is not None:
if k[-1] == '_': k = k[:-1]
if callable(v):
if hasattr(v, '__call__'):
v = self._register(v)
res = res + ('-'+k, v)
return res
@ -1570,7 +1570,7 @@ class Wm:
"""Bind function FUNC to command NAME for this widget.
Return the function bound to NAME if None is given. NAME could be
e.g. "WM_SAVE_YOURSELF" or "WM_DELETE_WINDOW"."""
if callable(func):
if hasattr(func, '__call__'):
command = self._register(func)
else:
command = func
@ -3221,7 +3221,7 @@ class Image:
elif kw: cnf = kw
options = ()
for k, v in cnf.items():
if callable(v):
if hasattr(v, '__call__'):
v = self._register(v)
options = options + ('-'+k, v)
self.tk.call(('image', 'create', imgtype, name,) + options)
@ -3244,7 +3244,7 @@ class Image:
for k, v in _cnfmerge(kw).items():
if v is not None:
if k[-1] == '_': k = k[:-1]
if callable(v):
if hasattr(v, '__call__'):
v = self._register(v)
res = res + ('-'+k, v)
self.tk.call((self.name, 'config') + res)

View File

@ -700,7 +700,7 @@ class Option:
def _check_callback(self):
if self.action == "callback":
if not callable(self.callback):
if not hasattr(self.callback, '__call__'):
raise OptionError(
"callback not callable: %r" % self.callback, self)
if (self.callback_args is not None and

View File

@ -346,7 +346,7 @@ class Pickler:
raise PicklingError("args from reduce() should be a tuple")
# Assert that func is callable
if not callable(func):
if not hasattr(func, '__call__'):
raise PicklingError("func from reduce should be callable")
save = self.save

View File

@ -1,198 +0,0 @@
"""macfs - Pure Python module designed to be backward compatible with
macfs and MACFS.
"""
import sys
import struct
import Carbon.Res
import Carbon.File
import warnings
warnings.warn("macfs is deprecated, use Carbon.File, Carbon.Folder or EasyDialogs",
DeprecationWarning, stacklevel=2)
# First step: ensure we also emulate the MACFS module, which contained
# all the constants
sys.modules['MACFS'] = sys.modules[__name__]
# Import all those constants
from Carbon.Files import *
from Carbon.Folders import *
# For some obscure historical reason these are here too:
READ = 1
WRITE = 2
smAllScripts = -3
#
# Find the epoch conversion for file dates in a way that works on OS9 and OSX
import time
if time.gmtime(0)[0] == 1970:
_EPOCHCONVERT = -((1970-1904)*365 + 17) * (24*60*60) + 0x100000000
def _utc2time(utc):
t = utc[1] + _EPOCHCONVERT
return int(t)
def _time2utc(t):
t = int(t) - _EPOCHCONVERT
if t < -0x7fffffff:
t = t + 0x10000000
return (0, int(t), 0)
else:
def _utc2time(utc):
t = utc[1]
if t < 0:
t = t + 0x100000000
return t
def _time2utc(t):
if t > 0x7fffffff:
t = t - 0x100000000
return (0, int(t), 0)
# The old name of the error object:
error = Carbon.File.Error
#
# The various objects macfs used to export. We override them here, because some
# of the method names are subtly different.
#
class FSSpec(Carbon.File.FSSpec):
def as_fsref(self):
return FSRef(self)
def NewAlias(self, src=None):
return Alias(Carbon.File.NewAlias(src, self))
def GetCreatorType(self):
finfo = self.FSpGetFInfo()
return finfo.Creator, finfo.Type
def SetCreatorType(self, ctor, tp):
finfo = self.FSpGetFInfo()
finfo.Creator = ctor
finfo.Type = tp
self.FSpSetFInfo(finfo)
def GetFInfo(self):
return self.FSpGetFInfo()
def SetFInfo(self, info):
return self.FSpSetFInfo(info)
def GetDates(self):
catInfoFlags = kFSCatInfoCreateDate|kFSCatInfoContentMod|kFSCatInfoBackupDate
catinfo, d1, d2, d3 = FSRef(self).FSGetCatalogInfo(catInfoFlags)
cdate = catinfo.createDate
mdate = catinfo.contentModDate
bdate = catinfo.backupDate
return _utc2time(cdate), _utc2time(mdate), _utc2time(bdate)
def SetDates(self, cdate, mdate, bdate):
catInfoFlags = kFSCatInfoCreateDate|kFSCatInfoContentMod|kFSCatInfoBackupDate
catinfo = Carbon.File.FSCatalogInfo(
createDate = _time2utc(cdate),
contentModDate = _time2utc(mdate),
backupDate = _time2utc(bdate))
FSRef(self).FSSetCatalogInfo(catInfoFlags, catinfo)
class FSRef(Carbon.File.FSRef):
def as_fsspec(self):
return FSSpec(self)
class Alias(Carbon.File.Alias):
def GetInfo(self, index):
return self.GetAliasInfo(index)
def Update(self, *args):
pass # print "Alias.Update not yet implemented"
def Resolve(self, src=None):
fss, changed = self.ResolveAlias(src)
return FSSpec(fss), changed
from Carbon.File import FInfo
# Backward-compatible type names:
FSSpecType = FSSpec
FSRefType = FSRef
AliasType = Alias
FInfoType = FInfo
# Global functions:
def ResolveAliasFile(fss, chain=1):
fss, isdir, isalias = Carbon.File.ResolveAliasFile(fss, chain)
return FSSpec(fss), isdir, isalias
def RawFSSpec(data):
return FSSpec(rawdata=data)
def RawAlias(data):
return Alias(rawdata=data)
def FindApplication(*args):
raise NotImplementedError, "FindApplication no longer implemented"
def NewAliasMinimalFromFullPath(path):
return Alias(Carbon.File.NewAliasMinimalFromFullPath(path, '', ''))
# Another global function:
from Carbon.Folder import FindFolder
#
# Finally the old Standard File routine emulators.
#
_curfolder = None
def StandardGetFile(*typelist):
"""Ask for an input file, optionally specifying 4-char file types that are
allowable"""
return PromptGetFile('', *typelist)
def PromptGetFile(prompt, *typelist):
"""Ask for an input file giving the user a prompt message. Optionally you can
specifying 4-char file types that are allowable"""
import EasyDialogs
warnings.warn("macfs.StandardGetFile and friends are deprecated, use EasyDialogs.AskFileForOpen",
DeprecationWarning, stacklevel=2)
if not typelist:
typelist = None
fss = EasyDialogs.AskFileForOpen(message=prompt, wanted=FSSpec,
typeList=typelist, defaultLocation=_handleSetFolder())
return fss, not fss is None
def StandardPutFile(prompt, default=None):
"""Ask the user for an output file, with a prompt. Optionally you cn supply a
default output filename"""
import EasyDialogs
warnings.warn("macfs.StandardGetFile and friends are deprecated, use EasyDialogs.AskFileForOpen",
DeprecationWarning, stacklevel=2)
fss = EasyDialogs.AskFileForSave(wanted=FSSpec, message=prompt,
savedFileName=default, defaultLocation=_handleSetFolder())
return fss, not fss is None
def SetFolder(folder):
global _curfolder
warnings.warn("macfs.StandardGetFile and friends are deprecated, use EasyDialogs.AskFileForOpen",
DeprecationWarning, stacklevel=2)
if _curfolder:
rv = FSSpec(_curfolder)
else:
rv = None
_curfolder = folder
return rv
def _handleSetFolder():
global _curfolder
rv = _curfolder
_curfolder = None
return rv
def GetDirectory(prompt=None):
"""Ask the user to select a folder. Optionally you can give a prompt."""
import EasyDialogs
warnings.warn("macfs.StandardGetFile and friends are deprecated, use EasyDialogs.AskFileForOpen",
DeprecationWarning, stacklevel=2)
fss = EasyDialogs.AskFolder(message=prompt, wanted=FSSpec,
defaultLocation=_handleSetFolder())
return fss, not fss is None

View File

@ -65,21 +65,9 @@ def mkdirs(dst):
def touched(dst):
"""Tell the finder a file has changed. No-op on MacOSX."""
if sys.platform != 'mac': return
import warnings
warnings.filterwarnings("ignore", "macfs.*", DeprecationWarning, __name__)
import macfs
file_fss = macfs.FSSpec(dst)
vRefNum, dirID, name = file_fss.as_tuple()
dir_fss = macfs.FSSpec((vRefNum, dirID, ''))
crdate, moddate, bkdate = dir_fss.GetDates()
now = time.time()
if now == moddate:
now = now + 1
try:
dir_fss.SetDates(crdate, now, bkdate)
except macfs.error:
pass
warnings.warn("macostools.touched() has been deprecated",
DeprecationWarning, 2)
def touched_ae(dst):
"""Tell the finder a file has changed"""
@ -129,7 +117,6 @@ def copy(src, dst, createpath=0, copydates=1, forcetype=None):
dstfsr = File.FSRef(dst)
catinfo, _, _, _ = srcfsr.FSGetCatalogInfo(Files.kFSCatInfoAllDates)
dstfsr.FSSetCatalogInfo(Files.kFSCatInfoAllDates, catinfo)
touched(dstfss)
def copytree(src, dst, copydates=1):
"""Copy a complete file tree to a new destination"""

View File

@ -52,7 +52,9 @@ f.lock(mode [, len [, start [, whence]]])
note: - the '?' modifier prevents a region from being locked; it is
query only
"""
import warnings
warnings.warn("The posixfile module is deprecated; "
"fcntl.lockf() provides better locking", DeprecationWarning, 2)
class _posixfile_:
"""File wrapper class that provides extra POSIX file routines."""

View File

@ -754,7 +754,7 @@ class HTMLDoc(Doc):
push(msg)
for name, kind, homecls, value in ok:
base = self.docother(getattr(object, name), name, mod)
if callable(value) or inspect.isdatadescriptor(value):
if hasattr(value, '__call__') or inspect.isdatadescriptor(value):
doc = getattr(value, "__doc__", None)
else:
doc = None
@ -1169,7 +1169,7 @@ class TextDoc(Doc):
hr.maybe()
push(msg)
for name, kind, homecls, value in ok:
if callable(value) or inspect.isdatadescriptor(value):
if hasattr(value, '__call__') or inspect.isdatadescriptor(value):
doc = getdoc(value)
else:
doc = None

View File

@ -306,7 +306,7 @@ class Scanner:
if i == j:
break
action = self.lexicon[m.lastindex-1][1]
if callable(action):
if hasattr(action, '__call__'):
self.match = m
action = action(self, m.group())
if action is not None:

View File

@ -118,8 +118,10 @@ def _init_pathinfo():
return d
def addpackage(sitedir, name, known_paths):
"""Add a new path to known_paths by combining sitedir and 'name' or execute
sitedir if it starts with 'import'"""
"""Process a .pth file within the site-packages directory:
For each line in the file, either combine it with sitedir to a path
and add that to known_paths, or execute it if it starts with 'import '.
"""
if known_paths is None:
_init_pathinfo()
reset = 1

View File

@ -15,89 +15,90 @@ file_input = 257
eval_input = 258
decorator = 259
decorators = 260
funcdef = 261
parameters = 262
typedargslist = 263
tname = 264
tfpdef = 265
tfplist = 266
varargslist = 267
vname = 268
vfpdef = 269
vfplist = 270
stmt = 271
simple_stmt = 272
small_stmt = 273
expr_stmt = 274
augassign = 275
del_stmt = 276
pass_stmt = 277
flow_stmt = 278
break_stmt = 279
continue_stmt = 280
return_stmt = 281
yield_stmt = 282
raise_stmt = 283
import_stmt = 284
import_name = 285
import_from = 286
import_as_name = 287
dotted_as_name = 288
import_as_names = 289
dotted_as_names = 290
dotted_name = 291
global_stmt = 292
nonlocal_stmt = 293
assert_stmt = 294
compound_stmt = 295
if_stmt = 296
while_stmt = 297
for_stmt = 298
try_stmt = 299
with_stmt = 300
with_var = 301
except_clause = 302
suite = 303
testlist_safe = 304
old_test = 305
old_lambdef = 306
test = 307
or_test = 308
and_test = 309
not_test = 310
comparison = 311
comp_op = 312
expr = 313
xor_expr = 314
and_expr = 315
shift_expr = 316
arith_expr = 317
term = 318
factor = 319
power = 320
atom = 321
listmaker = 322
testlist_gexp = 323
lambdef = 324
trailer = 325
subscriptlist = 326
subscript = 327
sliceop = 328
exprlist = 329
testlist = 330
dictsetmaker = 331
classdef = 332
arglist = 333
argument = 334
list_iter = 335
list_for = 336
list_if = 337
gen_iter = 338
gen_for = 339
gen_if = 340
testlist1 = 341
encoding_decl = 342
yield_expr = 343
decorated_thing = 261
funcdef = 262
parameters = 263
typedargslist = 264
tname = 265
tfpdef = 266
tfplist = 267
varargslist = 268
vname = 269
vfpdef = 270
vfplist = 271
stmt = 272
simple_stmt = 273
small_stmt = 274
expr_stmt = 275
augassign = 276
del_stmt = 277
pass_stmt = 278
flow_stmt = 279
break_stmt = 280
continue_stmt = 281
return_stmt = 282
yield_stmt = 283
raise_stmt = 284
import_stmt = 285
import_name = 286
import_from = 287
import_as_name = 288
dotted_as_name = 289
import_as_names = 290
dotted_as_names = 291
dotted_name = 292
global_stmt = 293
nonlocal_stmt = 294
assert_stmt = 295
compound_stmt = 296
if_stmt = 297
while_stmt = 298
for_stmt = 299
try_stmt = 300
with_stmt = 301
with_var = 302
except_clause = 303
suite = 304
testlist_safe = 305
old_test = 306
old_lambdef = 307
test = 308
or_test = 309
and_test = 310
not_test = 311
comparison = 312
comp_op = 313
expr = 314
xor_expr = 315
and_expr = 316
shift_expr = 317
arith_expr = 318
term = 319
factor = 320
power = 321
atom = 322
listmaker = 323
testlist_gexp = 324
lambdef = 325
trailer = 326
subscriptlist = 327
subscript = 328
sliceop = 329
exprlist = 330
testlist = 331
dictsetmaker = 332
classdef = 333
arglist = 334
argument = 335
list_iter = 336
list_for = 337
list_if = 338
gen_iter = 339
gen_for = 340
gen_if = 341
testlist1 = 342
encoding_decl = 343
yield_expr = 344
#--end constants--
sym_name = {}

View File

@ -9,6 +9,9 @@ test_extcall
(1, 2, 3) {'a': 4, 'b': 5}
(1, 2, 3, 4, 5) {'a': 6, 'b': 7}
(1, 2, 3, 6, 7) {'a': 8, 'b': 9, 'x': 4, 'y': 5}
(1, 2, 3) {'a': 4, 'b': 5}
(1, 2, 3, 4, 5) {'a': 6, 'b': 7}
(1, 2, 3, 6, 7) {'a': 8, 'b': 9, 'x': 4, 'y': 5}
TypeError: g() takes at least 1 positional argument (0 given)
TypeError: g() takes at least 1 positional argument (0 given)
TypeError: g() takes at least 1 positional argument (0 given)
@ -25,12 +28,12 @@ g() got multiple values for keyword argument 'x'
g() got multiple values for keyword argument 'b'
f() keywords must be strings
h() got an unexpected keyword argument 'e'
h() argument after * must be a sequence
dir() argument after * must be a sequence
NoneType object argument after * must be a sequence
h() argument after ** must be a dictionary
dir() argument after ** must be a dictionary
NoneType object argument after ** must be a dictionary
h() argument after * must be a sequence, not function
dir() argument after * must be a sequence, not function
NoneType object argument after * must be a sequence, not function
h() argument after ** must be a mapping, not function
dir() argument after ** must be a mapping, not function
NoneType object argument after ** must be a mapping, not function
dir() got multiple values for keyword argument 'b'
3 512 True
3

View File

@ -1108,7 +1108,6 @@ _expectations = {
test_gdbm
test_linuxaudiodev
test_locale
test_macfs
test_macostools
test_nis
test_ossaudiodev
@ -1139,7 +1138,6 @@ _expectations = {
test_gdbm
test_gzip
test_linuxaudiodev
test_macfs
test_macostools
test_nis
test_ossaudiodev
@ -1163,7 +1161,6 @@ _expectations = {
test_gdbm
test_linuxaudiodev
test_locale
test_macfs
test_macostools
test_nis
test_normalization
@ -1191,7 +1188,6 @@ _expectations = {
test_gdbm
test_linuxaudiodev
test_locale
test_macfs
test_macostools
test_nis
test_ossaudiodev
@ -1229,12 +1225,8 @@ class _ExpectedSkips:
if test_timeout.skip_expected:
self.expected.add('test_timeout')
if sys.maxint == 9223372036854775807:
self.expected.add('test_rgbimg')
self.expected.add('test_imageop')
if not sys.platform in ("mac", "darwin"):
MAC_ONLY = ["test_macostools", "test_macfs", "test_aepack",
MAC_ONLY = ["test_macostools", "test_aepack",
"test_plistlib", "test_scriptpackages"]
for skip in MAC_ONLY:
self.expected.add(skip)
@ -1245,6 +1237,11 @@ class _ExpectedSkips:
for skip in WIN_ONLY:
self.expected.add(skip)
if sys.platform != 'irix':
IRIX_ONLY =["test_imageop"]
for skip in IRIX_ONLY:
self.expected.add(skip)
self.valid = True
def isvalid(self):

View File

@ -3,10 +3,6 @@ from test.test_support import verbose, run_unittest
import sys
import warnings
warnings.filterwarnings("ignore",
"the gopherlib module is deprecated",
DeprecationWarning,
"<string>")
class AllTest(unittest.TestCase):
@ -78,7 +74,6 @@ class AllTest(unittest.TestCase):
self.check_all("getpass")
self.check_all("gettext")
self.check_all("glob")
self.check_all("gopherlib")
self.check_all("gzip")
self.check_all("heapq")
self.check_all("htmllib")

View File

@ -152,7 +152,7 @@ def run_tests():
#### EVERYTHING BELOW IS GENERATED #####
exec_results = [
('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, None, [], None, None, [], []), [('Pass', (1, 9))], [], None)]),
('Module', [('ClassDef', (1, 0), 'C', [], [], None, None, [('Pass', (1, 8))])]),
('Module', [('ClassDef', (1, 0), 'C', [], [], None, None, [('Pass', (1, 8))], [], )]),
('Module', [('FunctionDef', (1, 0), 'f', ('arguments', [], None, None, [], None, None, [], []), [('Return', (1, 8), ('Num', (1, 15), 1))], [], None)]),
('Module', [('Delete', (1, 0), [('Name', (1, 4), 'v', ('Del',))])]),
('Module', [('Assign', (1, 0), [('Name', (1, 0), 'v', ('Store',))], ('Num', (1, 4), 1))]),

View File

@ -26,10 +26,10 @@ class BinASCIITest(unittest.TestCase):
prefixes.extend(["crc_", "rlecode_", "rledecode_"])
for prefix in prefixes:
name = prefix + suffix
self.assert_(callable(getattr(binascii, name)))
self.assert_(hasattr(getattr(binascii, name), '__call__'))
self.assertRaises(TypeError, getattr(binascii, name))
for name in ("hexlify", "unhexlify"):
self.assert_(callable(getattr(binascii, name)))
self.assert_(hasattr(getattr(binascii, name), '__call__'))
self.assertRaises(TypeError, getattr(binascii, name))
def test_base64valid(self):

View File

@ -168,8 +168,8 @@ class BoolTest(unittest.TestCase):
self.assertIs(hasattr([], "wobble"), False)
def test_callable(self):
self.assertIs(callable(len), True)
self.assertIs(callable(1), False)
self.assertIs(hasattr(len, '__call__'), True)
self.assertIs(hasattr(1, '__call__'), False)
def test_isinstance(self):
self.assertIs(isinstance(True, bool), True)

View File

@ -146,20 +146,21 @@ class BuiltinTest(unittest.TestCase):
self.assert_(isinstance(x, int))
self.assertEqual(-x, sys.maxint+1)
# XXX(nnorwitz): This test case for callable should probably be removed.
def test_callable(self):
self.assert_(callable(len))
self.assert_(hasattr(len, '__call__'))
def f(): pass
self.assert_(callable(f))
self.assert_(hasattr(f, '__call__'))
class C:
def meth(self): pass
self.assert_(callable(C))
self.assert_(hasattr(C, '__call__'))
x = C()
self.assert_(callable(x.meth))
self.assert_(not callable(x))
self.assert_(hasattr(x.meth, '__call__'))
self.assert_(not hasattr(x, '__call__'))
class D(C):
def __call__(self): pass
y = D()
self.assert_(callable(y))
self.assert_(hasattr(y, '__call__'))
y()
def test_chr(self):

View File

@ -13,8 +13,8 @@ if is_jython:
def unify_callables(d):
for n,v in d.items():
if callable(v):
d[n] = callable
if hasattr(v, '__call__'):
d[n] = True
return d
class CodeopTests(unittest.TestCase):

View File

@ -11,7 +11,9 @@ class TestNamedTuple(unittest.TestCase):
self.assertEqual(Point.__slots__, ())
self.assertEqual(Point.__module__, __name__)
self.assertEqual(Point.__getitem__, tuple.__getitem__)
self.assert_('__getitem__' in Point.__dict__) # superclass methods localized
self.assertRaises(ValueError, NamedTuple, 'abc%', 'def ghi')
self.assertRaises(ValueError, NamedTuple, 'abc', 'def g%hi')
NamedTuple('Point0', 'x1 y2') # Verify that numbers are allowed in names
def test_instance(self):
Point = NamedTuple('Point', 'x y')
@ -50,8 +52,10 @@ class TestNamedTuple(unittest.TestCase):
def test_main(verbose=None):
import collections as CollectionsModule
test_classes = [TestNamedTuple]
test_support.run_unittest(*test_classes)
test_support.run_doctest(CollectionsModule, verbose)
if __name__ == "__main__":
test_main(verbose=True)

View File

@ -266,8 +266,44 @@ class TestDecorators(unittest.TestCase):
self.assertEqual(bar(), 42)
self.assertEqual(actions, expected_actions)
class TestClassDecorators(unittest.TestCase):
def test_simple(self):
def plain(x):
x.extra = 'Hello'
return x
@plain
class C(object): pass
self.assertEqual(C.extra, 'Hello')
def test_double(self):
def ten(x):
x.extra = 10
return x
def add_five(x):
x.extra += 5
return x
@add_five
@ten
class C(object): pass
self.assertEqual(C.extra, 15)
def test_order(self):
def applied_first(x):
x.extra = 'first'
return x
def applied_second(x):
x.extra = 'second'
return x
@applied_second
@applied_first
class C(object): pass
self.assertEqual(C.extra, 'second')
def test_main():
test_support.run_unittest(TestDecorators)
test_support.run_unittest(TestClassDecorators)
if __name__=="__main__":
test_main()

View File

@ -1,5 +1,6 @@
from test.test_support import verify, verbose, TestFailed, sortdict
from UserList import UserList
from UserDict import UserDict
def e(a, b):
print(a, b)
@ -25,6 +26,12 @@ f(1, 2, 3, **{'a':4, 'b':5})
f(1, 2, 3, *(4, 5), **{'a':6, 'b':7})
f(1, 2, 3, x=4, y=5, *(6, 7), **{'a':8, 'b':9})
f(1, 2, 3, **UserDict(a=4, b=5))
f(1, 2, 3, *(4, 5), **UserDict(a=6, b=7))
f(1, 2, 3, x=4, y=5, *(6, 7), **UserDict(a=8, b=9))
# Verify clearing of SF bug #733667
try:
e(c=3)

View File

@ -194,8 +194,16 @@ class TimeoutTest(TestCase):
httpConn.close()
class HTTPSTimeoutTest(TestCase):
# XXX Here should be tests for HTTPS, there isn't any right now!
def test_attributes(self):
# simple test to check it's storing it
h = httplib.HTTPSConnection(HOST, PORT, timeout=30)
self.assertEqual(h.timeout, 30)
def test_main(verbose=None):
test_support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest)
test_support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest, HTTPSTimeoutTest)
if __name__ == '__main__':
test_main()

View File

@ -1,177 +0,0 @@
#! /usr/bin/env python
"""Test script for the imageop module. This has the side
effect of partially testing the imgfile module as well.
Roger E. Masse
"""
from test.test_support import verbose, unlink
import imageop, uu, os
import warnings
warnings.filterwarnings("ignore",
"the rgbimg module is deprecated",
DeprecationWarning,
".*test_imageop")
def main(use_rgbimg=1):
# Create binary test files
uu.decode(get_qualified_path('testrgb'+os.extsep+'uue'), 'test'+os.extsep+'rgb')
if use_rgbimg:
image, width, height = getrgbimage('test'+os.extsep+'rgb')
else:
image, width, height = getimage('test'+os.extsep+'rgb')
# Return the selected part of image, which should by width by height
# in size and consist of pixels of psize bytes.
if verbose:
print('crop')
newimage = imageop.crop (image, 4, width, height, 0, 0, 1, 1)
# Return image scaled to size newwidth by newheight. No interpolation
# is done, scaling is done by simple-minded pixel duplication or removal.
# Therefore, computer-generated images or dithered images will
# not look nice after scaling.
if verbose:
print('scale')
scaleimage = imageop.scale(image, 4, width, height, 1, 1)
# Run a vertical low-pass filter over an image. It does so by computing
# each destination pixel as the average of two vertically-aligned source
# pixels. The main use of this routine is to forestall excessive flicker
# if the image two vertically-aligned source pixels, hence the name.
if verbose:
print('tovideo')
videoimage = imageop.tovideo (image, 4, width, height)
# Convert an rgb image to an 8 bit rgb
if verbose:
print('rgb2rgb8')
greyimage = imageop.rgb2rgb8(image, width, height)
# Convert an 8 bit rgb image to a 24 bit rgb image
if verbose:
print('rgb82rgb')
image = imageop.rgb82rgb(greyimage, width, height)
# Convert an rgb image to an 8 bit greyscale image
if verbose:
print('rgb2grey')
greyimage = imageop.rgb2grey(image, width, height)
# Convert an 8 bit greyscale image to a 24 bit rgb image
if verbose:
print('grey2rgb')
image = imageop.grey2rgb(greyimage, width, height)
# Convert a 8-bit deep greyscale image to a 1-bit deep image by
# thresholding all the pixels. The resulting image is tightly packed
# and is probably only useful as an argument to mono2grey.
if verbose:
print('grey2mono')
monoimage = imageop.grey2mono (greyimage, width, height, 0)
# monoimage, width, height = getimage('monotest.rgb')
# Convert a 1-bit monochrome image to an 8 bit greyscale or color image.
# All pixels that are zero-valued on input get value p0 on output and
# all one-value input pixels get value p1 on output. To convert a
# monochrome black-and-white image to greyscale pass the values 0 and
# 255 respectively.
if verbose:
print('mono2grey')
greyimage = imageop.mono2grey (monoimage, width, height, 0, 255)
# Convert an 8-bit greyscale image to a 1-bit monochrome image using a
# (simple-minded) dithering algorithm.
if verbose:
print('dither2mono')
monoimage = imageop.dither2mono (greyimage, width, height)
# Convert an 8-bit greyscale image to a 4-bit greyscale image without
# dithering.
if verbose:
print('grey2grey4')
grey4image = imageop.grey2grey4 (greyimage, width, height)
# Convert an 8-bit greyscale image to a 2-bit greyscale image without
# dithering.
if verbose:
print('grey2grey2')
grey2image = imageop.grey2grey2 (greyimage, width, height)
# Convert an 8-bit greyscale image to a 2-bit greyscale image with
# dithering. As for dither2mono, the dithering algorithm is currently
# very simple.
if verbose:
print('dither2grey2')
grey2image = imageop.dither2grey2 (greyimage, width, height)
# Convert a 4-bit greyscale image to an 8-bit greyscale image.
if verbose:
print('grey42grey')
greyimage = imageop.grey42grey (grey4image, width, height)
# Convert a 2-bit greyscale image to an 8-bit greyscale image.
if verbose:
print('grey22grey')
image = imageop.grey22grey (grey2image, width, height)
# Cleanup
unlink('test'+os.extsep+'rgb')
def getrgbimage(name):
"""return a tuple consisting of image (in 'imgfile' format but
using rgbimg instead) width and height"""
import rgbimg
try:
sizes = rgbimg.sizeofimage(name)
except rgbimg.error:
name = get_qualified_path(name)
sizes = rgbimg.sizeofimage(name)
if verbose:
print('rgbimg opening test image: %s, sizes: %s' % (name, str(sizes)))
image = rgbimg.longimagedata(name)
return (image, sizes[0], sizes[1])
def getimage(name):
"""return a tuple consisting of
image (in 'imgfile' format) width and height
"""
import imgfile
try:
sizes = imgfile.getsizes(name)
except imgfile.error:
name = get_qualified_path(name)
sizes = imgfile.getsizes(name)
if verbose:
print('imgfile opening test image: %s, sizes: %s' % (name, str(sizes)))
image = imgfile.read(name)
return (image, sizes[0], sizes[1])
def get_qualified_path(name):
""" return a more qualified path to name"""
import sys
import os
path = sys.path
try:
path = [os.path.dirname(__file__)] + path
except NameError:
pass
for dir in path:
fullname = os.path.join(dir, name)
if os.path.exists(fullname):
return fullname
return name
# rgbimg (unlike imgfile) is portable to platforms other than SGI.
# So we prefer to use it.
main(use_rgbimg=1)

View File

@ -1,78 +0,0 @@
# Copyright (C) 2003 Python Software Foundation
import unittest
import warnings
warnings.filterwarnings("ignore", "macfs.*", DeprecationWarning, __name__)
import macfs
import os
import sys
import tempfile
from test import test_support
class TestMacfs(unittest.TestCase):
def setUp(self):
fp = open(test_support.TESTFN, 'w')
fp.write('hello world\n')
fp.close()
def tearDown(self):
try:
os.unlink(test_support.TESTFN)
except:
pass
def test_fsspec(self):
fss = macfs.FSSpec(test_support.TESTFN)
self.assertEqual(os.path.realpath(test_support.TESTFN), fss.as_pathname())
def test_fsref(self):
fsr = macfs.FSRef(test_support.TESTFN)
self.assertEqual(os.path.realpath(test_support.TESTFN), fsr.as_pathname())
def test_fsref_unicode(self):
if sys.getfilesystemencoding():
testfn_unicode = str(test_support.TESTFN)
fsr = macfs.FSRef(testfn_unicode)
self.assertEqual(os.path.realpath(test_support.TESTFN), fsr.as_pathname())
def test_coercion(self):
fss = macfs.FSSpec(test_support.TESTFN)
fsr = macfs.FSRef(test_support.TESTFN)
fss2 = fsr.as_fsspec()
fsr2 = fss.as_fsref()
self.assertEqual(fss.as_pathname(), fss2.as_pathname())
self.assertEqual(fsr.as_pathname(), fsr2.as_pathname())
def test_dates(self):
import time
fss = macfs.FSSpec(test_support.TESTFN)
now = int(time.time())
fss.SetDates(now, now+1, now+2)
dates = fss.GetDates()
self.assertEqual(dates, (now, now+1, now+2))
def test_ctor_type(self):
fss = macfs.FSSpec(test_support.TESTFN)
fss.SetCreatorType('Pyth', 'TEXT')
filecr, filetp = fss.GetCreatorType()
self.assertEqual((filecr, filetp), ('Pyth', 'TEXT'))
def test_alias(self):
fss = macfs.FSSpec(test_support.TESTFN)
alias = fss.NewAlias()
fss2, changed = alias.Resolve()
self.assertEqual(changed, 0)
self.assertEqual(fss.as_pathname(), fss2.as_pathname())
def test_fss_alias(self):
fss = macfs.FSSpec(test_support.TESTFN)
def test_main():
test_support.run_unittest(TestMacfs)
if __name__ == '__main__':
test_main()

View File

@ -51,7 +51,11 @@ class TestMacostools(unittest.TestCase):
def test_touched(self):
# This really only tests that nothing unforeseen happens.
macostools.touched(test_support.TESTFN)
import warnings
with test_support.guard_warnings_filter():
warnings.filterwarnings('ignore', 'macostools.touched*',
DeprecationWarning)
macostools.touched(test_support.TESTFN)
def test_copy(self):
try:

View File

@ -220,6 +220,30 @@ class BugsTestCase(unittest.TestCase):
except Exception:
pass
def test_loads_recursion(self):
s = 'c' + ('X' * 4*4) + '{' * 2**20
self.assertRaises(ValueError, marshal.loads, s)
def test_recursion_limit(self):
# Create a deeply nested structure.
head = last = []
# The max stack depth should match the value in Python/marshal.c.
MAX_MARSHAL_STACK_DEPTH = 2000
for i in range(MAX_MARSHAL_STACK_DEPTH - 2):
last.append([0])
last = last[-1]
# Verify we don't blow out the stack with dumps/load.
data = marshal.dumps(head)
new_head = marshal.loads(data)
# Don't use == to compare objects, it can exceed the recursion limit.
self.assertEqual(len(new_head), len(head))
self.assertEqual(len(new_head[0]), len(head[0]))
self.assertEqual(len(new_head[-1]), len(head[-1]))
last.append([0])
self.assertRaises(ValueError, marshal.dumps, head)
def test_main():
test_support.run_unittest(IntTestCase,
FloatTestCase,

View File

@ -1,70 +0,0 @@
# Testing rgbimg module
import warnings
warnings.filterwarnings("ignore",
"the rgbimg module is deprecated",
DeprecationWarning,
".*test_rgbimg$")
import rgbimg
import os, uu
from test.test_support import verbose, unlink, findfile
class error(Exception):
pass
print('RGBimg test suite:')
def testimg(rgb_file, raw_file):
rgb_file = findfile(rgb_file)
raw_file = findfile(raw_file)
width, height = rgbimg.sizeofimage(rgb_file)
rgb = rgbimg.longimagedata(rgb_file)
if len(rgb) != width * height * 4:
raise error, 'bad image length'
raw = open(raw_file, 'rb').read()
if rgb != raw:
raise error, \
'images don\'t match for '+rgb_file+' and '+raw_file
for depth in [1, 3, 4]:
rgbimg.longstoimage(rgb, width, height, depth, '@.rgb')
os.unlink('@.rgb')
table = [
('testrgb'+os.extsep+'uue', 'test'+os.extsep+'rgb'),
('testimg'+os.extsep+'uue', 'test'+os.extsep+'rawimg'),
('testimgr'+os.extsep+'uue', 'test'+os.extsep+'rawimg'+os.extsep+'rev'),
]
for source, target in table:
source = findfile(source)
target = findfile(target)
if verbose:
print("uudecoding", source, "->", target, "...")
uu.decode(source, target)
if verbose:
print("testing...")
ttob = rgbimg.ttob(0)
if ttob != 0:
raise error, 'ttob should start out as zero'
testimg('test'+os.extsep+'rgb', 'test'+os.extsep+'rawimg')
ttob = rgbimg.ttob(1)
if ttob != 0:
raise error, 'ttob should be zero'
testimg('test'+os.extsep+'rgb', 'test'+os.extsep+'rawimg'+os.extsep+'rev')
ttob = rgbimg.ttob(0)
if ttob != 1:
raise error, 'ttob should be one'
ttob = rgbimg.ttob(0)
if ttob != 0:
raise error, 'ttob should be zero'
for source, target in table:
unlink(findfile(target))

View File

@ -124,7 +124,7 @@ class ThreadableTest:
self.server_ready.wait()
self.client_ready.set()
self.clientSetUp()
if not callable(test_func):
if not hasattr(test_func, '__call__'):
raise TypeError, "test_func must be a callable function"
try:
test_func()

View File

@ -1,75 +1,72 @@
"""Do a minimal test of all the modules that aren't otherwise tested."""
from test.test_support import guard_warnings_filter
import warnings
warnings.filterwarnings('ignore', r".*posixfile module",
DeprecationWarning, 'posixfile$')
warnings.filterwarnings("ignore",
"the gopherlib module is deprecated",
DeprecationWarning,
".*test_sundry")
with guard_warnings_filter():
warnings.filterwarnings('ignore', r".*posixfile",
DeprecationWarning)
from test.test_support import verbose
from test.test_support import verbose
import BaseHTTPServer
import DocXMLRPCServer
import CGIHTTPServer
import SimpleHTTPServer
import SimpleXMLRPCServer
import aifc
import audiodev
import bdb
import cgitb
import cmd
import code
import compileall
import encodings
import formatter
import ftplib
import getpass
import gopherlib
import htmlentitydefs
import ihooks
import imghdr
import imputil
import keyword
import linecache
import macurl2path
import mailcap
import mimify
import mutex
import nntplib
import nturl2path
import opcode
import os2emxpath
import pdb
import pipes
#import poplib
import posixfile
import pstats
import py_compile
import pydoc
import rlcompleter
import sched
import smtplib
import sndhdr
import statvfs
import sunau
import sunaudio
import symbol
import tabnanny
import telnetlib
import timeit
import toaiff
import token
try:
import tty # not available on Windows
except ImportError:
if verbose:
print("skipping tty")
import BaseHTTPServer
import DocXMLRPCServer
import CGIHTTPServer
import SimpleHTTPServer
import SimpleXMLRPCServer
import aifc
import audiodev
import bdb
import cgitb
import cmd
import code
import compileall
import encodings
import formatter
import ftplib
import getpass
import htmlentitydefs
import ihooks
import imghdr
import imputil
import keyword
import linecache
import macurl2path
import mailcap
import mimify
import mutex
import nntplib
import nturl2path
import opcode
import os2emxpath
import pdb
import pipes
#import poplib
import posixfile
import pstats
import py_compile
import pydoc
import rlcompleter
import sched
import smtplib
import sndhdr
import statvfs
import sunau
import sunaudio
import symbol
import tabnanny
import telnetlib
import timeit
import toaiff
import token
try:
import tty # not available on Windows
except ImportError:
if verbose:
print("skipping tty")
# Can't test the "user" module -- if the user has a ~/.pythonrc.py, it
# can screw up all sorts of things (esp. if it prints!).
#import user
import webbrowser
import xml
# Can't test the "user" module -- if the user has a ~/.pythonrc.py, it
# can screw up all sorts of things (esp. if it prints!).
#import user
import webbrowser
import xml

View File

@ -173,19 +173,6 @@ class OtherNetworkTests(unittest.TestCase):
]
self._test_urls(urls, self._extra_handlers())
def test_gopher(self):
import warnings
warnings.filterwarnings("ignore",
"the gopherlib module is deprecated",
DeprecationWarning,
"urllib2$")
urls = [
# Thanks to Fred for finding these!
'gopher://gopher.lib.ncsu.edu./11/library/stacks/Alex',
'gopher://gopher.vt.edu.:10010/10/33',
]
self._test_urls(urls, self._extra_handlers())
def test_file(self):
TESTFN = test_support.TESTFN
f = open(TESTFN, 'w')
@ -274,8 +261,6 @@ class OtherNetworkTests(unittest.TestCase):
def _extra_handlers(self):
handlers = []
handlers.append(urllib2.GopherHandler)
cfh = urllib2.CacheFTPHandler()
cfh.setTimeout(1)
handlers.append(cfh)

View File

@ -36,7 +36,7 @@ def sanity():
"""
def check_method(method):
if not callable(method):
if not hasattr(method, '__call__'):
print(method, "not callable")
def serialize(ET, elem, encoding=None):

View File

@ -34,7 +34,7 @@ def sanity():
"""
def check_method(method):
if not callable(method):
if not hasattr(method, '__call__'):
print(method, "not callable")
def serialize(ET, elem, encoding=None):

View File

@ -55,7 +55,7 @@ elif hName == '_hashlib' and len(sys.argv) == 3:
import _hashlib
exec('creatorFunc = lambda x=_hashlib.new : x(%r)' % sys.argv[2])
print("testing speed of _hashlib.new(%r)" % sys.argv[2])
elif hasattr(hashlib, hName) and callable(getattr(hashlib, hName)):
elif hasattr(hashlib, hName) and hasattr(getattr(hashlib, hName), '__call__'):
creatorFunc = getattr(hashlib, hName)
print("testing speed of hashlib."+hName, getattr(hashlib, hName))
else:

View File

@ -126,7 +126,7 @@ class Timer:
if isinstance(setup, basestring):
setup = reindent(setup, 4)
src = template % {'stmt': stmt, 'setup': setup}
elif callable(setup):
elif hasattr(setup, '__call__'):
src = template % {'stmt': stmt, 'setup': '_setup()'}
ns['_setup'] = setup
else:
@ -135,13 +135,13 @@ class Timer:
code = compile(src, dummy_src_name, "exec")
exec(code, globals(), ns)
self.inner = ns["inner"]
elif callable(stmt):
elif hasattr(stmt, '__call__'):
self.src = None
if isinstance(setup, basestring):
_setup = setup
def setup():
exec(_setup, globals(), ns)
elif not callable(setup):
elif not hasattr(setup, '__call__'):
raise ValueError("setup is neither a string nor callable")
self.inner = _template_func(setup, stmt)
else:

View File

@ -426,7 +426,7 @@ class TestSuite:
def addTest(self, test):
# sanity checks
if not callable(test):
if not hasattr(test, '__call__'):
raise TypeError("the test to add must be callable")
if (isinstance(test, (type, types.ClassType)) and
issubclass(test, (TestCase, TestSuite))):
@ -581,7 +581,7 @@ class TestLoader:
return TestSuite([parent(obj.__name__)])
elif isinstance(obj, TestSuite):
return obj
elif callable(obj):
elif hasattr(obj, '__call__'):
test = obj()
if isinstance(test, TestSuite):
return test
@ -604,7 +604,7 @@ class TestLoader:
"""Return a sorted sequence of method names found within testCaseClass
"""
def isTestMethod(attrname, testCaseClass=testCaseClass, prefix=self.testMethodPrefix):
return attrname.startswith(prefix) and callable(getattr(testCaseClass, attrname))
return attrname.startswith(prefix) and hasattr(getattr(testCaseClass, attrname), '__call__')
testFnNames = filter(isTestMethod, dir(testCaseClass))
if self.sortTestMethodsUsing:
testFnNames.sort(self.sortTestMethodsUsing)

View File

@ -34,7 +34,7 @@ __all__ = ["urlopen", "URLopener", "FancyURLopener", "urlretrieve",
"localhost", "thishost", "ftperrors", "basejoin", "unwrap",
"splittype", "splithost", "splituser", "splitpasswd", "splitport",
"splitnport", "splitquery", "splitattr", "splitvalue",
"splitgophertype", "getproxies"]
"getproxies"]
__version__ = '1.17' # XXX This version is not always updated :-(
@ -432,24 +432,6 @@ class URLopener:
return self.http_error(url, fp, errcode, errmsg, headers,
data)
def open_gopher(self, url):
"""Use Gopher protocol."""
if not isinstance(url, str):
raise IOError, ('gopher error', 'proxy support for gopher protocol currently not implemented')
import gopherlib
host, selector = splithost(url)
if not host: raise IOError, ('gopher error', 'no host given')
host = unquote(host)
type, selector = splitgophertype(selector)
selector, query = splitquery(selector)
selector = unquote(selector)
if query:
query = unquote(query)
fp = gopherlib.send_query(selector, query, host)
else:
fp = gopherlib.send_selector(selector, host)
return addinfourl(fp, noheaders(), "gopher:" + url)
def open_file(self, url):
"""Use local file or FTP depending on form of URL."""
if not isinstance(url, str):
@ -967,7 +949,6 @@ class addinfourl(addbase):
# splitattr('/path;attr1=value1;attr2=value2;...') ->
# '/path', ['attr1=value1', 'attr2=value2', ...]
# splitvalue('attr=value') --> 'attr', 'value'
# splitgophertype('/Xselector') --> 'X', 'selector'
# unquote('abc%20def') -> 'abc def'
# quote('abc def') -> 'abc%20def')
@ -1127,12 +1108,6 @@ def splitvalue(attr):
if match: return match.group(1, 2)
return attr, None
def splitgophertype(selector):
"""splitgophertype('/Xselector') --> 'X', 'selector'."""
if selector[:1] == '/' and selector[1:2]:
return selector[1], selector[2:]
return None, selector
_hextochr = dict(('%02x' % i, chr(i)) for i in range(256))
_hextochr.update(('%02X' % i, chr(i)) for i in range(256))
@ -1469,7 +1444,6 @@ def test(args=[]):
'file:/etc/passwd',
'file://localhost/etc/passwd',
'ftp://ftp.gnu.org/pub/README',
## 'gopher://gopher.micro.umn.edu/1/',
'http://www.python.org/index.html',
]
if hasattr(URLopener, "open_https"):

View File

@ -104,7 +104,7 @@ import bisect
from io import StringIO
from urllib import (unwrap, unquote, splittype, splithost, quote,
addinfourl, splitport, splitgophertype, splitquery,
addinfourl, splitport, splitquery,
splitattr, ftpwrapper, noheaders, splituser, splitpasswd, splitvalue)
# support for FileHandler, proxies via environment variables
@ -161,9 +161,6 @@ class HTTPError(URLError, addinfourl):
def __str__(self):
return 'HTTP Error %s: %s' % (self.code, self.msg)
class GopherError(URLError):
pass
# copied from cookielib.py
_cut_port_re = re.compile(r":\d+$")
def request_host(request):
@ -1337,22 +1334,3 @@ class CacheFTPHandler(FTPHandler):
del self.timeout[k]
break
self.soonest = min(list(self.timeout.values()))
class GopherHandler(BaseHandler):
def gopher_open(self, req):
# XXX can raise socket.error
import gopherlib # this raises DeprecationWarning in 2.5
host = req.get_host()
if not host:
raise GopherError('no host given')
host = unquote(host)
selector = req.get_selector()
type, selector = splitgophertype(selector)
selector, query = splitquery(selector)
selector = unquote(selector)
if query:
query = unquote(query)
fp = gopherlib.send_query(selector, query, host)
else:
fp = gopherlib.send_selector(selector, host)
return addinfourl(fp, noheaders(), req.get_full_url())

View File

@ -429,6 +429,7 @@ Dieter Maurer
Greg McFarlane
Michael McLay
Gordon McMillan
Damien Miller
Jay T. Miller
Chris McDonough
Andrew McNamara

View File

@ -39,5 +39,4 @@ Install:
make install
- Donn Cave (donn@oz.net)
October 4, 2000
Maintainer: Mikael Jansson (mail at mikael.jansson.be)

122
Misc/NEWS
View File

@ -28,8 +28,6 @@ Core and Builtins
- Remove BaseException.message.
- Remove strop module.
- Remove tuple parameter unpacking (PEP 3113).
- Remove the f_restricted attribute from frames. This naturally leads to teh
@ -41,8 +39,6 @@ Core and Builtins
- range() now returns an iterator rather than a list. Floats are not allowed.
xrange() is no longer defined.
- Merged from (2.6) trunk at r54987.
- Patch #1660500: hide iteration variable in list comps, add set comps
and use common code to handle compilation of iterative expressions
@ -66,8 +62,6 @@ Core and Builtins
- Removed indexing/slicing on BaseException.
- Removed the exceptions module, all the exceptions are already builtin.
- input() became raw_input(): the name input() now implements the
functionality formerly known as raw_input(); the name raw_input()
is no longer defined.
@ -138,19 +132,71 @@ Core and Builtins
- Absolute import is the default behavior for 'import foo' etc.
- Removed support for syntax:
backticks (`x`), <>
backticks (ie, `x`), <>
- Removed these Python builtins:
apply(), coerce()
apply(), callable(), coerce(), file()
- Removed these Python methods:
{}.has_key
- Removed these Python slots:
__coerce__, __div__, __idiv__, __rdiv__
- Removed these opcodes:
BINARY_DIVIDE, INPLACE_DIVIDE, UNARY_CONVERT
- Remove C API support for restricted execution.
- zip returns an iterator
- Additions:
set literals, ellipsis literal
- Added class decorators per PEP 3129.
Extension Modules
-----------------
- Remove the imageop module. Obsolete long with its unit tests becoming
useless from the removal of rgbimg and imgfile.
- Removed these attributes from Python modules:
* operator module: div, idiv, __div__, __idiv__
* operator module: div, idiv, __div__, __idiv__, isCallable, sequenceIncludes
Library
-------
- Remove the compiler package. Use of the _ast module and (an eventual)
AST -> bytecode mechanism.
- Removed these modules:
* Bastion, bsddb185, exceptions, md5, popen2, rexec,
sets, sha, stringold, strop, xmllib
- Remove obsolete IRIX modules: al/AL, cd/CD, cddb, cdplayer, cl/CL, DEVICE,
ERRNO, FILE, fl/FL, flp, fm, GET, gl/GL, GLWS, IN, imgfile, IOCTL, jpeg,
panel, panelparser, readcd, sgi, sv/SV, torgb, WAIT.
- Remove obsolete functions:
* commands.getstatus(), os.popen*,
- Remove functions in the string module that are also string methods.
- Remove support for long obsolete platforms: plat-aix3, plat-irix5.
- Remove xmlrpclib.SlowParser. It was based on xmllib.
- Patch #1680961: atexit has been reimplemented in C.
Build
-----
C API
-----
- Removed these Python slots:
__coerce__, __div__, __idiv__, __rdiv__
- Removed these C APIs:
PyNumber_Coerce(), PyNumber_CoerceEx()
@ -165,60 +211,6 @@ Core and Builtins
intargfunc, intintargfunc, intobjargproc, intintobjargproc,
getreadbufferproc, getwritebufferproc, getsegcountproc, getcharbufferproc
- Removed these opcodes:
BINARY_DIVIDE, INPLACE_DIVIDE, UNARY_CONVERT
- zip returns an iterator
- Additions:
set literals, ellipsis literal
Extension Modules
-----------------
- isCallable() and sequenceIncludes() have been removed from the operator
module.
Library
-------
- Remove popen2 module and os.popen* functions.
- Remove the compiler package. Use of the _ast module and (an eventual)
AST -> bytecode mechanism.
- Remove md5 and sha. Both have been deprecated since Python 2.5.
- Remove Bastion and rexec as they have been disabled since Python 2.3 (this
also leads to the C API support for restricted execution).
- Remove obsolete IRIX modules: al/AL, cd/CD, cddb, cdplayer, cl/CL, DEVICE,
ERRNO, FILE, fl/FL, flp, fm, GET, gl/GL, GLWS, IN, imgfile, IOCTL, jpeg,
panel, panelparser, readcd, sgi, sv/SV, torgb, WAIT.
- Remove bsddb185 module; it was obsolete.
- Remove commands.getstatus(); it was obsolete.
- Remove functions in string and strop modules that are also string methods.
- Remove obsolete modules: xmllib, stringold.
- Remove support for long obsolete platforms: plat-aix3, plat-irix5.
- Remove xmlrpclib.SlowParser. It was based on xmllib.
- Patch #1680961: atexit has been reimplemented in C.
- Removed all traces of the sets module.
Build
-----
C API
-----
Tests
-----

View File

@ -17,6 +17,10 @@ the format to accommodate documentation needs as they arise.
Permissions History
-------------------
- Alexandre Vassalotti was given SVN access on May 21 2007
by MvL, for his Summer-of-Code project, mentored by
Brett Cannon.
- Travis Oliphant was given SVN access on 17 Apr 2007 by MvL,
for implementing the extended buffer protocol.

View File

@ -218,8 +218,6 @@ _symtable symtablemodule.c
# These represent audio samples or images as strings:
#audioop audioop.c # Operations on audio samples
#imageop imageop.c # Operations on images
#rgbimg rgbimgmodule.c # Read SGI RGB image files (but coded portably)
# Note that the _md5 and _sha modules are normally only built if the

View File

@ -1724,6 +1724,7 @@ DB_get_both(DBObject* self, PyObject* args, PyObject* kwargs)
CHECK_DB_NOT_CLOSED(self);
if (!make_key_dbt(self, keyobj, &key, NULL))
return NULL;
CLEAR_DBT(data);
if ( !make_dbt(dataobj, &data) ||
!checkTxnObj(txnobj, &txn) )
{

View File

@ -1299,7 +1299,7 @@ static PyObject *
PyCursesWindow_RedrawLine(PyCursesWindowObject *self, PyObject *args)
{
int beg, num;
if (!PyArg_ParseTuple(args,"ii;beg,num", &beg, &num))
if (!PyArg_ParseTuple(args, "ii;beg,num", &beg, &num))
return NULL;
return PyCursesCheckERR(wredrawln(self->win,beg,num), "redrawln");
}
@ -1533,7 +1533,7 @@ static PyMethodDef PyCursesWindow_Methods[] = {
{"overwrite", (PyCFunction)PyCursesWindow_Overwrite,
METH_VARARGS},
{"putwin", (PyCFunction)PyCursesWindow_PutWin, METH_VARARGS},
{"redrawln", (PyCFunction)PyCursesWindow_RedrawLine},
{"redrawln", (PyCFunction)PyCursesWindow_RedrawLine, METH_VARARGS},
{"redrawwin", (PyCFunction)PyCursesWindow_redrawwin, METH_NOARGS},
{"refresh", (PyCFunction)PyCursesWindow_Refresh, METH_VARARGS},
#ifndef STRICT_SYSV_CURSES

View File

@ -1817,7 +1817,7 @@ static struct PyMethodDef s_methods[] = {
{"pack", s_pack, METH_VARARGS, s_pack__doc__},
{"pack_into", s_pack_into, METH_VARARGS, s_pack_into__doc__},
{"unpack", s_unpack, METH_O, s_unpack__doc__},
{"unpack_from", (PyCFunction)s_unpack_from, METH_KEYWORDS,
{"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS,
s_unpack_from__doc__},
{NULL, NULL} /* sentinel */
};

View File

@ -2668,8 +2668,8 @@ static PyMethodDef Tkapp_methods[] =
{
{"willdispatch", Tkapp_WillDispatch, METH_NOARGS},
{"wantobjects", Tkapp_WantObjects, METH_VARARGS},
{"call", Tkapp_Call, METH_OLDARGS},
{"globalcall", Tkapp_GlobalCall, METH_OLDARGS},
{"call", Tkapp_Call, METH_VARARGS},
{"globalcall", Tkapp_GlobalCall, METH_VARARGS},
{"eval", Tkapp_Eval, METH_VARARGS},
{"globaleval", Tkapp_GlobalEval, METH_VARARGS},
{"evalfile", Tkapp_EvalFile, METH_VARARGS},
@ -2690,7 +2690,7 @@ static PyMethodDef Tkapp_methods[] =
{"exprboolean", Tkapp_ExprBoolean, METH_VARARGS},
{"splitlist", Tkapp_SplitList, METH_VARARGS},
{"split", Tkapp_Split, METH_VARARGS},
{"merge", Tkapp_Merge, METH_OLDARGS},
{"merge", Tkapp_Merge, METH_VARARGS},
{"createcommand", Tkapp_CreateCommand, METH_VARARGS},
{"deletecommand", Tkapp_DeleteCommand, METH_VARARGS},
#ifdef HAVE_CREATEFILEHANDLER

View File

@ -2603,7 +2603,7 @@ static PyMethodDef date_methods[] = {
{"ctime", (PyCFunction)date_ctime, METH_NOARGS,
PyDoc_STR("Return ctime() style string.")},
{"strftime", (PyCFunction)date_strftime, METH_KEYWORDS,
{"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
PyDoc_STR("format -> strftime() style string.")},
{"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
@ -2628,7 +2628,7 @@ static PyMethodDef date_methods[] = {
PyDoc_STR("Return the day of the week represented by the date.\n"
"Monday == 0 ... Sunday == 6")},
{"replace", (PyCFunction)date_replace, METH_KEYWORDS,
{"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
PyDoc_STR("Return date with new specified fields.")},
{"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
@ -3375,7 +3375,7 @@ static PyMethodDef time_methods[] = {
PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
"[+HH:MM].")},
{"strftime", (PyCFunction)time_strftime, METH_KEYWORDS,
{"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
PyDoc_STR("format -> strftime() style string.")},
{"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
@ -3387,7 +3387,7 @@ static PyMethodDef time_methods[] = {
{"dst", (PyCFunction)time_dst, METH_NOARGS,
PyDoc_STR("Return self.tzinfo.dst(self).")},
{"replace", (PyCFunction)time_replace, METH_KEYWORDS,
{"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
PyDoc_STR("Return time with new specified fields.")},
{"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
@ -4411,7 +4411,7 @@ static PyMethodDef datetime_methods[] = {
/* Class methods: */
{"now", (PyCFunction)datetime_now,
METH_KEYWORDS | METH_CLASS,
METH_VARARGS | METH_KEYWORDS | METH_CLASS,
PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
{"utcnow", (PyCFunction)datetime_utcnow,
@ -4419,7 +4419,7 @@ static PyMethodDef datetime_methods[] = {
PyDoc_STR("Return a new datetime representing UTC day and time.")},
{"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
METH_KEYWORDS | METH_CLASS,
METH_VARARGS | METH_KEYWORDS | METH_CLASS,
PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
{"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
@ -4456,7 +4456,7 @@ static PyMethodDef datetime_methods[] = {
{"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
{"isoformat", (PyCFunction)datetime_isoformat, METH_KEYWORDS,
{"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
PyDoc_STR("[sep] -> string in ISO 8601 format, "
"YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
"sep is used to separate the year from the time, and "
@ -4471,10 +4471,10 @@ static PyMethodDef datetime_methods[] = {
{"dst", (PyCFunction)datetime_dst, METH_NOARGS,
PyDoc_STR("Return self.tzinfo.dst(self).")},
{"replace", (PyCFunction)datetime_replace, METH_KEYWORDS,
{"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
PyDoc_STR("Return datetime with new specified fields.")},
{"astimezone", (PyCFunction)datetime_astimezone, METH_KEYWORDS,
{"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
{"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,

View File

@ -1,785 +0,0 @@
/* imageopmodule - Various operations on pictures */
#ifdef sun
#define signed
#endif
#include "Python.h"
#if SIZEOF_INT == 4
typedef int Py_Int32;
typedef unsigned int Py_UInt32;
#else
#if SIZEOF_LONG == 4
typedef long Py_Int32;
typedef unsigned long Py_UInt32;
#else
#error "No 4-byte integral type"
#endif
#endif
#define CHARP(cp, xmax, x, y) ((char *)(cp+y*xmax+x))
#define SHORTP(cp, xmax, x, y) ((short *)(cp+2*(y*xmax+x)))
#define LONGP(cp, xmax, x, y) ((Py_Int32 *)(cp+4*(y*xmax+x)))
static PyObject *ImageopError;
static PyObject *ImageopDict;
/* If this function returns true (the default if anything goes wrong), we're
behaving in a backward-compatible way with respect to how multi-byte pixels
are stored in the strings. The code in this module was originally written
for an SGI which is a big-endian system, and so the old code assumed that
4-byte integers hold the R, G, and B values in a particular order.
However, on little-endian systems the order is reversed, and so not
actually compatible with what gl.lrectwrite and imgfile expect.
(gl.lrectwrite and imgfile are also SGI-specific, however, it is
conceivable that the data handled here comes from or goes to an SGI or that
it is otherwise used in the expectation that the byte order in the strings
is as specified.)
The function returns the value of the module variable
"backward_compatible", or 1 if the variable does not exist or is not an
int.
*/
static int
imageop_backward_compatible(void)
{
static PyObject *bcos;
PyObject *bco;
long rc;
if (ImageopDict == NULL) /* "cannot happen" */
return 1;
if (bcos == NULL) {
/* cache string object for future use */
bcos = PyString_FromString("backward_compatible");
if (bcos == NULL)
return 1;
}
bco = PyDict_GetItem(ImageopDict, bcos);
if (bco == NULL)
return 1;
if (!PyInt_Check(bco))
return 1;
rc = PyInt_AsLong(bco);
if (PyErr_Occurred()) {
/* not an integer, or too large, or something */
PyErr_Clear();
rc = 1;
}
return rc != 0; /* convert to values 0, 1 */
}
static PyObject *
imageop_crop(PyObject *self, PyObject *args)
{
char *cp, *ncp;
short *nsp;
Py_Int32 *nlp;
int len, size, x, y, newx1, newx2, newy1, newy2;
int ix, iy, xstep, ystep;
PyObject *rv;
if ( !PyArg_ParseTuple(args, "s#iiiiiii", &cp, &len, &size, &x, &y,
&newx1, &newy1, &newx2, &newy2) )
return 0;
if ( size != 1 && size != 2 && size != 4 ) {
PyErr_SetString(ImageopError, "Size should be 1, 2 or 4");
return 0;
}
if ( len != size*x*y ) {
PyErr_SetString(ImageopError, "String has incorrect length");
return 0;
}
xstep = (newx1 < newx2)? 1 : -1;
ystep = (newy1 < newy2)? 1 : -1;
rv = PyString_FromStringAndSize(NULL,
(abs(newx2-newx1)+1)*(abs(newy2-newy1)+1)*size);
if ( rv == 0 )
return 0;
ncp = (char *)PyString_AsString(rv);
nsp = (short *)ncp;
nlp = (Py_Int32 *)ncp;
newy2 += ystep;
newx2 += xstep;
for( iy = newy1; iy != newy2; iy+=ystep ) {
for ( ix = newx1; ix != newx2; ix+=xstep ) {
if ( iy < 0 || iy >= y || ix < 0 || ix >= x ) {
if ( size == 1 )
*ncp++ = 0;
else
*nlp++ = 0;
} else {
if ( size == 1 )
*ncp++ = *CHARP(cp, x, ix, iy);
else if ( size == 2 )
*nsp++ = *SHORTP(cp, x, ix, iy);
else
*nlp++ = *LONGP(cp, x, ix, iy);
}
}
}
return rv;
}
static PyObject *
imageop_scale(PyObject *self, PyObject *args)
{
char *cp, *ncp;
short *nsp;
Py_Int32 *nlp;
int len, size, x, y, newx, newy;
int ix, iy;
int oix, oiy;
PyObject *rv;
if ( !PyArg_ParseTuple(args, "s#iiiii",
&cp, &len, &size, &x, &y, &newx, &newy) )
return 0;
if ( size != 1 && size != 2 && size != 4 ) {
PyErr_SetString(ImageopError, "Size should be 1, 2 or 4");
return 0;
}
if ( len != size*x*y ) {
PyErr_SetString(ImageopError, "String has incorrect length");
return 0;
}
rv = PyString_FromStringAndSize(NULL, newx*newy*size);
if ( rv == 0 )
return 0;
ncp = (char *)PyString_AsString(rv);
nsp = (short *)ncp;
nlp = (Py_Int32 *)ncp;
for( iy = 0; iy < newy; iy++ ) {
for ( ix = 0; ix < newx; ix++ ) {
oix = ix * x / newx;
oiy = iy * y / newy;
if ( size == 1 )
*ncp++ = *CHARP(cp, x, oix, oiy);
else if ( size == 2 )
*nsp++ = *SHORTP(cp, x, oix, oiy);
else
*nlp++ = *LONGP(cp, x, oix, oiy);
}
}
return rv;
}
/* Note: this routine can use a bit of optimizing */
static PyObject *
imageop_tovideo(PyObject *self, PyObject *args)
{
int maxx, maxy, x, y, len;
int i;
unsigned char *cp, *ncp;
int width;
PyObject *rv;
if ( !PyArg_ParseTuple(args, "s#iii", &cp, &len, &width, &maxx, &maxy) )
return 0;
if ( width != 1 && width != 4 ) {
PyErr_SetString(ImageopError, "Size should be 1 or 4");
return 0;
}
if ( maxx*maxy*width != len ) {
PyErr_SetString(ImageopError, "String has incorrect length");
return 0;
}
rv = PyString_FromStringAndSize(NULL, len);
if ( rv == 0 )
return 0;
ncp = (unsigned char *)PyString_AsString(rv);
if ( width == 1 ) {
memcpy(ncp, cp, maxx); /* Copy first line */
ncp += maxx;
for (y=1; y<maxy; y++) { /* Interpolate other lines */
for(x=0; x<maxx; x++) {
i = y*maxx + x;
*ncp++ = ((int)cp[i] + (int)cp[i-maxx]) >> 1;
}
}
} else {
memcpy(ncp, cp, maxx*4); /* Copy first line */
ncp += maxx*4;
for (y=1; y<maxy; y++) { /* Interpolate other lines */
for(x=0; x<maxx; x++) {
i = (y*maxx + x)*4 + 1;
*ncp++ = 0; /* Skip alfa comp */
*ncp++ = ((int)cp[i] + (int)cp[i-4*maxx]) >> 1;
i++;
*ncp++ = ((int)cp[i] + (int)cp[i-4*maxx]) >> 1;
i++;
*ncp++ = ((int)cp[i] + (int)cp[i-4*maxx]) >> 1;
}
}
}
return rv;
}
static PyObject *
imageop_grey2mono(PyObject *self, PyObject *args)
{
int tres, x, y, len;
unsigned char *cp, *ncp;
unsigned char ovalue;
PyObject *rv;
int i, bit;
if ( !PyArg_ParseTuple(args, "s#iii", &cp, &len, &x, &y, &tres) )
return 0;
if ( x*y != len ) {
PyErr_SetString(ImageopError, "String has incorrect length");
return 0;
}
rv = PyString_FromStringAndSize(NULL, (len+7)/8);
if ( rv == 0 )
return 0;
ncp = (unsigned char *)PyString_AsString(rv);
bit = 0x80;
ovalue = 0;
for ( i=0; i < len; i++ ) {
if ( (int)cp[i] > tres )
ovalue |= bit;
bit >>= 1;
if ( bit == 0 ) {
*ncp++ = ovalue;
bit = 0x80;
ovalue = 0;
}
}
if ( bit != 0x80 )
*ncp++ = ovalue;
return rv;
}
static PyObject *
imageop_grey2grey4(PyObject *self, PyObject *args)
{
int x, y, len;
unsigned char *cp, *ncp;
unsigned char ovalue;
PyObject *rv;
int i;
int pos;
if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
return 0;
if ( x*y != len ) {
PyErr_SetString(ImageopError, "String has incorrect length");
return 0;
}
rv = PyString_FromStringAndSize(NULL, (len+1)/2);
if ( rv == 0 )
return 0;
ncp = (unsigned char *)PyString_AsString(rv);
pos = 0;
ovalue = 0;
for ( i=0; i < len; i++ ) {
ovalue |= ((int)cp[i] & 0xf0) >> pos;
pos += 4;
if ( pos == 8 ) {
*ncp++ = ovalue;
ovalue = 0;
pos = 0;
}
}
if ( pos != 0 )
*ncp++ = ovalue;
return rv;
}
static PyObject *
imageop_grey2grey2(PyObject *self, PyObject *args)
{
int x, y, len;
unsigned char *cp, *ncp;
unsigned char ovalue;
PyObject *rv;
int i;
int pos;
if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
return 0;
if ( x*y != len ) {
PyErr_SetString(ImageopError, "String has incorrect length");
return 0;
}
rv = PyString_FromStringAndSize(NULL, (len+3)/4);
if ( rv == 0 )
return 0;
ncp = (unsigned char *)PyString_AsString(rv);
pos = 0;
ovalue = 0;
for ( i=0; i < len; i++ ) {
ovalue |= ((int)cp[i] & 0xc0) >> pos;
pos += 2;
if ( pos == 8 ) {
*ncp++ = ovalue;
ovalue = 0;
pos = 0;
}
}
if ( pos != 0 )
*ncp++ = ovalue;
return rv;
}
static PyObject *
imageop_dither2mono(PyObject *self, PyObject *args)
{
int sum, x, y, len;
unsigned char *cp, *ncp;
unsigned char ovalue;
PyObject *rv;
int i, bit;
if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
return 0;
if ( x*y != len ) {
PyErr_SetString(ImageopError, "String has incorrect length");
return 0;
}
rv = PyString_FromStringAndSize(NULL, (len+7)/8);
if ( rv == 0 )
return 0;
ncp = (unsigned char *)PyString_AsString(rv);
bit = 0x80;
ovalue = 0;
sum = 0;
for ( i=0; i < len; i++ ) {
sum += cp[i];
if ( sum >= 256 ) {
sum -= 256;
ovalue |= bit;
}
bit >>= 1;
if ( bit == 0 ) {
*ncp++ = ovalue;
bit = 0x80;
ovalue = 0;
}
}
if ( bit != 0x80 )
*ncp++ = ovalue;
return rv;
}
static PyObject *
imageop_dither2grey2(PyObject *self, PyObject *args)
{
int x, y, len;
unsigned char *cp, *ncp;
unsigned char ovalue;
PyObject *rv;
int i;
int pos;
int sum = 0, nvalue;
if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
return 0;
if ( x*y != len ) {
PyErr_SetString(ImageopError, "String has incorrect length");
return 0;
}
rv = PyString_FromStringAndSize(NULL, (len+3)/4);
if ( rv == 0 )
return 0;
ncp = (unsigned char *)PyString_AsString(rv);
pos = 1;
ovalue = 0;
for ( i=0; i < len; i++ ) {
sum += cp[i];
nvalue = sum & 0x180;
sum -= nvalue;
ovalue |= nvalue >> pos;
pos += 2;
if ( pos == 9 ) {
*ncp++ = ovalue;
ovalue = 0;
pos = 1;
}
}
if ( pos != 0 )
*ncp++ = ovalue;
return rv;
}
static PyObject *
imageop_mono2grey(PyObject *self, PyObject *args)
{
int v0, v1, x, y, len, nlen;
unsigned char *cp, *ncp;
PyObject *rv;
int i, bit;
if ( !PyArg_ParseTuple(args, "s#iiii", &cp, &len, &x, &y, &v0, &v1) )
return 0;
nlen = x*y;
if ( (nlen+7)/8 != len ) {
PyErr_SetString(ImageopError, "String has incorrect length");
return 0;
}
rv = PyString_FromStringAndSize(NULL, nlen);
if ( rv == 0 )
return 0;
ncp = (unsigned char *)PyString_AsString(rv);
bit = 0x80;
for ( i=0; i < nlen; i++ ) {
if ( *cp & bit )
*ncp++ = v1;
else
*ncp++ = v0;
bit >>= 1;
if ( bit == 0 ) {
bit = 0x80;
cp++;
}
}
return rv;
}
static PyObject *
imageop_grey22grey(PyObject *self, PyObject *args)
{
int x, y, len, nlen;
unsigned char *cp, *ncp;
PyObject *rv;
int i, pos, value = 0, nvalue;
if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
return 0;
nlen = x*y;
if ( (nlen+3)/4 != len ) {
PyErr_SetString(ImageopError, "String has incorrect length");
return 0;
}
rv = PyString_FromStringAndSize(NULL, nlen);
if ( rv == 0 )
return 0;
ncp = (unsigned char *)PyString_AsString(rv);
pos = 0;
for ( i=0; i < nlen; i++ ) {
if ( pos == 0 ) {
value = *cp++;
pos = 8;
}
pos -= 2;
nvalue = (value >> pos) & 0x03;
*ncp++ = nvalue | (nvalue << 2) |
(nvalue << 4) | (nvalue << 6);
}
return rv;
}
static PyObject *
imageop_grey42grey(PyObject *self, PyObject *args)
{
int x, y, len, nlen;
unsigned char *cp, *ncp;
PyObject *rv;
int i, pos, value = 0, nvalue;
if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
return 0;
nlen = x*y;
if ( (nlen+1)/2 != len ) {
PyErr_SetString(ImageopError, "String has incorrect length");
return 0;
}
rv = PyString_FromStringAndSize(NULL, nlen);
if ( rv == 0 )
return 0;
ncp = (unsigned char *)PyString_AsString(rv);
pos = 0;
for ( i=0; i < nlen; i++ ) {
if ( pos == 0 ) {
value = *cp++;
pos = 8;
}
pos -= 4;
nvalue = (value >> pos) & 0x0f;
*ncp++ = nvalue | (nvalue << 4);
}
return rv;
}
static PyObject *
imageop_rgb2rgb8(PyObject *self, PyObject *args)
{
int x, y, len, nlen;
unsigned char *cp;
unsigned char *ncp;
PyObject *rv;
int i, r, g, b;
int backward_compatible = imageop_backward_compatible();
if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
return 0;
nlen = x*y;
if ( nlen*4 != len ) {
PyErr_SetString(ImageopError, "String has incorrect length");
return 0;
}
rv = PyString_FromStringAndSize(NULL, nlen);
if ( rv == 0 )
return 0;
ncp = (unsigned char *)PyString_AsString(rv);
for ( i=0; i < nlen; i++ ) {
/* Bits in source: aaaaaaaa BBbbbbbb GGGggggg RRRrrrrr */
if (backward_compatible) {
Py_UInt32 value = * (Py_UInt32 *) cp;
cp += 4;
r = (int) ((value & 0xff) / 255. * 7. + .5);
g = (int) (((value >> 8) & 0xff) / 255. * 7. + .5);
b = (int) (((value >> 16) & 0xff) / 255. * 3. + .5);
} else {
cp++; /* skip alpha channel */
b = (int) (*cp++ / 255. * 3. + .5);
g = (int) (*cp++ / 255. * 7. + .5);
r = (int) (*cp++ / 255. * 7. + .5);
}
*ncp++ = (unsigned char)((r<<5) | (b<<3) | g);
}
return rv;
}
static PyObject *
imageop_rgb82rgb(PyObject *self, PyObject *args)
{
int x, y, len, nlen;
unsigned char *cp;
unsigned char *ncp;
PyObject *rv;
int i, r, g, b;
unsigned char value;
int backward_compatible = imageop_backward_compatible();
if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
return 0;
nlen = x*y;
if ( nlen != len ) {
PyErr_SetString(ImageopError, "String has incorrect length");
return 0;
}
rv = PyString_FromStringAndSize(NULL, nlen*4);
if ( rv == 0 )
return 0;
ncp = (unsigned char *)PyString_AsString(rv);
for ( i=0; i < nlen; i++ ) {
/* Bits in source: RRRBBGGG
** Red and Green are multiplied by 36.5, Blue by 85
*/
value = *cp++;
r = (value >> 5) & 7;
g = (value ) & 7;
b = (value >> 3) & 3;
r = (r<<5) | (r<<3) | (r>>1);
g = (g<<5) | (g<<3) | (g>>1);
b = (b<<6) | (b<<4) | (b<<2) | b;
if (backward_compatible) {
Py_UInt32 nvalue = r | (g<<8) | (b<<16);
* (Py_UInt32 *) ncp = nvalue;
ncp += 4;
} else {
*ncp++ = 0;
*ncp++ = b;
*ncp++ = g;
*ncp++ = r;
}
}
return rv;
}
static PyObject *
imageop_rgb2grey(PyObject *self, PyObject *args)
{
int x, y, len, nlen;
unsigned char *cp;
unsigned char *ncp;
PyObject *rv;
int i, r, g, b;
int nvalue;
int backward_compatible = imageop_backward_compatible();
if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
return 0;
nlen = x*y;
if ( nlen*4 != len ) {
PyErr_SetString(ImageopError, "String has incorrect length");
return 0;
}
rv = PyString_FromStringAndSize(NULL, nlen);
if ( rv == 0 )
return 0;
ncp = (unsigned char *)PyString_AsString(rv);
for ( i=0; i < nlen; i++ ) {
if (backward_compatible) {
Py_UInt32 value = * (Py_UInt32 *) cp;
cp += 4;
r = (int) ((value & 0xff) / 255. * 7. + .5);
g = (int) (((value >> 8) & 0xff) / 255. * 7. + .5);
b = (int) (((value >> 16) & 0xff) / 255. * 3. + .5);
} else {
cp++; /* skip alpha channel */
b = *cp++;
g = *cp++;
r = *cp++;
}
nvalue = (int)(0.30*r + 0.59*g + 0.11*b);
if ( nvalue > 255 ) nvalue = 255;
*ncp++ = (unsigned char)nvalue;
}
return rv;
}
static PyObject *
imageop_grey2rgb(PyObject *self, PyObject *args)
{
int x, y, len, nlen;
unsigned char *cp;
unsigned char *ncp;
PyObject *rv;
int i;
unsigned char value;
int backward_compatible = imageop_backward_compatible();
if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
return 0;
nlen = x*y;
if ( nlen != len ) {
PyErr_SetString(ImageopError, "String has incorrect length");
return 0;
}
rv = PyString_FromStringAndSize(NULL, nlen*4);
if ( rv == 0 )
return 0;
ncp = (unsigned char *)PyString_AsString(rv);
for ( i=0; i < nlen; i++ ) {
value = *cp++;
if (backward_compatible) {
* (Py_UInt32 *) ncp = (Py_UInt32) value | ((Py_UInt32) value << 8 ) | ((Py_UInt32) value << 16);
ncp += 4;
} else {
*ncp++ = 0;
*ncp++ = value;
*ncp++ = value;
*ncp++ = value;
}
}
return rv;
}
/*
static object *
imageop_mul(object *self, object *args)
{
char *cp, *ncp;
int len, size, x, y;
object *rv;
int i;
if ( !getargs(args, "(s#iii)", &cp, &len, &size, &x, &y) )
return 0;
if ( size != 1 && size != 4 ) {
err_setstr(ImageopError, "Size should be 1 or 4");
return 0;
}
if ( len != size*x*y ) {
err_setstr(ImageopError, "String has incorrect length");
return 0;
}
rv = newsizedstringobject(NULL, XXXX);
if ( rv == 0 )
return 0;
ncp = (char *)getstringvalue(rv);
for ( i=0; i < len; i += size ) {
}
return rv;
}
*/
static PyMethodDef imageop_methods[] = {
{ "crop", imageop_crop, METH_VARARGS },
{ "scale", imageop_scale, METH_VARARGS },
{ "grey2mono", imageop_grey2mono, METH_VARARGS },
{ "grey2grey2", imageop_grey2grey2, METH_VARARGS },
{ "grey2grey4", imageop_grey2grey4, METH_VARARGS },
{ "dither2mono", imageop_dither2mono, METH_VARARGS },
{ "dither2grey2", imageop_dither2grey2, METH_VARARGS },
{ "mono2grey", imageop_mono2grey, METH_VARARGS },
{ "grey22grey", imageop_grey22grey, METH_VARARGS },
{ "grey42grey", imageop_grey42grey, METH_VARARGS },
{ "tovideo", imageop_tovideo, METH_VARARGS },
{ "rgb2rgb8", imageop_rgb2rgb8, METH_VARARGS },
{ "rgb82rgb", imageop_rgb82rgb, METH_VARARGS },
{ "rgb2grey", imageop_rgb2grey, METH_VARARGS },
{ "grey2rgb", imageop_grey2rgb, METH_VARARGS },
{ 0, 0 }
};
PyMODINIT_FUNC
initimageop(void)
{
PyObject *m;
m = Py_InitModule("imageop", imageop_methods);
if (m == NULL)
return;
ImageopDict = PyModule_GetDict(m);
ImageopError = PyErr_NewException("imageop.error", NULL, NULL);
if (ImageopError != NULL)
PyDict_SetItemString(ImageopDict, "error", ImageopError);
}

View File

@ -1403,7 +1403,7 @@ validate_small_stmt(node *tree)
/* compound_stmt:
* if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
* if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef | decorated
*/
static int
validate_compound_stmt(node *tree)
@ -1422,7 +1422,8 @@ validate_compound_stmt(node *tree)
|| (ntype == for_stmt)
|| (ntype == try_stmt)
|| (ntype == funcdef)
|| (ntype == classdef))
|| (ntype == classdef)
|| (ntype == decorated))
res = validate_node(tree);
else {
res = 0;
@ -1432,7 +1433,6 @@ validate_compound_stmt(node *tree)
return (res);
}
static int
validate_yield_or_testlist(node *tree)
{
@ -2366,28 +2366,40 @@ validate_decorators(node *tree)
/* funcdef:
*
* -6 -5 -4 -3 -2 -1
* [decorators] 'def' NAME parameters ':' suite
* -5 -4 -3 -2 -1
* 'def' NAME parameters ':' suite
*/
static int
validate_funcdef(node *tree)
{
int nch = NCH(tree);
int ok = (validate_ntype(tree, funcdef)
&& ((nch == 5) || (nch == 6))
&& (nch == 5)
&& validate_name(RCHILD(tree, -5), "def")
&& validate_ntype(RCHILD(tree, -4), NAME)
&& validate_colon(RCHILD(tree, -2))
&& validate_parameters(RCHILD(tree, -3))
&& validate_suite(RCHILD(tree, -1)));
if (ok && (nch == 6))
ok = validate_decorators(CHILD(tree, 0));
return ok;
}
/* decorated
* decorators (classdef | funcdef)
*/
static int
validate_decorated(node *tree)
{
int nch = NCH(tree);
int ok = (validate_ntype(tree, decorated)
&& (nch == 2)
&& validate_decorators(RCHILD(tree, -2))
&& (validate_funcdef(RCHILD(tree, -1))
|| validate_class(RCHILD(tree, -1)))
);
return ok;
}
static int
validate_lambdef(node *tree)
{
@ -2731,6 +2743,9 @@ validate_node(node *tree)
case classdef:
res = validate_class(tree);
break;
case decorated:
res = validate_decorated(tree);
break;
/*
* "Trivial" parse tree nodes.
* (Why did I call these trivial?)

View File

@ -1,780 +0,0 @@
/*
* fastimg -
* Faster reading and writing of image files.
*
* This code should work on machines with any byte order.
*
* Could someone make this run real fast using multiple processors
* or how about using memory mapped files to speed it up?
*
* Paul Haeberli - 1991
*
* Changed to return sizes.
* Sjoerd Mullender - 1993
* Changed to incorporate into Python.
* Sjoerd Mullender - 1993
*/
#include "Python.h"
#if SIZEOF_INT == 4
typedef int Py_Int32;
typedef unsigned int Py_UInt32;
#else
#if SIZEOF_LONG == 4
typedef long Py_Int32;
typedef unsigned long Py_UInt32;
#else
#error "No 4-byte integral type"
#endif
#endif
#include <string.h>
/*
* from image.h
*
*/
typedef struct {
unsigned short imagic; /* stuff saved on disk . . */
unsigned short type;
unsigned short dim;
unsigned short xsize;
unsigned short ysize;
unsigned short zsize;
Py_UInt32 min;
Py_UInt32 max;
Py_UInt32 wastebytes;
char name[80];
Py_UInt32 colormap;
Py_Int32 file; /* stuff used in core only */
unsigned short flags;
short dorev;
short x;
short y;
short z;
short cnt;
unsigned short *ptr;
unsigned short *base;
unsigned short *tmpbuf;
Py_UInt32 offset;
Py_UInt32 rleend; /* for rle images */
Py_UInt32 *rowstart; /* for rle images */
Py_Int32 *rowsize; /* for rle images */
} IMAGE;
#define IMAGIC 0732
#define TYPEMASK 0xff00
#define BPPMASK 0x00ff
#define ITYPE_VERBATIM 0x0000
#define ITYPE_RLE 0x0100
#define ISRLE(type) (((type) & 0xff00) == ITYPE_RLE)
#define ISVERBATIM(type) (((type) & 0xff00) == ITYPE_VERBATIM)
#define BPP(type) ((type) & BPPMASK)
#define RLE(bpp) (ITYPE_RLE | (bpp))
#define VERBATIM(bpp) (ITYPE_VERBATIM | (bpp))
/*
* end of image.h stuff
*
*/
#define RINTLUM (79)
#define GINTLUM (156)
#define BINTLUM (21)
#define ILUM(r,g,b) ((int)(RINTLUM*(r)+GINTLUM*(g)+BINTLUM*(b))>>8)
#define OFFSET_R 3 /* this is byte order dependent */
#define OFFSET_G 2
#define OFFSET_B 1
#define OFFSET_A 0
#define CHANOFFSET(z) (3-(z)) /* this is byte order dependent */
static void expandrow(unsigned char *, unsigned char *, int);
static void setalpha(unsigned char *, int);
static void copybw(Py_Int32 *, int);
static void interleaverow(unsigned char*, unsigned char*, int, int);
static int compressrow(unsigned char *, unsigned char *, int, int);
static void lumrow(unsigned char *, unsigned char *, int);
#ifdef ADD_TAGS
#define TAGLEN (5)
#else
#define TAGLEN (0)
#endif
static PyObject *ImgfileError;
static int reverse_order;
#ifdef ADD_TAGS
/*
* addlongimgtag -
* this is used to extract image data from core dumps.
*
*/
static void
addlongimgtag(Py_UInt32 *dptr, int xsize, int ysize)
{
dptr = dptr + (xsize * ysize);
dptr[0] = 0x12345678;
dptr[1] = 0x59493333;
dptr[2] = 0x69434222;
dptr[3] = xsize;
dptr[4] = ysize;
}
#endif
/*
* byte order independent read/write of shorts and longs.
*
*/
static unsigned short
getshort(FILE *inf)
{
unsigned char buf[2];
fread(buf, 2, 1, inf);
return (buf[0] << 8) + (buf[1] << 0);
}
static Py_UInt32
getlong(FILE *inf)
{
unsigned char buf[4];
fread(buf, 4, 1, inf);
return (buf[0] << 24) + (buf[1] << 16) + (buf[2] << 8) + (buf[3] << 0);
}
static void
putshort(FILE *outf, unsigned short val)
{
unsigned char buf[2];
buf[0] = (val >> 8);
buf[1] = (val >> 0);
fwrite(buf, 2, 1, outf);
}
static int
putlong(FILE *outf, Py_UInt32 val)
{
unsigned char buf[4];
buf[0] = (unsigned char) (val >> 24);
buf[1] = (unsigned char) (val >> 16);
buf[2] = (unsigned char) (val >> 8);
buf[3] = (unsigned char) (val >> 0);
return (int)fwrite(buf, 4, 1, outf);
}
static void
readheader(FILE *inf, IMAGE *image)
{
memset(image ,0, sizeof(IMAGE));
image->imagic = getshort(inf);
image->type = getshort(inf);
image->dim = getshort(inf);
image->xsize = getshort(inf);
image->ysize = getshort(inf);
image->zsize = getshort(inf);
}
static int
writeheader(FILE *outf, IMAGE *image)
{
IMAGE t;
memset(&t, 0, sizeof(IMAGE));
fwrite(&t, sizeof(IMAGE), 1, outf);
fseek(outf, 0, SEEK_SET);
putshort(outf, image->imagic);
putshort(outf, image->type);
putshort(outf, image->dim);
putshort(outf, image->xsize);
putshort(outf, image->ysize);
putshort(outf, image->zsize);
putlong(outf, image->min);
putlong(outf, image->max);
putlong(outf, 0);
return (int)fwrite("no name", 8, 1, outf);
}
static int
writetab(FILE *outf, /*unsigned*/ Py_Int32 *tab, int len)
{
int r = 0;
while(len) {
r = putlong(outf, *tab++);
len--;
}
return r;
}
static void
readtab(FILE *inf, /*unsigned*/ Py_Int32 *tab, int len)
{
while(len) {
*tab++ = getlong(inf);
len--;
}
}
/*
* sizeofimage -
* return the xsize and ysize of an iris image file.
*
*/
static PyObject *
sizeofimage(PyObject *self, PyObject *args)
{
char *name;
IMAGE image;
FILE *inf;
if (!PyArg_ParseTuple(args, "s:sizeofimage", &name))
return NULL;
inf = fopen(name, "rb");
if (!inf) {
PyErr_SetString(ImgfileError, "can't open image file");
return NULL;
}
readheader(inf, &image);
fclose(inf);
if (image.imagic != IMAGIC) {
PyErr_SetString(ImgfileError,
"bad magic number in image file");
return NULL;
}
return Py_BuildValue("(ii)", image.xsize, image.ysize);
}
/*
* longimagedata -
* read in a B/W RGB or RGBA iris image file and return a
* pointer to an array of longs.
*
*/
static PyObject *
longimagedata(PyObject *self, PyObject *args)
{
char *name;
unsigned char *base, *lptr;
unsigned char *rledat = NULL, *verdat = NULL;
Py_Int32 *starttab = NULL, *lengthtab = NULL;
FILE *inf = NULL;
IMAGE image;
int y, z, tablen;
int xsize, ysize, zsize;
int bpp, rle, cur, badorder;
int rlebuflen;
PyObject *rv = NULL;
if (!PyArg_ParseTuple(args, "s:longimagedata", &name))
return NULL;
inf = fopen(name,"rb");
if (!inf) {
PyErr_SetString(ImgfileError, "can't open image file");
return NULL;
}
readheader(inf,&image);
if (image.imagic != IMAGIC) {
PyErr_SetString(ImgfileError,
"bad magic number in image file");
goto finally;
}
rle = ISRLE(image.type);
bpp = BPP(image.type);
if (bpp != 1) {
PyErr_SetString(ImgfileError,
"image must have 1 byte per pix chan");
goto finally;
}
xsize = image.xsize;
ysize = image.ysize;
zsize = image.zsize;
if (rle) {
tablen = ysize * zsize * sizeof(Py_Int32);
starttab = (Py_Int32 *)malloc(tablen);
lengthtab = (Py_Int32 *)malloc(tablen);
rlebuflen = (int) (1.05 * xsize +10);
rledat = (unsigned char *)malloc(rlebuflen);
if (!starttab || !lengthtab || !rledat) {
PyErr_NoMemory();
goto finally;
}
fseek(inf, 512, SEEK_SET);
readtab(inf, starttab, ysize*zsize);
readtab(inf, lengthtab, ysize*zsize);
/* check data order */
cur = 0;
badorder = 0;
for(y = 0; y < ysize; y++) {
for(z = 0; z < zsize; z++) {
if (starttab[y + z * ysize] < cur) {
badorder = 1;
break;
}
cur = starttab[y +z * ysize];
}
if (badorder)
break;
}
fseek(inf, 512 + 2 * tablen, SEEK_SET);
cur = 512 + 2 * tablen;
rv = PyString_FromStringAndSize((char *)NULL,
(xsize * ysize + TAGLEN) * sizeof(Py_Int32));
if (rv == NULL)
goto finally;
base = (unsigned char *) PyString_AsString(rv);
#ifdef ADD_TAGS
addlongimgtag(base,xsize,ysize);
#endif
if (badorder) {
for (z = 0; z < zsize; z++) {
lptr = base;
if (reverse_order)
lptr += (ysize - 1) * xsize
* sizeof(Py_UInt32);
for (y = 0; y < ysize; y++) {
int idx = y + z * ysize;
if (cur != starttab[idx]) {
fseek(inf,starttab[idx],
SEEK_SET);
cur = starttab[idx];
}
if (lengthtab[idx] > rlebuflen) {
PyErr_SetString(ImgfileError,
"rlebuf is too small");
Py_DECREF(rv);
rv = NULL;
goto finally;
}
fread(rledat, lengthtab[idx], 1, inf);
cur += lengthtab[idx];
expandrow(lptr, rledat, 3-z);
if (reverse_order)
lptr -= xsize
* sizeof(Py_UInt32);
else
lptr += xsize
* sizeof(Py_UInt32);
}
}
} else {
lptr = base;
if (reverse_order)
lptr += (ysize - 1) * xsize
* sizeof(Py_UInt32);
for (y = 0; y < ysize; y++) {
for(z = 0; z < zsize; z++) {
int idx = y + z * ysize;
if (cur != starttab[idx]) {
fseek(inf, starttab[idx],
SEEK_SET);
cur = starttab[idx];
}
fread(rledat, lengthtab[idx], 1, inf);
cur += lengthtab[idx];
expandrow(lptr, rledat, 3-z);
}
if (reverse_order)
lptr -= xsize * sizeof(Py_UInt32);
else
lptr += xsize * sizeof(Py_UInt32);
}
}
if (zsize == 3)
setalpha(base, xsize * ysize);
else if (zsize < 3)
copybw((Py_Int32 *) base, xsize * ysize);
}
else {
rv = PyString_FromStringAndSize((char *) 0,
(xsize*ysize+TAGLEN)*sizeof(Py_Int32));
if (rv == NULL)
goto finally;
base = (unsigned char *) PyString_AsString(rv);
#ifdef ADD_TAGS
addlongimgtag(base, xsize, ysize);
#endif
verdat = (unsigned char *)malloc(xsize);
if (!verdat) {
Py_CLEAR(rv);
goto finally;
}
fseek(inf, 512, SEEK_SET);
for (z = 0; z < zsize; z++) {
lptr = base;
if (reverse_order)
lptr += (ysize - 1) * xsize
* sizeof(Py_UInt32);
for (y = 0; y < ysize; y++) {
fread(verdat, xsize, 1, inf);
interleaverow(lptr, verdat, 3-z, xsize);
if (reverse_order)
lptr -= xsize * sizeof(Py_UInt32);
else
lptr += xsize * sizeof(Py_UInt32);
}
}
if (zsize == 3)
setalpha(base, xsize * ysize);
else if (zsize < 3)
copybw((Py_Int32 *) base, xsize * ysize);
}
finally:
if (starttab)
free(starttab);
if (lengthtab)
free(lengthtab);
if (rledat)
free(rledat);
if (verdat)
free(verdat);
fclose(inf);
return rv;
}
/* static utility functions for longimagedata */
static void
interleaverow(unsigned char *lptr, unsigned char *cptr, int z, int n)
{
lptr += z;
while (n--) {
*lptr = *cptr++;
lptr += 4;
}
}
static void
copybw(Py_Int32 *lptr, int n)
{
while (n >= 8) {
lptr[0] = 0xff000000 + (0x010101 * (lptr[0] & 0xff));
lptr[1] = 0xff000000 + (0x010101 * (lptr[1] & 0xff));
lptr[2] = 0xff000000 + (0x010101 * (lptr[2] & 0xff));
lptr[3] = 0xff000000 + (0x010101 * (lptr[3] & 0xff));
lptr[4] = 0xff000000 + (0x010101 * (lptr[4] & 0xff));
lptr[5] = 0xff000000 + (0x010101 * (lptr[5] & 0xff));
lptr[6] = 0xff000000 + (0x010101 * (lptr[6] & 0xff));
lptr[7] = 0xff000000 + (0x010101 * (lptr[7] & 0xff));
lptr += 8;
n -= 8;
}
while (n--) {
*lptr = 0xff000000 + (0x010101 * (*lptr&0xff));
lptr++;
}
}
static void
setalpha(unsigned char *lptr, int n)
{
while (n >= 8) {
lptr[0 * 4] = 0xff;
lptr[1 * 4] = 0xff;
lptr[2 * 4] = 0xff;
lptr[3 * 4] = 0xff;
lptr[4 * 4] = 0xff;
lptr[5 * 4] = 0xff;
lptr[6 * 4] = 0xff;
lptr[7 * 4] = 0xff;
lptr += 4 * 8;
n -= 8;
}
while (n--) {
*lptr = 0xff;
lptr += 4;
}
}
static void
expandrow(unsigned char *optr, unsigned char *iptr, int z)
{
unsigned char pixel, count;
optr += z;
while (1) {
pixel = *iptr++;
if (!(count = (pixel & 0x7f)))
return;
if (pixel & 0x80) {
while (count >= 8) {
optr[0 * 4] = iptr[0];
optr[1 * 4] = iptr[1];
optr[2 * 4] = iptr[2];
optr[3 * 4] = iptr[3];
optr[4 * 4] = iptr[4];
optr[5 * 4] = iptr[5];
optr[6 * 4] = iptr[6];
optr[7 * 4] = iptr[7];
optr += 8 * 4;
iptr += 8;
count -= 8;
}
while (count--) {
*optr = *iptr++;
optr += 4;
}
}
else {
pixel = *iptr++;
while (count >= 8) {
optr[0 * 4] = pixel;
optr[1 * 4] = pixel;
optr[2 * 4] = pixel;
optr[3 * 4] = pixel;
optr[4 * 4] = pixel;
optr[5 * 4] = pixel;
optr[6 * 4] = pixel;
optr[7 * 4] = pixel;
optr += 8 * 4;
count -= 8;
}
while (count--) {
*optr = pixel;
optr += 4;
}
}
}
}
/*
* longstoimage -
* copy an array of longs to an iris image file. Each long
* represents one pixel. xsize and ysize specify the dimensions of
* the pixel array. zsize specifies what kind of image file to
* write out. if zsize is 1, the luminance of the pixels are
* calculated, and a single channel black and white image is saved.
* If zsize is 3, an RGB image file is saved. If zsize is 4, an
* RGBA image file is saved.
*
*/
static PyObject *
longstoimage(PyObject *self, PyObject *args)
{
unsigned char *lptr;
char *name;
int xsize, ysize, zsize;
FILE *outf = NULL;
IMAGE image;
int tablen, y, z, pos, len;
Py_Int32 *starttab = NULL, *lengthtab = NULL;
unsigned char *rlebuf = NULL;
unsigned char *lumbuf = NULL;
int rlebuflen;
Py_ssize_t goodwrite;
PyObject *retval = NULL;
if (!PyArg_ParseTuple(args, "s#iiis:longstoimage", &lptr, &len,
&xsize, &ysize, &zsize, &name))
return NULL;
goodwrite = 1;
outf = fopen(name, "wb");
if (!outf) {
PyErr_SetString(ImgfileError, "can't open output file");
return NULL;
}
tablen = ysize * zsize * sizeof(Py_Int32);
starttab = (Py_Int32 *)malloc(tablen);
lengthtab = (Py_Int32 *)malloc(tablen);
rlebuflen = (int) (1.05 * xsize + 10);
rlebuf = (unsigned char *)malloc(rlebuflen);
lumbuf = (unsigned char *)malloc(xsize * sizeof(Py_Int32));
if (!starttab || !lengthtab || !rlebuf || !lumbuf) {
PyErr_NoMemory();
goto finally;
}
memset(&image, 0, sizeof(IMAGE));
image.imagic = IMAGIC;
image.type = RLE(1);
if (zsize>1)
image.dim = 3;
else
image.dim = 2;
image.xsize = xsize;
image.ysize = ysize;
image.zsize = zsize;
image.min = 0;
image.max = 255;
goodwrite *= writeheader(outf, &image);
pos = 512 + 2 * tablen;
fseek(outf, pos, SEEK_SET);
if (reverse_order)
lptr += (ysize - 1) * xsize * sizeof(Py_UInt32);
for (y = 0; y < ysize; y++) {
for (z = 0; z < zsize; z++) {
if (zsize == 1) {
lumrow(lptr, lumbuf, xsize);
len = compressrow(lumbuf, rlebuf,
CHANOFFSET(z), xsize);
} else {
len = compressrow(lptr, rlebuf,
CHANOFFSET(z), xsize);
}
if(len > rlebuflen) {
PyErr_SetString(ImgfileError,
"rlebuf is too small");
goto finally;
}
goodwrite *= fwrite(rlebuf, len, 1, outf);
starttab[y + z * ysize] = pos;
lengthtab[y + z * ysize] = len;
pos += len;
}
if (reverse_order)
lptr -= xsize * sizeof(Py_UInt32);
else
lptr += xsize * sizeof(Py_UInt32);
}
fseek(outf, 512, SEEK_SET);
goodwrite *= writetab(outf, starttab, ysize*zsize);
goodwrite *= writetab(outf, lengthtab, ysize*zsize);
if (goodwrite) {
Py_INCREF(Py_None);
retval = Py_None;
} else
PyErr_SetString(ImgfileError, "not enough space for image");
finally:
fclose(outf);
free(starttab);
free(lengthtab);
free(rlebuf);
free(lumbuf);
return retval;
}
/* static utility functions for longstoimage */
static void
lumrow(unsigned char *rgbptr, unsigned char *lumptr, int n)
{
lumptr += CHANOFFSET(0);
while (n--) {
*lumptr = ILUM(rgbptr[OFFSET_R],
rgbptr[OFFSET_G],
rgbptr[OFFSET_B]);
lumptr += 4;
rgbptr += 4;
}
}
static int
compressrow(unsigned char *lbuf, unsigned char *rlebuf, int z, int cnt)
{
unsigned char *iptr, *ibufend, *sptr, *optr;
short todo, cc;
Py_Int32 count;
lbuf += z;
iptr = lbuf;
ibufend = iptr + cnt * 4;
optr = rlebuf;
while(iptr < ibufend) {
sptr = iptr;
iptr += 8;
while ((iptr<ibufend) &&
((iptr[-8]!=iptr[-4]) ||(iptr[-4]!=iptr[0])))
{
iptr += 4;
}
iptr -= 8;
count = (iptr - sptr) / 4;
while (count) {
todo = count > 126 ? 126 : (short)count;
count -= todo;
*optr++ = 0x80 | todo;
while (todo > 8) {
optr[0] = sptr[0 * 4];
optr[1] = sptr[1 * 4];
optr[2] = sptr[2 * 4];
optr[3] = sptr[3 * 4];
optr[4] = sptr[4 * 4];
optr[5] = sptr[5 * 4];
optr[6] = sptr[6 * 4];
optr[7] = sptr[7 * 4];
optr += 8;
sptr += 8 * 4;
todo -= 8;
}
while (todo--) {
*optr++ = *sptr;
sptr += 4;
}
}
sptr = iptr;
cc = *iptr;
iptr += 4;
while ((iptr < ibufend) && (*iptr == cc))
iptr += 4;
count = (iptr - sptr) / 4;
while (count) {
todo = count > 126 ? 126 : (short)count;
count -= todo;
*optr++ = (unsigned char) todo;
*optr++ = (unsigned char) cc;
}
}
*optr++ = 0;
return optr - (unsigned char *)rlebuf;
}
static PyObject *
ttob(PyObject *self, PyObject *args)
{
int order, oldorder;
if (!PyArg_ParseTuple(args, "i:ttob", &order))
return NULL;
oldorder = reverse_order;
reverse_order = order;
return PyInt_FromLong(oldorder);
}
static PyMethodDef
rgbimg_methods[] = {
{"sizeofimage", sizeofimage, METH_VARARGS},
{"longimagedata", longimagedata, METH_VARARGS},
{"longstoimage", longstoimage, METH_VARARGS},
{"ttob", ttob, METH_VARARGS},
{NULL, NULL} /* sentinel */
};
PyMODINIT_FUNC
initrgbimg(void)
{
PyObject *m, *d;
m = Py_InitModule("rgbimg", rgbimg_methods);
if (m == NULL)
return;
if (PyErr_Warn(PyExc_DeprecationWarning,
"the rgbimg module is deprecated"))
return;
d = PyModule_GetDict(m);
ImgfileError = PyErr_NewException("rgbimg.error", NULL, NULL);
if (ImgfileError != NULL)
PyDict_SetItemString(d, "error", ImgfileError);
}

View File

@ -4174,7 +4174,7 @@ tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
}
static struct PyMethodDef tp_new_methoddef[] = {
{"__new__", (PyCFunction)tp_new_wrapper, METH_KEYWORDS,
{"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
PyDoc_STR("T.__new__(S, ...) -> "
"a new object with type S, a subtype of T")},
{0}

View File

@ -13,16 +13,10 @@ extern void initbinascii(void);
extern void initcmath(void);
extern void initerrno(void);
extern void initgc(void);
#ifndef MS_WINI64
extern void initimageop(void);
#endif
extern void initmath(void);
extern void init_md5(void);
extern void initnt(void);
extern void initoperator(void);
#ifndef MS_WINI64
extern void initrgbimg(void);
#endif
extern void initsignal(void);
extern void init_sha(void);
extern void init_sha256(void);
@ -89,16 +83,10 @@ struct _inittab _PyImport_Inittab[] = {
{"cmath", initcmath},
{"errno", initerrno},
{"gc", initgc},
#ifndef MS_WINI64
{"imageop", initimageop},
#endif
{"math", initmath},
{"_md5", init_md5},
{"nt", initnt}, /* Use the NT os functions, not posix */
{"operator", initoperator},
#ifndef MS_WINI64
{"rgbimg", initrgbimg},
#endif
{"signal", initsignal},
{"_sha", init_sha},
{"_sha256", init_sha256},

View File

@ -565,9 +565,6 @@
<File
RelativePath="..\Parser\grammar1.c">
</File>
<File
RelativePath="..\Modules\imageop.c">
</File>
<File
RelativePath="..\Python\import.c">
</File>
@ -715,9 +712,6 @@
<File
RelativePath="..\Objects\rangeobject.c">
</File>
<File
RelativePath="..\Modules\rgbimgmodule.c">
</File>
<File
RelativePath="..\Modules\rotatingtree.c">
</File>

View File

@ -10,13 +10,14 @@ module Python version "$Revision$"
| Suite(stmt* body)
stmt = FunctionDef(identifier name, arguments args,
stmt* body, expr* decorators, expr? returns)
stmt* body, expr* decorator_list, expr? returns)
| ClassDef(identifier name,
expr* bases,
keyword* keywords,
expr? starargs,
expr? kwargs,
stmt* body)
stmt* body,
expr *decorator_list)
| Return(expr? value)
| Delete(expr* targets)

View File

@ -2,7 +2,7 @@
/*
__version__ 55343.
__version__ 55430.
This module must be committed separately after each AST grammar change;
The __version__ number is set to the revision number of the commit
@ -42,7 +42,7 @@ static char *FunctionDef_fields[]={
"name",
"args",
"body",
"decorators",
"decorator_list",
"returns",
};
static PyTypeObject *ClassDef_type;
@ -53,6 +53,7 @@ static char *ClassDef_fields[]={
"starargs",
"kwargs",
"body",
"decorator_list",
};
static PyTypeObject *Return_type;
static char *Return_fields[]={
@ -485,7 +486,7 @@ static int init_types(void)
FunctionDef_type = make_type("FunctionDef", stmt_type,
FunctionDef_fields, 5);
if (!FunctionDef_type) return 0;
ClassDef_type = make_type("ClassDef", stmt_type, ClassDef_fields, 6);
ClassDef_type = make_type("ClassDef", stmt_type, ClassDef_fields, 7);
if (!ClassDef_type) return 0;
Return_type = make_type("Return", stmt_type, Return_fields, 1);
if (!Return_type) return 0;
@ -812,8 +813,8 @@ Suite(asdl_seq * body, PyArena *arena)
stmt_ty
FunctionDef(identifier name, arguments_ty args, asdl_seq * body, asdl_seq *
decorators, expr_ty returns, int lineno, int col_offset, PyArena
*arena)
decorator_list, expr_ty returns, int lineno, int col_offset,
PyArena *arena)
{
stmt_ty p;
if (!name) {
@ -833,7 +834,7 @@ FunctionDef(identifier name, arguments_ty args, asdl_seq * body, asdl_seq *
p->v.FunctionDef.name = name;
p->v.FunctionDef.args = args;
p->v.FunctionDef.body = body;
p->v.FunctionDef.decorators = decorators;
p->v.FunctionDef.decorator_list = decorator_list;
p->v.FunctionDef.returns = returns;
p->lineno = lineno;
p->col_offset = col_offset;
@ -842,8 +843,8 @@ FunctionDef(identifier name, arguments_ty args, asdl_seq * body, asdl_seq *
stmt_ty
ClassDef(identifier name, asdl_seq * bases, asdl_seq * keywords, expr_ty
starargs, expr_ty kwargs, asdl_seq * body, int lineno, int col_offset,
PyArena *arena)
starargs, expr_ty kwargs, asdl_seq * body, asdl_seq * decorator_list,
int lineno, int col_offset, PyArena *arena)
{
stmt_ty p;
if (!name) {
@ -861,6 +862,7 @@ ClassDef(identifier name, asdl_seq * bases, asdl_seq * keywords, expr_ty
p->v.ClassDef.starargs = starargs;
p->v.ClassDef.kwargs = kwargs;
p->v.ClassDef.body = body;
p->v.ClassDef.decorator_list = decorator_list;
p->lineno = lineno;
p->col_offset = col_offset;
return p;
@ -1994,9 +1996,11 @@ ast2obj_stmt(void* _o)
if (PyObject_SetAttrString(result, "body", value) == -1)
goto failed;
Py_DECREF(value);
value = ast2obj_list(o->v.FunctionDef.decorators, ast2obj_expr);
value = ast2obj_list(o->v.FunctionDef.decorator_list,
ast2obj_expr);
if (!value) goto failed;
if (PyObject_SetAttrString(result, "decorators", value) == -1)
if (PyObject_SetAttrString(result, "decorator_list", value) ==
-1)
goto failed;
Py_DECREF(value);
value = ast2obj_expr(o->v.FunctionDef.returns);
@ -2038,6 +2042,13 @@ ast2obj_stmt(void* _o)
if (PyObject_SetAttrString(result, "body", value) == -1)
goto failed;
Py_DECREF(value);
value = ast2obj_list(o->v.ClassDef.decorator_list,
ast2obj_expr);
if (!value) goto failed;
if (PyObject_SetAttrString(result, "decorator_list", value) ==
-1)
goto failed;
Py_DECREF(value);
break;
case Return_kind:
result = PyType_GenericNew(Return_type, NULL, NULL);
@ -3113,7 +3124,7 @@ init_ast(void)
if (PyDict_SetItemString(d, "AST", (PyObject*)AST_type) < 0) return;
if (PyModule_AddIntConstant(m, "PyCF_ONLY_AST", PyCF_ONLY_AST) < 0)
return;
if (PyModule_AddStringConstant(m, "__version__", "55343") < 0)
if (PyModule_AddStringConstant(m, "__version__", "55430") < 0)
return;
if (PyDict_SetItemString(d, "mod", (PyObject*)mod_type) < 0) return;
if (PyDict_SetItemString(d, "Module", (PyObject*)Module_type) < 0)
@ -3269,5 +3280,3 @@ PyObject* PyAST_mod2obj(mod_ty t)
init_types();
return ast2obj_mod(t);
}

View File

@ -28,6 +28,7 @@ static asdl_seq *ast_for_suite(struct compiling *, const node *);
static asdl_seq *ast_for_exprlist(struct compiling *, const node *,
expr_context_ty);
static expr_ty ast_for_testlist(struct compiling *, const node *);
static stmt_ty ast_for_classdef(struct compiling *, const node *, asdl_seq *);
/* Note different signature for ast_for_call */
static expr_ty ast_for_call(struct compiling *, const node *, expr_ty);
@ -931,28 +932,17 @@ ast_for_decorators(struct compiling *c, const node *n)
}
static stmt_ty
ast_for_funcdef(struct compiling *c, const node *n)
ast_for_funcdef(struct compiling *c, const node *n, asdl_seq *decorator_seq)
{
/* funcdef: 'def' [decorators] NAME parameters ['->' test] ':' suite */
/* funcdef: 'def' NAME parameters ['->' test] ':' suite */
identifier name;
arguments_ty args;
asdl_seq *body;
asdl_seq *decorator_seq = NULL;
expr_ty returns = NULL;
int name_i;
int name_i = 1;
REQ(n, funcdef);
if (NCH(n) == 6 || NCH(n) == 8) { /* decorators are present */
decorator_seq = ast_for_decorators(c, CHILD(n, 0));
if (!decorator_seq)
return NULL;
name_i = 2;
}
else {
name_i = 1;
}
name = NEW_IDENTIFIER(CHILD(n, name_i));
if (!name)
return NULL;
@ -977,6 +967,30 @@ ast_for_funcdef(struct compiling *c, const node *n)
n->n_col_offset, c->c_arena);
}
static stmt_ty
ast_for_decorated(struct compiling *c, const node *n)
{
/* decorated: decorators (classdef | funcdef) */
stmt_ty thing = NULL;
asdl_seq *decorator_seq = NULL;
REQ(n, decorated);
decorator_seq = ast_for_decorators(c, CHILD(n, 0));
if (!decorator_seq)
return NULL;
assert(TYPE(CHILD(n, 1)) == funcdef ||
TYPE(CHILD(n, 1)) == classdef);
if (TYPE(CHILD(n, 1)) == funcdef) {
thing = ast_for_funcdef(c, CHILD(n, 1), decorator_seq);
} else if (TYPE(CHILD(n, 1)) == classdef) {
thing = ast_for_classdef(c, CHILD(n, 1), decorator_seq);
}
return thing;
}
static expr_ty
ast_for_lambdef(struct compiling *c, const node *n)
{
@ -2693,7 +2707,7 @@ ast_for_for_stmt(struct compiling *c, const node *n)
static excepthandler_ty
ast_for_except_clause(struct compiling *c, const node *exc, node *body)
{
/* except_clause: 'except' [test [',' test]] */
/* except_clause: 'except' [test ['as' test]] */
REQ(exc, except_clause);
REQ(body, suite);
@ -2858,7 +2872,7 @@ ast_for_with_stmt(struct compiling *c, const node *n)
}
static stmt_ty
ast_for_classdef(struct compiling *c, const node *n)
ast_for_classdef(struct compiling *c, const node *n, asdl_seq *decorator_seq)
{
/* classdef: 'class' NAME ['(' arglist ')'] ':' suite */
asdl_seq *s;
@ -2876,7 +2890,7 @@ ast_for_classdef(struct compiling *c, const node *n)
if (!s)
return NULL;
return ClassDef(NEW_IDENTIFIER(CHILD(n, 1)), NULL, NULL, NULL, NULL, s,
LINENO(n), n->n_col_offset, c->c_arena);
decorator_seq, LINENO(n), n->n_col_offset, c->c_arena);
}
if (TYPE(CHILD(n, 3)) == RPAR) { /* class NAME '(' ')' ':' suite */
@ -2884,7 +2898,7 @@ ast_for_classdef(struct compiling *c, const node *n)
if (!s)
return NULL;
return ClassDef(NEW_IDENTIFIER(CHILD(n, 1)), NULL, NULL, NULL, NULL, s,
LINENO(n), n->n_col_offset, c->c_arena);
decorator_seq, LINENO(n), n->n_col_offset, c->c_arena);
}
/* class NAME '(' arglist ')' ':' suite */
@ -2900,7 +2914,7 @@ ast_for_classdef(struct compiling *c, const node *n)
return ClassDef(NEW_IDENTIFIER(CHILD(n, 1)),
call->v.Call.args, call->v.Call.keywords,
call->v.Call.starargs, call->v.Call.kwargs, s,
LINENO(n), n->n_col_offset, c->c_arena);
decorator_seq, LINENO(n), n->n_col_offset, c->c_arena);
}
static stmt_ty
@ -2946,7 +2960,7 @@ ast_for_stmt(struct compiling *c, const node *n)
}
else {
/* compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt
| funcdef | classdef
| funcdef | classdef | decorated
*/
node *ch = CHILD(n, 0);
REQ(n, compound_stmt);
@ -2962,9 +2976,11 @@ ast_for_stmt(struct compiling *c, const node *n)
case with_stmt:
return ast_for_with_stmt(c, ch);
case funcdef:
return ast_for_funcdef(c, ch);
return ast_for_funcdef(c, ch, NULL);
case classdef:
return ast_for_classdef(c, ch);
return ast_for_classdef(c, ch, NULL);
case decorated:
return ast_for_decorated(c, ch);
default:
PyErr_Format(PyExc_SystemError,
"unhandled small_stmt: TYPE=%d NCH=%d\n",

View File

@ -244,19 +244,6 @@ PyDoc_STRVAR(any_doc,
Return True if bool(x) is True for any x in the iterable.");
static PyObject *
builtin_callable(PyObject *self, PyObject *v)
{
return PyBool_FromLong((long)PyCallable_Check(v));
}
PyDoc_STRVAR(callable_doc,
"callable(object) -> bool\n\
\n\
Return whether the object is callable (i.e., some kind of function).\n\
Note that classes are callable, as are instances with a __call__() method.");
static PyObject *
builtin_filter(PyObject *self, PyObject *args)
{
@ -1948,7 +1935,6 @@ static PyMethodDef builtin_methods[] = {
{"abs", builtin_abs, METH_O, abs_doc},
{"all", builtin_all, METH_O, all_doc},
{"any", builtin_any, METH_O, any_doc},
{"callable", builtin_callable, METH_O, callable_doc},
{"chr", builtin_unichr, METH_VARARGS, unichr_doc},
{"chr8", builtin_chr, METH_VARARGS, chr_doc},
{"cmp", builtin_cmp, METH_VARARGS, cmp_doc},

View File

@ -3779,13 +3779,31 @@ ext_do_call(PyObject *func, PyObject ***pp_stack, int flags, int na, int nk)
if (flags & CALL_FLAG_KW) {
kwdict = EXT_POP(*pp_stack);
if (!(kwdict && PyDict_Check(kwdict))) {
PyErr_Format(PyExc_TypeError,
"%s%s argument after ** "
"must be a dictionary",
PyEval_GetFuncName(func),
PyEval_GetFuncDesc(func));
goto ext_call_fail;
if (!PyDict_Check(kwdict)) {
PyObject *d;
d = PyDict_New();
if (d == NULL)
goto ext_call_fail;
if (PyDict_Update(d, kwdict) != 0) {
Py_DECREF(d);
/* PyDict_Update raises attribute
* error (percolated from an attempt
* to get 'keys' attribute) instead of
* a type error if its second argument
* is not a mapping.
*/
if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
PyErr_Format(PyExc_TypeError,
"%.200s%.200s argument after ** "
"must be a mapping, not %.200s",
PyEval_GetFuncName(func),
PyEval_GetFuncDesc(func),
kwdict->ob_type->tp_name);
}
goto ext_call_fail;
}
Py_DECREF(kwdict);
kwdict = d;
}
}
if (flags & CALL_FLAG_VAR) {
@ -3796,10 +3814,11 @@ ext_do_call(PyObject *func, PyObject ***pp_stack, int flags, int na, int nk)
if (t == NULL) {
if (PyErr_ExceptionMatches(PyExc_TypeError)) {
PyErr_Format(PyExc_TypeError,
"%s%s argument after * "
"must be a sequence",
"%.200s%.200s argument after * "
"must be a sequence, not %200s",
PyEval_GetFuncName(func),
PyEval_GetFuncDesc(func));
PyEval_GetFuncDesc(func),
stararg->ob_type->tp_name);
}
goto ext_call_fail;
}

View File

@ -1408,7 +1408,7 @@ compiler_function(struct compiler *c, stmt_ty s)
PyObject *first_const = Py_None;
arguments_ty args = s->v.FunctionDef.args;
expr_ty returns = s->v.FunctionDef.returns;
asdl_seq* decos = s->v.FunctionDef.decorators;
asdl_seq* decos = s->v.FunctionDef.decorator_list;
stmt_ty st;
int i, n, docstring, kw_default_count = 0, arglength;
int num_annotations;
@ -1479,7 +1479,12 @@ compiler_class(struct compiler *c, stmt_ty s)
PyCodeObject *co;
PyObject *str;
PySTEntryObject *ste;
int err;
int err, i;
asdl_seq* decos = s->v.ClassDef.decorator_list;
if (!compiler_decorators(c, decos))
return 0;
/* initialize statics */
if (build_class == NULL) {
@ -1577,7 +1582,12 @@ compiler_class(struct compiler *c, stmt_ty s)
s->v.ClassDef.kwargs))
return 0;
/* 6. store into <name> */
/* 6. apply decorators */
for (i = 0; i < asdl_seq_LEN(decos); i++) {
ADDOP_I(c, CALL_FUNCTION, 1);
}
/* 7. store into <name> */
if (!compiler_nameop(c, s->v.ClassDef.name, Store))
return 0;
return 1;

File diff suppressed because it is too large Load Diff

View File

@ -15,7 +15,7 @@
* and risks coring the interpreter. When the object stack gets this deep,
* raise an exception instead of continuing.
*/
#define MAX_MARSHAL_STACK_DEPTH 5000
#define MAX_MARSHAL_STACK_DEPTH 2000
#define TYPE_NULL '0'
#define TYPE_NONE 'N'
@ -235,9 +235,16 @@ w_object(PyObject *v, WFILE *p)
goto exit;
}
else {
int ok;
o = PyInt_FromSsize_t(PyDict_Size(p->strings));
PyDict_SetItem(p->strings, v, o);
Py_DECREF(o);
ok = o &&
PyDict_SetItem(p->strings, v, o) >= 0;
Py_XDECREF(o);
if (!ok) {
p->depth--;
p->error = 1;
return;
}
w_byte(TYPE_INTERNED, p);
}
}
@ -401,7 +408,7 @@ PyMarshal_WriteObjectToFile(PyObject *x, FILE *fp, int version)
typedef WFILE RFILE; /* Same struct with different invariants */
#define rs_byte(p) (((p)->ptr != (p)->end) ? (unsigned char)*(p)->ptr++ : EOF)
#define rs_byte(p) (((p)->ptr < (p)->end) ? (unsigned char)*(p)->ptr++ : EOF)
#define r_byte(p) ((p)->fp ? getc((p)->fp) : rs_byte(p))
@ -492,42 +499,60 @@ r_object(RFILE *p)
PyObject *v, *v2, *v3;
long i, n;
int type = r_byte(p);
PyObject *retval;
p->depth++;
if (p->depth > MAX_MARSHAL_STACK_DEPTH) {
p->depth--;
PyErr_SetString(PyExc_ValueError, "recursion limit exceeded");
return NULL;
}
switch (type) {
case EOF:
PyErr_SetString(PyExc_EOFError,
"EOF read where object expected");
return NULL;
retval = NULL;
break;
case TYPE_NULL:
return NULL;
retval = NULL;
break;
case TYPE_NONE:
Py_INCREF(Py_None);
return Py_None;
retval = Py_None;
break;
case TYPE_STOPITER:
Py_INCREF(PyExc_StopIteration);
return PyExc_StopIteration;
retval = PyExc_StopIteration;
break;
case TYPE_ELLIPSIS:
Py_INCREF(Py_Ellipsis);
return Py_Ellipsis;
retval = Py_Ellipsis;
break;
case TYPE_FALSE:
Py_INCREF(Py_False);
return Py_False;
retval = Py_False;
break;
case TYPE_TRUE:
Py_INCREF(Py_True);
return Py_True;
retval = Py_True;
break;
case TYPE_INT:
return PyInt_FromLong(r_long(p));
retval = PyInt_FromLong(r_long(p));
break;
case TYPE_INT64:
return r_long64(p);
retval = r_long64(p);
break;
case TYPE_LONG:
{
@ -537,12 +562,15 @@ r_object(RFILE *p)
if (n < -INT_MAX || n > INT_MAX) {
PyErr_SetString(PyExc_ValueError,
"bad marshal data");
return NULL;
retval = NULL;
break;
}
size = n<0 ? -n : n;
ob = _PyLong_New(size);
if (ob == NULL)
return NULL;
if (ob == NULL) {
retval = NULL;
break;
}
ob->ob_size = n;
for (i = 0; i < size; i++) {
int digit = r_short(p);
@ -550,11 +578,14 @@ r_object(RFILE *p)
Py_DECREF(ob);
PyErr_SetString(PyExc_ValueError,
"bad marshal data");
return NULL;
ob = NULL;
break;
}
ob->ob_digit[i] = digit;
if (ob != NULL)
ob->ob_digit[i] = digit;
}
return (PyObject *)ob;
retval = (PyObject *)ob;
break;
}
case TYPE_FLOAT:
@ -565,13 +596,16 @@ r_object(RFILE *p)
if (n == EOF || r_string(buf, (int)n, p) != n) {
PyErr_SetString(PyExc_EOFError,
"EOF read where object expected");
return NULL;
retval = NULL;
break;
}
buf[n] = '\0';
PyFPE_START_PROTECT("atof", return 0)
retval = NULL;
PyFPE_START_PROTECT("atof", break)
dx = PyOS_ascii_atof(buf);
PyFPE_END_PROTECT(dx)
return PyFloat_FromDouble(dx);
retval = PyFloat_FromDouble(dx);
break;
}
case TYPE_BINARY_FLOAT:
@ -581,13 +615,16 @@ r_object(RFILE *p)
if (r_string((char*)buf, 8, p) != 8) {
PyErr_SetString(PyExc_EOFError,
"EOF read where object expected");
return NULL;
retval = NULL;
break;
}
x = _PyFloat_Unpack8(buf, 1);
if (x == -1.0 && PyErr_Occurred()) {
return NULL;
retval = NULL;
break;
}
return PyFloat_FromDouble(x);
retval = PyFloat_FromDouble(x);
break;
}
#ifndef WITHOUT_COMPLEX
@ -599,23 +636,27 @@ r_object(RFILE *p)
if (n == EOF || r_string(buf, (int)n, p) != n) {
PyErr_SetString(PyExc_EOFError,
"EOF read where object expected");
return NULL;
retval = NULL;
break;
}
buf[n] = '\0';
PyFPE_START_PROTECT("atof", return 0)
retval = NULL;
PyFPE_START_PROTECT("atof", break;)
c.real = PyOS_ascii_atof(buf);
PyFPE_END_PROTECT(c)
n = r_byte(p);
if (n == EOF || r_string(buf, (int)n, p) != n) {
PyErr_SetString(PyExc_EOFError,
"EOF read where object expected");
return NULL;
retval = NULL;
break;
}
buf[n] = '\0';
PyFPE_START_PROTECT("atof", return 0)
PyFPE_START_PROTECT("atof", break)
c.imag = PyOS_ascii_atof(buf);
PyFPE_END_PROTECT(c)
return PyComplex_FromCComplex(c);
retval = PyComplex_FromCComplex(c);
break;
}
case TYPE_BINARY_COMPLEX:
@ -625,22 +666,27 @@ r_object(RFILE *p)
if (r_string((char*)buf, 8, p) != 8) {
PyErr_SetString(PyExc_EOFError,
"EOF read where object expected");
return NULL;
retval = NULL;
break;
}
c.real = _PyFloat_Unpack8(buf, 1);
if (c.real == -1.0 && PyErr_Occurred()) {
return NULL;
retval = NULL;
break;
}
if (r_string((char*)buf, 8, p) != 8) {
PyErr_SetString(PyExc_EOFError,
"EOF read where object expected");
return NULL;
retval = NULL;
break;
}
c.imag = _PyFloat_Unpack8(buf, 1);
if (c.imag == -1.0 && PyErr_Occurred()) {
return NULL;
retval = NULL;
break;
}
return PyComplex_FromCComplex(c);
retval = PyComplex_FromCComplex(c);
break;
}
#endif
@ -649,32 +695,42 @@ r_object(RFILE *p)
n = r_long(p);
if (n < 0 || n > INT_MAX) {
PyErr_SetString(PyExc_ValueError, "bad marshal data");
return NULL;
retval = NULL;
break;
}
v = PyString_FromStringAndSize((char *)NULL, n);
if (v == NULL)
return v;
if (v == NULL) {
retval = NULL;
break;
}
if (r_string(PyString_AS_STRING(v), (int)n, p) != n) {
Py_DECREF(v);
PyErr_SetString(PyExc_EOFError,
"EOF read where object expected");
return NULL;
retval = NULL;
break;
}
if (type == TYPE_INTERNED) {
PyString_InternInPlace(&v);
PyList_Append(p->strings, v);
if (PyList_Append(p->strings, v) < 0) {
retval = NULL;
break;
}
}
return v;
retval = v;
break;
case TYPE_STRINGREF:
n = r_long(p);
if (n < 0 || n >= PyList_GET_SIZE(p->strings)) {
PyErr_SetString(PyExc_ValueError, "bad marshal data");
return NULL;
retval = NULL;
break;
}
v = PyList_GET_ITEM(p->strings, n);
Py_INCREF(v);
return v;
retval = v;
break;
case TYPE_UNICODE:
{
@ -683,31 +739,39 @@ r_object(RFILE *p)
n = r_long(p);
if (n < 0 || n > INT_MAX) {
PyErr_SetString(PyExc_ValueError, "bad marshal data");
return NULL;
retval = NULL;
break;
}
buffer = PyMem_NEW(char, n);
if (buffer == NULL)
return PyErr_NoMemory();
if (buffer == NULL) {
retval = PyErr_NoMemory();
break;
}
if (r_string(buffer, (int)n, p) != n) {
PyMem_DEL(buffer);
PyErr_SetString(PyExc_EOFError,
"EOF read where object expected");
return NULL;
retval = NULL;
break;
}
v = PyUnicode_DecodeUTF8(buffer, n, NULL);
PyMem_DEL(buffer);
return v;
retval = v;
break;
}
case TYPE_TUPLE:
n = r_long(p);
if (n < 0 || n > INT_MAX) {
PyErr_SetString(PyExc_ValueError, "bad marshal data");
return NULL;
retval = NULL;
break;
}
v = PyTuple_New((int)n);
if (v == NULL)
return v;
if (v == NULL) {
retval = NULL;
break;
}
for (i = 0; i < n; i++) {
v2 = r_object(p);
if ( v2 == NULL ) {
@ -720,17 +784,21 @@ r_object(RFILE *p)
}
PyTuple_SET_ITEM(v, (int)i, v2);
}
return v;
retval = v;
break;
case TYPE_LIST:
n = r_long(p);
if (n < 0 || n > INT_MAX) {
PyErr_SetString(PyExc_ValueError, "bad marshal data");
return NULL;
retval = NULL;
break;
}
v = PyList_New((int)n);
if (v == NULL)
return v;
if (v == NULL) {
retval = NULL;
break;
}
for (i = 0; i < n; i++) {
v2 = r_object(p);
if ( v2 == NULL ) {
@ -741,14 +809,17 @@ r_object(RFILE *p)
v = NULL;
break;
}
PyList_SetItem(v, (int)i, v2);
PyList_SET_ITEM(v, (int)i, v2);
}
return v;
retval = v;
break;
case TYPE_DICT:
v = PyDict_New();
if (v == NULL)
return NULL;
if (v == NULL) {
retval = NULL;
break;
}
for (;;) {
PyObject *key, *val;
key = r_object(p);
@ -764,18 +835,22 @@ r_object(RFILE *p)
Py_DECREF(v);
v = NULL;
}
return v;
retval = v;
break;
case TYPE_SET:
case TYPE_FROZENSET:
n = r_long(p);
if (n < 0) {
if (n < 0 || n > INT_MAX) {
PyErr_SetString(PyExc_ValueError, "bad marshal data");
return NULL;
retval = NULL;
break;
}
v = PyTuple_New((int)n);
if (v == NULL)
return v;
if (v == NULL) {
retval = NULL;
break;
}
for (i = 0; i < n; i++) {
v2 = r_object(p);
if ( v2 == NULL ) {
@ -788,14 +863,17 @@ r_object(RFILE *p)
}
PyTuple_SET_ITEM(v, (int)i, v2);
}
if (v == NULL)
return v;
if (v == NULL) {
retval = NULL;
break;
}
if (type == TYPE_SET)
v3 = PySet_New(v);
else
v3 = PyFrozenSet_New(v);
Py_DECREF(v);
return v3;
retval = v3;
break;
case TYPE_CODE:
{
@ -872,14 +950,19 @@ r_object(RFILE *p)
return v;
}
retval = v;
break;
default:
/* Bogus data got written, which isn't ideal.
This will let you keep working and recover. */
PyErr_SetString(PyExc_ValueError, "bad marshal data");
return NULL;
retval = NULL;
break;
}
p->depth--;
return retval;
}
static PyObject *
@ -985,6 +1068,7 @@ PyMarshal_ReadObjectFromFile(FILE *fp)
PyObject *result;
rf.fp = fp;
rf.strings = PyList_New(0);
rf.depth = 0;
result = r_object(&rf);
Py_DECREF(rf.strings);
return result;
@ -999,6 +1083,7 @@ PyMarshal_ReadObjectFromString(char *str, Py_ssize_t len)
rf.ptr = str;
rf.end = str + len;
rf.strings = PyList_New(0);
rf.depth = 0;
result = r_object(&rf);
Py_DECREF(rf.strings);
return result;
@ -1125,6 +1210,7 @@ marshal_load(PyObject *self, PyObject *f)
}
rf.fp = PyFile_AsFile(f);
rf.strings = PyList_New(0);
rf.depth = 0;
result = read_object(&rf);
Py_DECREF(rf.strings);
return result;
@ -1153,6 +1239,7 @@ marshal_loads(PyObject *self, PyObject *args)
rf.ptr = s;
rf.end = s + n;
rf.strings = PyList_New(0);
rf.depth = 0;
result = read_object(&rf);
Py_DECREF(rf.strings);
return result;

View File

@ -1009,8 +1009,8 @@ symtable_visit_stmt(struct symtable *st, stmt_ty s)
s->v.FunctionDef.args->kw_defaults);
if (!symtable_visit_annotations(st, s))
return 0;
if (s->v.FunctionDef.decorators)
VISIT_SEQ(st, expr, s->v.FunctionDef.decorators);
if (s->v.FunctionDef.decorator_list)
VISIT_SEQ(st, expr, s->v.FunctionDef.decorator_list);
if (!symtable_enter_block(st, s->v.FunctionDef.name,
FunctionBlock, (void *)s, s->lineno))
return 0;
@ -1029,6 +1029,8 @@ symtable_visit_stmt(struct symtable *st, stmt_ty s)
VISIT(st, expr, s->v.ClassDef.starargs);
if (s->v.ClassDef.kwargs)
VISIT(st, expr, s->v.ClassDef.kwargs);
if (s->v.ClassDef.decorator_list)
VISIT_SEQ(st, expr, s->v.ClassDef.decorator_list);
if (!symtable_enter_block(st, s->v.ClassDef.name, ClassBlock,
(void *)s, s->lineno))
return 0;

Some files were not shown because too many files have changed in this diff Show More