[Python-Dev] 2.2a1 patch from PyChecker (original) (raw)
Neal Norwitz neal@metaslash.com
Thu, 09 Aug 2001 15:33:52 -0400
- Previous message: [Python-Dev] optimizing non-local object access
- Next message: [Python-Dev] 2.2a1 patch from PyChecker
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
This is a multi-part message in MIME format. --------------1899DB72A2CEC0DFFD96771A Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit
Attached is a patch to address some problems found by PyChecker. Mostly unused imports/locals, etc.
There were a few methods that were removed because they were duplicated (ConfigParser.py:has_option, gzip.py:writelines, locale.py:set_locale). I deleted the first occurrence, but I'm not sure that was always right.
I have changed many unused locals to _ (e.g., for _ in range(3):). This gets PyChecker to shut up about being unused. It also defaults to ignoring unused local variables if their name is 'empty' or 'unused'.
There are many more unused warnings. Does anybody want me to change
the variables to empty, unused, _, or something different?
Should the default unused names be expanded?
Note: I could not run under Python 2.2a1 because dir([]) does not return the methods.
Here are some other warnings I didn't fix because I wasn't sure what should be done:
audiodev.py:214: No global (BUFFERSIZE) found (this is old, should BUFFERSIZE be defined, a better exception raised, and/or deprecation warning?)
cgi.py:820: Overriden method (values) doesn't match signature in class (cgi.FormContentDict)
ihooks.py:491: Overriden method (reload) doesn't match signature in class (ihooks.BasicModuleImporter)
imaplib.py:1026: No global (j) found
ntpath.py:411: No global (WindowsError) found (I ran on unix, not sure if this is ok on windows.)
pdb.py:138: Overriden method (default) doesn't match signature in class (cmd.Cmd)
profile.py:179: No global (operator) found
-- Neal --------------1899DB72A2CEC0DFFD96771A Content-Type: text/plain; charset=us-ascii; name="py-2.2a1-patch" Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="py-2.2a1-patch"
diff -C 5 Lib.orig/ConfigParser.py Lib/ConfigParser.py
*** Lib.orig/ConfigParser.py Sat Jul 14 03:47:34 2001
--- Lib/ConfigParser.py Mon Aug 6 20:26:14 2001
***************
*** 83,93 ****
write(fp)
write the configuration state in .ini format
"""
- import sys
import string
import re
all = ["NoSectionError","DuplicateSectionError","NoOptionError",
"InterpolationError","InterpolationDepthError","ParsingError",
--- 83,92 ----
***************
*** 149,174 ****
% (section, option, rawval))
self.option = option
self.section = section
class ParsingError(Error):
! def init(self, filename):
! Error.init(self, 'File contains parsing errors: %s' % filename)
self.filename = filename
self.errors = []
def append(self, lineno, line):
self.errors.append((lineno, line))
self._msg = self._msg + '\n\t[line %2d]: %s' % (lineno, line)
class MissingSectionHeaderError(ParsingError):
def init(self, filename, lineno, line):
! Error.init(
! self,
'File contains no section headers.\nfile: %s, line: %d\n%s' %
(filename, lineno, line))
- self.filename = filename
self.lineno = lineno
self.line = line
--- 148,174 ----
% (section, option, rawval))
self.option = option
self.section = section
class ParsingError(Error):
! def init(self, filename, msg=None):
! if msg is None:
! msg = 'File contains parsing errors: %s' % filename
! Error.init(self, msg)
self.filename = filename
self.errors = []
def append(self, lineno, line):
self.errors.append((lineno, line))
self._msg = self._msg + '\n\t[line %2d]: %s' % (lineno, line)
class MissingSectionHeaderError(ParsingError):
def init(self, filename, lineno, line):
! ParsingError.init(
! self, filename,
'File contains no section headers.\nfile: %s, line: %d\n%s' %
(filename, lineno, line))
self.lineno = lineno
self.line = line
***************
*** 213,226 ****
raise NoSectionError(section)
opts.update(self.__defaults)
if opts.has_key('name'):
del opts['name']
return opts.keys()
def has_option(self, section, option):
"""Return whether the given section has the given option."""
return option in self.options(section) def read(self, filenames): """Read and parse a filename or a list of filenames. Files that cannot be opened are silently ignored; this is
--- 213,222 ----
diff -C 5 Lib.orig/Cookie.py Lib/Cookie.py
*** Lib.orig/Cookie.py Sat Jul 7 18:55:27 2001
--- Lib/Cookie.py Mon Aug 6 20:26:31 2001
***************
*** 213,223 ****
# |----helps out font-lock
#
# Import our required modules
#
! import string, sys
from UserDict import UserDict
try:
from cPickle import dumps, loads
except ImportError:
--- 213,223 ----
# |----helps out font-lock
#
# Import our required modules
#
! import string
from UserDict import UserDict
try:
from cPickle import dumps, loads
except ImportError:
diff -C 5 Lib.orig/MimeWriter.py Lib/MimeWriter.py
*** Lib.orig/MimeWriter.py Fri Feb 9 04:34:36 2001
--- Lib/MimeWriter.py Mon Aug 6 20:27:58 2001
***************
*** 103,122 ****
self._headers = []
def startbody(self, ctype, plist=[], prefix=1):
for name, value in plist:
ctype = ctype + ';\n %s="%s"' % (name, value)
! self.addheader("Content-Type", ctype, prefix=prefix)
self.flushheaders()
self._fp.write("\n")
return self._fp
def startmultipartbody(self, subtype, boundary=None, plist=[], prefix=1):
self._boundary = boundary or mimetools.choose_boundary()
return self.startbody("multipart/" + subtype,
[("boundary", self._boundary)] + plist,
! prefix=prefix)
def nextpart(self):
self._fp.write("\n--" + self._boundary + "\n")
return self.class(self._fp)
--- 103,122 ----
self._headers = []
def startbody(self, ctype, plist=[], prefix=1):
for name, value in plist:
ctype = ctype + ';\n %s="%s"' % (name, value)
! self.addheader("Content-Type", ctype, prefix)
self.flushheaders()
self._fp.write("\n")
return self._fp
def startmultipartbody(self, subtype, boundary=None, plist=[], prefix=1):
self._boundary = boundary or mimetools.choose_boundary()
return self.startbody("multipart/" + subtype,
[("boundary", self._boundary)] + plist,
! prefix)
def nextpart(self):
self._fp.write("\n--" + self._boundary + "\n")
return self.class(self._fp)
diff -C 5 Lib.orig/StringIO.py Lib/StringIO.py
*** Lib.orig/StringIO.py Fri Feb 9 08:37:37 2001
--- Lib/StringIO.py Mon Aug 6 20:30:17 2001
***************
*** 182,192 ****
print 'File length =', length
f.seek(len(lines[0]))
f.write(lines[1])
f.seek(0)
print 'First line =', f.readline()
- here = f.tell()
line = f.readline()
print 'Second line =', line
f.seek(-len(line), 1)
line2 = f.read(len(line))
if line != line2:
--- 182,191 ----
diff -C 5 Lib.orig/asyncore.py Lib/asyncore.py
*** Lib.orig/asyncore.py Sat Jul 7 18:55:27 2001
--- Lib/asyncore.py Mon Aug 6 20:31:22 2001
***************
*** 151,161 ****
map=socket_map
# timeout is in milliseconds
timeout = int(timeout1000)
pollster = select.poll()
if map:
- l = []
for fd, obj in map.items():
flags = 0
if obj.readable():
flags = select.POLLIN
if obj.writable():
--- 151,160 ----
diff -C 5 Lib.orig/bdb.py Lib/bdb.py
*** Lib.orig/bdb.py Sat Jul 7 18:55:27 2001
--- Lib/bdb.py Mon Aug 6 20:43:40 2001
***************
*** 216,226 ****
if not self.breaks.has_key(filename):
self.breaks[filename] = []
list = self.breaks[filename]
if not lineno in list:
list.append(lineno)
! bp = Breakpoint(filename, lineno, temporary, cond)
def clear_break(self, filename, lineno):
filename = self.canonic(filename)
if not self.breaks.has_key(filename):
return 'There are no breakpoints in %s' % filename
--- 216,226 ----
if not self.breaks.has_key(filename):
self.breaks[filename] = []
list = self.breaks[filename]
if not lineno in list:
list.append(lineno)
! _ = Breakpoint(filename, lineno, temporary, cond)
def clear_break(self, filename, lineno):
filename = self.canonic(filename)
if not self.breaks.has_key(filename):
return 'There are no breakpoints in %s' % filename
diff -C 5 Lib.orig/cgi.py Lib/cgi.py
*** Lib.orig/cgi.py Sat Jul 7 18:55:27 2001
--- Lib/cgi.py Mon Aug 6 20:47:55 2001
***************
*** 846,856 ****
Write minimal HTTP headers and dump all information provided to
the script in HTML form.
"""
- import traceback
print "Content-type: text/html"
print
sys.stderr = sys.stdout
try:
form = FieldStorage() # Replace with other classes to test those
--- 846,855 ----
diff -C 5 Lib.orig/codecs.py Lib/codecs.py
*** Lib.orig/codecs.py Fri Jul 6 03:01:30 2001
--- Lib/codecs.py Mon Aug 6 20:48:48 2001
***************
*** 5,15 ****
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
"""#"
! import struct, types, builtin
### Registry and builtin stateless codec functions
try:
from _codecs import *
--- 5,15 ----
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
"""#"
! import struct, builtin
### Registry and builtin stateless codec functions
try:
from _codecs import *
***************
*** 215,225 ****
data = read(size)
i = 0
while 1:
try:
object, decodedbytes = decode(data, self.errors)
! except ValueError, why:
# This method is slow but should work under pretty much
# all conditions; at most 10 tries are made
i = i + 1
newdata = read(1)
if not newdata or i > 10:
--- 215,225 ----
data = read(size)
i = 0
while 1:
try:
object, decodedbytes = decode(data, self.errors)
! except ValueError:
# This method is slow but should work under pretty much
# all conditions; at most 10 tries are made
i = i + 1
newdata = read(1)
if not newdata or i > 10:
diff -C 5 Lib.orig/codeop.py Lib/codeop.py
*** Lib.orig/codeop.py Sat Apr 7 20:43:13 2001
--- Lib/codeop.py Mon Aug 6 20:49:33 2001
***************
*** 50,65 ****
if line and line[0] != '#':
break # Leave it alone
else:
source = "pass" # Replace it with a 'pass' statement
! err = err1 = err2 = None
code = code1 = code2 = None
try:
code = compile(source, filename, symbol)
! except SyntaxError, err:
pass
try:
code1 = compile(source + "\n", filename, symbol)
except SyntaxError, err1:
--- 50,65 ----
if line and line[0] != '#':
break # Leave it alone
else:
source = "pass" # Replace it with a 'pass' statement
! err1 = err2 = None
code = code1 = code2 = None
try:
code = compile(source, filename, symbol)
! except SyntaxError:
pass
try:
code1 = compile(source + "\n", filename, symbol)
except SyntaxError, err1:
diff -C 5 Lib.orig/fileinput.py Lib/fileinput.py
*** Lib.orig/fileinput.py Sat Jan 20 18:34:12 2001
--- Lib/fileinput.py Mon Aug 6 20:53:16 2001
***************
*** 287,297 ****
backup = 0
opts, args = getopt.getopt(sys.argv[1:], "ib:")
for o, a in opts:
if o == '-i': inplace = 1
if o == '-b': backup = a
! for line in input(args, inplace=inplace, backup=backup):
if line[-1:] == '\n': line = line[:-1]
if line[-1:] == '\r': line = line[:-1]
print "%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(),
isfirstline() and "" or "", line)
print "%d: %s[%d]" % (lineno(), filename(), filelineno())
--- 287,297 ----
backup = 0
opts, args = getopt.getopt(sys.argv[1:], "ib:")
for o, a in opts:
if o == '-i': inplace = 1
if o == '-b': backup = a
! for line in input(args, inplace, backup):
if line[-1:] == '\n': line = line[:-1]
if line[-1:] == '\r': line = line[:-1]
print "%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(),
isfirstline() and "*" or "", line)
print "%d: %s[%d]" % (lineno(), filename(), filelineno())
diff -C 5 Lib.orig/formatter.py Lib/formatter.py
*** Lib.orig/formatter.py Sat Jul 7 18:55:27 2001
--- Lib/formatter.py Mon Aug 6 20:53:57 2001
***************
*** 299,311 ****
def send_literal_data(self, data): pass
class AbstractWriter(NullWriter):
- def init(self):
- pass
def new_alignment(self, align):
print "new_alignment(%s)" % `align`
def new_font(self, font):
print "new_font(%s)" % `font`
--- 299,308 ----
diff -C 5 Lib.orig/ftplib.py Lib/ftplib.py
*** Lib.orig/ftplib.py Mon Apr 9 00:31:50 2001
--- Lib/ftplib.py Mon Aug 6 20:54:20 2001
***************
*** 34,44 ****
# Modified by Siebren to support docstrings and PASV.
#
import os
import sys
- import string
# Import SOCKS module if it exists, else standard socket module socket
try:
import SOCKS; socket = SOCKS; del SOCKS # import SOCKS as socket
from socket import getfqdn; socket.getfqdn = getfqdn; del getfqdn
--- 34,43 ----
diff -C 5 Lib.orig/getpass.py Lib/getpass.py
*** Lib.orig/getpass.py Tue Feb 27 16:23:31 2001
--- Lib/getpass.py Mon Aug 6 20:56:40 2001
***************
*** 24,34 ****
try:
fd = sys.stdin.fileno()
except:
return default_getpass(prompt)
- getpass = default_getpass
old = termios.tcgetattr(fd) # a copy to save
new = old[:]
new[3] = new[3] & ~termios.ECHO # 3 == 'lflags'
try:
--- 24,33 ----
***************
*** 68,78 ****
def _raw_input(prompt=""):
# A raw_input() replacement that doesn't save the string in the
# GNU readline history.
- import sys
prompt = str(prompt)
if prompt:
sys.stdout.write(prompt)
line = sys.stdin.readline()
if not line:
--- 67,76 ----
diff -C 5 Lib.orig/gettext.py Lib/gettext.py
*** Lib.orig/gettext.py Tue Jan 23 10:35:04 2001
--- Lib/gettext.py Mon Aug 6 20:57:07 2001
***************
*** 156,166 ****
msgcount &= MASK
masteridx &= MASK
transidx &= MASK
# Now put all messages from the .mo file buffer into the catalog
# dictionary.
! for i in xrange(0, msgcount):
mlen, moff = unpack(ii, buf[masteridx:masteridx+8])
moff &= MASK
mend = moff + (mlen & MASK)
tlen, toff = unpack(ii, buf[transidx:transidx+8])
toff &= MASK
--- 156,166 ----
msgcount &= MASK
masteridx &= MASK
transidx &= MASK
# Now put all messages from the .mo file buffer into the catalog
# dictionary.
! for _ in xrange(0, msgcount):
mlen, moff = unpack(ii, buf[masteridx:masteridx+8])
moff &= MASK
mend = moff + (mlen & MASK)
tlen, toff = unpack(ii, buf[transidx:transidx+8])
toff &= MASK
diff -C 5 Lib.orig/gopherlib.py Lib/gopherlib.py
*** Lib.orig/gopherlib.py Fri Feb 9 05:10:02 2001
--- Lib/gopherlib.py Mon Aug 6 20:57:23 2001
***************
*** 167,177 ****
import getopt
opts, args = getopt.getopt(sys.argv[1:], '')
selector = DEF_SELECTOR
type = selector[0]
host = DEF_HOST
- port = DEF_PORT
if args:
host = args[0]
args = args[1:]
if args:
type = args[0]
--- 167,176 ----
diff -C 5 Lib.orig/gzip.py Lib/gzip.py
*** Lib.orig/gzip.py Tue Mar 20 10:51:14 2001
--- Lib/gzip.py Mon Aug 6 21:00:00 2001
***************
*** 137,149 ****
if len(data) > 0:
self.size = self.size + len(data)
self.crc = zlib.crc32(data, self.crc)
self.fileobj.write( self.compress.compress(data) )
- def writelines(self,lines):
- self.write(" ".join(lines))
def read(self, size=-1):
if self.extrasize <= 0 and self.fileobj is None:
return ''
readsize = 1024
--- 137,146 ----
***************
*** 271,281 ****
return 0
def readline(self, size=-1):
if size < 0: size = sys.maxint
bufs = []
- orig_size = size
readsize = min(100, size) # Read from the file in small chunks
while 1:
if size == 0:
return "".join(bufs) # Return resulting line
--- 268,277 ----
***************
*** 318,328 ****
def _test():
# Act like gzip; with -d, act like gunzip.
# The input file is not deleted, however, nor are any other gzip
# options or features supported.
- import sys
args = sys.argv[1:]
decompress = args and args[0] == "-d"
if decompress:
args = args[1:]
if not args:
--- 314,323 ----
diff -C 5 Lib.orig/httplib.py Lib/httplib.py
*** Lib.orig/httplib.py Sat Jul 7 18:55:27 2001
--- Lib/httplib.py Mon Aug 6 21:01:20 2001
***************
*** 588,598 ****
msgbuf = []
while 1:
try:
buf = self.__ssl.read()
! except socket.sslerror, msg:
break
if buf == '':
break
msgbuf.append(buf)
return StringIO("".join(msgbuf))
--- 588,598 ----
msgbuf = []
while 1:
try:
buf = self.__ssl.read()
! except socket.sslerror:
break
if buf == '':
break
msgbuf.append(buf)
return StringIO("".join(msgbuf))
diff -C 5 Lib.orig/ihooks.py Lib/ihooks.py
*** Lib.orig/ihooks.py Fri Feb 9 05:17:30 2001
--- Lib/ihooks.py Mon Aug 6 21:03:51 2001
***************
*** 489,503 ****
return m
def reload(self, module):
name = module.__name__
if '.' not in name:
! return self.import_it(name, name, None, force_load=1)
i = name.rfind('.')
pname = name[:i]
parent = self.modules[pname]
! return self.import_it(name[i+1:], name, parent, force_load=1)
default_importer = None
current_importer = None
--- 489,503 ----
return m
def reload(self, module):
name = module.__name__
if '.' not in name:
! return self.import_it(name, name, None, 1)
i = name.rfind('.')
pname = name[:i]
parent = self.modules[pname]
! return self.import_it(name[i+1:], name, parent, 1)
default_importer = None
current_importer = None
diff -C 5 Lib.orig/imaplib.py Lib/imaplib.py
*** Lib.orig/imaplib.py Sat Jul 7 18:55:27 2001
--- Lib/imaplib.py Mon Aug 6 21:05:16 2001
***************
*** 778,788 ****
# Instead, send me details of the unexpected response and
# I'll update the code in _get_response()'. try: self._get_response() ! except self.abort, val: if __debug__: if self.debug >= 1: print_log() raise --- 778,788 ---- # Instead, send me details of the unexpected response and # I'll update the code in
_get_response()'.
try:
self._get_response()
! except self.abort:
if debug:
if self.debug >= 1:
print_log()
raise
***************
*** 1041,1051 ****
if name == 'main':
! import getopt, getpass, sys
try:
optlist, args = getopt.getopt(sys.argv[1:], 'd:')
except getopt.error, val:
pass
--- 1041,1051 ----
if name == 'main':
! import getopt, getpass
try:
optlist, args = getopt.getopt(sys.argv[1:], 'd:')
except getopt.error, val:
pass
diff -C 5 Lib.orig/locale.py Lib/locale.py
*** Lib.orig/locale.py Mon Apr 16 12:04:10 2001
--- Lib/locale.py Mon Aug 6 21:07:58 2001
***************
*** 63,80 ****
'mon_thousands_sep': '',
'frac_digits': 127,
'mon_decimal_point': '',
'int_frac_digits': 127}
- def setlocale(category, value=None):
- """ setlocale(integer,string=None) -> string.
- Activates/queries locale processing.
- """
- if value is not None and value != 'C':
- raise Error, '_locale emulation only supports "C" locale'
- return 'C'
def strcoll(a,b):
""" strcoll(string,string) -> int.
Compares two strings according to the locale.
"""
return cmp(a,b)
--- 63,72 ----
***************
*** 266,278 ****
code = normalize(localename)
if '.' in code:
return code.split('.')[:2]
elif code == 'C':
return None, None
! else:
! raise ValueError, 'unknown locale: %s' % localename
! return l
def _build_localename(localetuple):
""" Builds a locale code from the given tuple (language code,
encoding).
--- 258,268 ----
code = normalize(localename)
if '.' in code:
return code.split('.')[:2]
elif code == 'C':
return None, None
! raise ValueError, 'unknown locale: %s' % localename
def _build_localename(localetuple):
""" Builds a locale code from the given tuple (language code,
encoding).
diff -C 5 Lib.orig/mailbox.py Lib/mailbox.py
*** Lib.orig/mailbox.py Sat Jul 7 18:55:27 2001
--- Lib/mailbox.py Mon Aug 6 21:08:39 2001
***************
*** 256,268 ****
self.fp.seek(pos)
return
def _test():
- import time
import sys
- import os
args = sys.argv[1:]
if not args:
for key in 'MAILDIR', 'MAIL', 'LOGNAME', 'USER':
if os.environ.has_key(key):
--- 256,266 ----
diff -C 5 Lib.orig/multifile.py Lib/multifile.py
*** Lib.orig/multifile.py Sun Mar 11 21:56:15 2001
--- Lib/multifile.py Mon Aug 6 21:11:47 2001
***************
*** 25,36 ****
it normally attempts in order to make seeks relative to the beginning of the
current file part. This may be useful when using MultiFile with a non-
seekable stream object.
"""
- import sys
all = ["MultiFile","Error"]
class Error(Exception):
pass
--- 25,34 ----
diff -C 5 Lib.orig/nturl2path.py Lib/nturl2path.py
*** Lib.orig/nturl2path.py Sat Feb 17 22:30:53 2001
--- Lib/nturl2path.py Mon Aug 6 21:14:48 2001
***************
*** 40,50 ****
becomes
///C|/foo/bar/spam.foo
"""
! import string, urllib
if not ':' in p:
# No drive specifier, just convert slashes and quote the name
if p[:2] == '\\':
# path is something like \host\path\on\remote\host
# convert this to ////host/path/on/remote/host
--- 40,50 ----
becomes
///C|/foo/bar/spam.foo
"""
! import urllib
if not ':' in p:
# No drive specifier, just convert slashes and quote the name
if p[:2] == '\\':
# path is something like \host\path\on\remote\host
# convert this to ////host/path/on/remote/host
diff -C 5 Lib.orig/pdb.py Lib/pdb.py
*** Lib.orig/pdb.py Fri Feb 9 18:28:07 2001
--- Lib/pdb.py Mon Aug 6 21:15:22 2001
***************
*** 214,224 ****
else:
filename = f
arg = arg[colon+1:].lstrip()
try:
lineno = int(arg)
! except ValueError, msg:
print '*** Bad lineno:', arg
return
else:
# no colon; can be lineno or function
try:
--- 214,224 ----
else:
filename = f
arg = arg[colon+1:].lstrip()
try:
lineno = int(arg)
! except ValueError:
print '*** Bad lineno:', arg
return
else:
# no colon; can be lineno or function
try:
diff -C 5 Lib.orig/pipes.py Lib/pipes.py
*** Lib.orig/pipes.py Sat Jul 7 18:55:28 2001
--- Lib/pipes.py Mon Aug 6 21:16:37 2001
***************
*** 57,67 ****
For an example, see the function test() at the end of the file.
""" # '
- import sys
import re
import os
import tempfile
import string
--- 57,66 ----
diff -C 5 Lib.orig/posixfile.py Lib/posixfile.py
*** Lib.orig/posixfile.py Sat Jul 7 18:55:28 2001
--- Lib/posixfile.py Thu Aug 9 15:25:13 2001
***************
*** 105,115 ****
posix.dup2(self.file.fileno(), fd)
return posix.fdopen(fd, self.file.mode)
def flags(self, which):
! import fcntl
if which:
if len(which) > 1:
raise TypeError, 'Too many arguments'
which = which[0]
--- 105,115 ----
posix.dup2(self.file.fileno(), fd)
return posix.fdopen(fd, self.file.mode)
def flags(self, which):
! import fcntl, os
if which:
if len(which) > 1:
raise TypeError, 'Too many arguments'
which = which[0]
***************
*** 142,152 ****
if os.O_NDELAY & l_flags: which = which + 'n'
if os.O_SYNC & l_flags: which = which + 's'
return which
def lock(self, how, args):
! import struct, fcntl
if 'w' in how: l_type = fcntl.F_WRLCK
elif 'r' in how: l_type = fcntl.F_RDLCK
elif 'u' in how: l_type = fcntl.F_UNLCK
else: raise TypeError, 'no type of lock specified'
--- 142,152 ----
if os.O_NDELAY & l_flags: which = which + 'n'
if os.O_SYNC & l_flags: which = which + 's'
return which
def lock(self, how, args):
! import struct, fcntl, os
if 'w' in how: l_type = fcntl.F_WRLCK
elif 'r' in how: l_type = fcntl.F_RDLCK
elif 'u' in how: l_type = fcntl.F_UNLCK
else: raise TypeError, 'no type of lock specified'
diff -C 5 Lib.orig/profile.py Lib/profile.py
*** Lib.orig/profile.py Sat Jul 7 18:55:28 2001
--- Lib/profile.py Mon Aug 6 21🔞22 2001
***************
*** 143,153 ****
self.cur = None
self.cmd = ""
if not timer:
if os.name == 'mac':
- import MacOS
self.timer = MacOS.GetTicks
self.dispatcher = self.trace_dispatch_mac
self.get_time = _get_time_mac
elif hasattr(time, 'clock'):
self.timer = self.get_time = time.clock
--- 143,152 ----
diff -C 5 Lib.orig/pstats.py Lib/pstats.py
*** Lib.orig/pstats.py Sat Jul 7 18:55:28 2001
--- Lib/pstats.py Mon Aug 6 21:19:33 2001
***************
*** 183,193 ****
def get_sort_arg_defs(self):
"""Expand all abbreviations that are unique."""
if not self.sort_arg_dict:
self.sort_arg_dict = dict = {}
- std_list = dict.keys()
bad_list = {}
for word in self.sort_arg_dict_default.keys():
fragment = word
while fragment:
if not fragment:
--- 183,192 ----
diff -C 5 Lib.orig/pyclbr.py Lib/pyclbr.py
*** Lib.orig/pyclbr.py Sun Feb 11 21:00:42 2001
--- Lib/pyclbr.py Mon Aug 6 21:20:20 2001
***************
*** 51,61 ****
It can't locate the parent. It probably needs to have the same
hairy logic that the import locator already does. (This logic
exists coded in Python in the freeze package.)
"""
- import os
import sys
import imp
import re
import string
--- 51,60 ----
***************
*** 201,211 ****
f.close()
_modules[module] = dict
return dict
_modules[module] = dict
- imports = []
classstack = [] # stack of (class, indent) pairs
src = f.read()
f.close()
# To avoid having to stop the regexp at each newline, instead
--- 200,209 ----
diff -C 5 Lib.orig/random.py Lib/random.py
*** Lib.orig/random.py Thu Feb 15 18:56:39 2001
--- Lib/random.py Mon Aug 6 21:20:48 2001
***************
*** 582,592 ****
sum = 0.0
sqsum = 0.0
smallest = 1e10
largest = -1e10
t0 = time.time()
! for i in range(n):
x = eval(code)
sum = sum + x
sqsum = sqsum + xx
smallest = min(x, smallest)
largest = max(x, largest)
--- 582,592 ----
sum = 0.0
sqsum = 0.0
smallest = 1e10
largest = -1e10
t0 = time.time()
! for _ in range(n):
x = eval(code)
sum = sum + x
sqsum = sqsum + xx
smallest = min(x, smallest)
largest = max(x, largest)
***************
*** 623,633 ****
s = getstate()
jumpahead(N)
r1 = random()
# now do it the slow way
setstate(s)
! for i in range(N):
random()
r2 = random()
if r1 != r2:
raise ValueError("jumpahead test failed " + (N, r1, r2)
)
--- 623,633 ----
s = getstate()
jumpahead(N)
r1 = random()
# now do it the slow way
setstate(s)
! for _ in range(N):
random()
r2 = random()
if r1 != r2:
raise ValueError("jumpahead test failed " + (N, r1, r2)
)
diff -C 5 Lib.orig/rexec.py Lib/rexec.py
*** Lib.orig/rexec.py Sat Jul 7 18:55:28 2001
--- Lib/rexec.py Mon Aug 6 21:22:08 2001
***************
*** 366,376 ****
tr = None
return ty, va, tr
def test():
! import sys, getopt, traceback
opts, args = getopt.getopt(sys.argv[1:], 'vt:')
verbose = 0
trusted = []
for o, a in opts:
if o == '-v':
--- 366,376 ----
tr = None
return ty, va, tr
def test():
! import getopt, traceback
opts, args = getopt.getopt(sys.argv[1:], 'vt:')
verbose = 0
trusted = []
for o, a in opts:
if o == '-v':
***************
*** 387,397 ****
r.modules['sys'].path.insert(0, "")
fp = sys.stdin
if args and args[0] != '-':
try:
fp = open(args[0])
! except IOError, msg:
print "%s: can't open file %s" % (sys.argv[0], args[0]
)
return 1
if fp.isatty():
print "* RESTRICTED *** Python", sys.version
print sys.copyright
--- 387,397 ----
r.modules['sys'].path.insert(0, "")
fp = sys.stdin
if args and args[0] != '-':
try:
fp = open(args[0])
! except IOError:
print "%s: can't open file %s" % (sys.argv[0], args[0]
)
return 1
if fp.isatty():
print "*** RESTRICTED *** Python", sys.version
print sys.copyright
diff -C 5 Lib.orig/rfc822.py Lib/rfc822.py
*** Lib.orig/rfc822.py Tue Jul 17 00:19:05 2001
--- Lib/rfc822.py Mon Aug 6 21:22:48 2001
***************
*** 631,641 ****
elif self.field[self.pos] == '@':
self.pos = self.pos + 1
expectroute = 1
elif self.field[self.pos] == ':':
self.pos = self.pos + 1
- expectaddrspec = 1
else:
adlist = self.getaddrspec()
self.pos = self.pos + 1
break
self.gotonext()
--- 631,640 ----
diff -C 5 Lib.orig/robotparser.py Lib/robotparser.py
*** Lib.orig/robotparser.py Thu Feb 15 18:56:39 2001
--- Lib/robotparser.py Mon Aug 6 21:22:59 2001
***************
*** 229,239 ****
print "ok (%s)" % ac
print
def _test():
global debug
- import sys
rp = RobotFileParser()
debug = 1
# robots.txt that exists, gotten to by redirection
rp.set_url('http://www.musi-cal.com/robots.txt')
--- 229,238 ----
diff -C 5 Lib.orig/sched.py Lib/sched.py
*** Lib.orig/sched.py Thu Feb 15 17:15:13 2001
--- Lib/sched.py Mon Aug 6 21:23:12 2001
***************
*** 100,106 ****
now = self.timefunc()
if now < time:
self.delayfunc(time - now)
else:
del q[0]
! void = apply(action, argument)
self.delayfunc(0) # Let other threads run
--- 100,106 ----
now = self.timefunc()
if now < time:
self.delayfunc(time - now)
else:
del q[0]
! _ = apply(action, argument)
self.delayfunc(0) # Let other threads run
diff -C 5 Lib.orig/sgmllib.py Lib/sgmllib.py
*** Lib.orig/sgmllib.py Mon Jul 16 17:39:41 2001
--- Lib/sgmllib.py Mon Aug 6 21:23:43 2001
***************
*** 8,18 ****
# and CDATA (character data -- only end tags are special). RCDATA is
# not supported at all.
import re
- import string
all = ["SGMLParser"]
# Regular expressions used for parsing
--- 8,17 ----
diff -C 5 Lib.orig/smtpd.py Lib/smtpd.py
*** Lib.orig/smtpd.py Sun Apr 15 09:06:04 2001
--- Lib/smtpd.py Mon Aug 6 21:25:08 2001
***************
*** 370,380 ****
class MailmanProxy(PureProxy):
def process_message(self, peer, mailfrom, rcpttos, data):
from cStringIO import StringIO
- import paths
from Mailman import Utils
from Mailman import Message
from Mailman import MailList
# If the message is to a Mailman mailing list, then we'll invoke the
# Mailman script directly, without going through the real smtpd.
--- 370,379 ----
diff -C 5 Lib.orig/smtplib.py Lib/smtplib.py
*** Lib.orig/smtplib.py Thu Feb 15 17:15:13 2001
--- Lib/smtplib.py Mon Aug 6 21:25:37 2001
***************
*** 518,528 ****
# Test the sendmail method, which tests most of the others.
# Note: This always sends to localhost.
if name == 'main':
! import sys, rfc822
def prompt(prompt):
sys.stdout.write(prompt + ": ")
return sys.stdin.readline().strip()
--- 518,528 ----
# Test the sendmail method, which tests most of the others.
# Note: This always sends to localhost.
if name == 'main':
! import sys
def prompt(prompt):
sys.stdout.write(prompt + ": ")
return sys.stdin.readline().strip()
diff -C 5 Lib.orig/sunau.py Lib/sunau.py
*** Lib.orig/sunau.py Sun Jan 14 20:36:40 2001
--- Lib/sunau.py Mon Aug 6 21:26:36 2001
***************
*** 131,141 ****
class Error(Exception):
pass
def _read_u32(file):
x = 0L
! for i in range(4):
byte = file.read(1)
if byte == '':
raise EOFError
x = x256 + ord(byte)
return x
--- 131,141 ----
class Error(Exception):
pass
def _read_u32(file):
x = 0L
! for _ in range(4):
byte = file.read(1)
if byte == '':
raise EOFError
x = x256 + ord(byte)
return x
diff -C 5 Lib.orig/threading.py Lib/threading.py
*** Lib.orig/threading.py Mon Apr 2 16:15:57 2001
--- Lib/threading.py Mon Aug 6 21:30:23 2001
***************
*** 542,553 ****
# Self-test code
def _test():
- import random
class BoundedQueue(_Verbose):
def __init__(self, limit):
_Verbose.__init__(self)
self.mon = RLock()
--- 542,551 ---- *************** *** 605,616 **** def run(self): while self.count > 0: item = self.queue.get() print item self.count = self.count - 1
import time NP = 3 QL = 4 NI = 5
--- 603,612 ---- diff -C 5 Lib.orig/toaiff.py Lib/toaiff.py *** Lib.orig/toaiff.py Wed Feb 28 23:27:19 2001 --- Lib/toaiff.py Mon Aug 6 21:31:07 2001
*** 84,94 ****
fname = filename
try:
ftype = sndhdr.whathdr(fname)
if ftype:
ftype = ftype[0] # All we're interested in
! except IOError:
if type(msg) == type(()) and len(msg) == 2 and
type(msg[0]) == type(0) and type(msg[1]) == type(''):
msg = msg[1]
if type(msg) != type(''):
msg = msg
--- 84,94 ----
fname = filename
try:
ftype = sndhdr.whathdr(fname)
if ftype:
ftype = ftype[0] # All we're interested in
! except IOError, msg:
if type(msg) == type(()) and len(msg) == 2 and
type(msg[0]) == type(0) and type(msg[1]) == type(''):
msg = msg[1]
if type(msg) != type(''):
msg = msg
diff -C 5 Lib.orig/token.py Lib/token.py
*** Lib.orig/token.py Fri Feb 9 19:20:16 2001
--- Lib/token.py Mon Aug 6 21:31:28 2001
*** 80,90 **** return x == ENDMARKER
def main(): import re
import string import sys args = sys.argv[1:] inFileName = args and args[0] or "Include/token.h" outFileName = "Lib/token.py" if len(args) > 1:
--- 80,89 ---- diff -C 5 Lib.orig/urllib2.py Lib/urllib2.py *** Lib.orig/urllib2.py Sat Jul 7 18:55:28 2001 --- Lib/urllib2.py Mon Aug 6 21:36:33 2001
*** 86,96 ****
ftp errors aren't handled cleanly
gopher can return a socket.error
check digest against correct (i.e. non-apache) implementation
import socket
- import UserDict import httplib import re import base64 import types import urlparse --- 86,95 ----
*** 435,445 **** newurl = headers['location'] elif headers.has_key('uri'): newurl = headers['uri'] else: return ! nil = fp.read() fp.close()
newurl = urlparse.urljoin(req.get_full_url(), newurl)
# XXX Probably want to forget about the state of the current
--- 434,444 ---- newurl = headers['location'] elif headers.has_key('uri'): newurl = headers['uri'] else: return ! _ = fp.read() fp.close()
newurl = urlparse.urljoin(req.get_full_url(), newurl)
# XXX Probably want to forget about the state of the current
*** 449,459 ****
new.error_302_dict = {}
if hasattr(req, 'error_302_dict'):
if len(req.error_302_dict)>10 or
req.error_302_dict.has_key(newurl):
raise HTTPError(req.get_full_url(), code,
! self.inf_msg + msg, headers)
new.error_302_dict.update(req.error_302_dict)
new.error_302_dict[newurl] = newurl
return self.parent.open(new)
http_error_301 = http_error_302
--- 448,458 ----
new.error_302_dict = {}
if hasattr(req, 'error_302_dict'):
if len(req.error_302_dict)>10 or
req.error_302_dict.has_key(newurl):
raise HTTPError(req.get_full_url(), code,
! self.inf_msg + msg, headers, None)
new.error_302_dict.update(req.error_302_dict)
new.error_302_dict[newurl] = newurl
return self.parent.open(new)
http_error_301 = http_error_302
*** 658,668 ****
class AbstractDigestAuthHandler:
def __init__(self, passwd=None):
if passwd is None:
! passwd = HTTPPassowrdMgr() self.passwd = passwd self.add_password = self.passwd.add_password self.__current_realm = None
def http_error_auth_reqed(self, authreq, host, req, headers):
--- 657,667 ----
class AbstractDigestAuthHandler:
def __init__(self, passwd=None):
if passwd is None:
! passwd = HTTPPasswordMgr() self.passwd = passwd self.add_password = self.passwd.add_password self.__current_realm = None
def http_error_auth_reqed(self, authreq, host, req, headers):
diff -C 5 Lib.orig/urlparse.py Lib/urlparse.py *** Lib.orig/urlparse.py Wed Feb 28 23:27:19 2001 --- Lib/urlparse.py Mon Aug 6 21:37:47 2001
*** 53,63 **** cached = _parse_cache.get(key, None) if cached: return cached if len(_parse_cache) >= MAX_CACHE_SIZE: # avoid runaway growth clear_cache() ! netloc = path = params = query = fragment = '' i = url.find(':') if i > 0: if url[:i] == 'http': # optimize the common case scheme = url[:i].lower() url = url[i+1:] --- 53,63 ---- cached = _parse_cache.get(key, None) if cached: return cached if len(_parse_cache) >= MAX_CACHE_SIZE: # avoid runaway growth clear_cache() ! netloc = params = query = fragment = '' i = url.find(':') if i > 0: if url[:i] == 'http': # optimize the common case scheme = url[:i].lower() url = url[i+1:] diff -C 5 Lib.orig/warnings.py Lib/warnings.py *** Lib.orig/warnings.py Wed Feb 28 23:27:19 2001 --- Lib/warnings.py Mon Aug 6 21:38:04 2001
*** 223,233 **** for item in filters: print item hello = "hello world" warn(hello); warn(hello); warn(hello); warn(hello) warn(hello, UserWarning) warn(hello, DeprecationWarning) ! for i in range(3): warn(hello) filterwarnings("error", "", Warning, "", 0) try: warn(hello) except Exception, msg: --- 223,233 ---- for item in filters: print item hello = "hello world" warn(hello); warn(hello); warn(hello); warn(hello) warn(hello, UserWarning) warn(hello, DeprecationWarning) ! for _ in range(3): warn(hello) filterwarnings("error", "", Warning, "", 0) try: warn(hello) except Exception, msg: diff -C 5 Lib.orig/webbrowser.py Lib/webbrowser.py *** Lib.orig/webbrowser.py Thu Apr 12 18:07:27 2001 --- Lib/webbrowser.py Mon Aug 6 21:39:15 2001
*** 72,82 **** controller = copy.copy(controller) controller.name = browser controller.basename = os.path.basename(browser) register(browser, None, controller) return [None, controller] ! ret
Everything after this point initializes _browsers and _tryorder,
then disappears. Some class definitions and instances remain
live through these globals, but only the minimum set needed to
--- 72,82 ---- controller = copy.copy(controller) controller.name = browser controller.basename = os.path.basename(browser) register(browser, None, controller) return [None, controller] ! return [None, None]
Everything after this point initializes _browsers and _tryorder,
then disappears. Some class definitions and instances remain
live through these globals, but only the minimum set needed to
diff -C 5 Lib.orig/xdrlib.py Lib/xdrlib.py *** Lib.orig/xdrlib.py Wed Feb 28 23:27:19 2001 --- Lib/xdrlib.py Mon Aug 6 21:40:21 2001
*** 212,222 **** list.append(item) return list
def unpack_farray(self, n, unpack_item):
list = []
! for i in range(n): list.append(unpack_item()) return list
def unpack_array(self, unpack_item):
n = self.unpack_uint()
--- 212,222 ---- list.append(item) return list
def unpack_farray(self, n, unpack_item):
list = []
! for _ in range(n): list.append(unpack_item()) return list
def unpack_array(self, unpack_item):
n = self.unpack_uint()
--------------1899DB72A2CEC0DFFD96771A--
- Previous message: [Python-Dev] optimizing non-local object access
- Next message: [Python-Dev] 2.2a1 patch from PyChecker
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]