Remove uses of the string and types modules:

x in string.whitespace => x.isspace()
type(x) in types.StringTypes => isinstance(x, basestring)
isinstance(x, types.StringTypes) => isinstance(x, basestring)
type(x) is types.StringType => isinstance(x, str)
type(x) == types.StringType => isinstance(x, str)
string.split(x, ...) => x.split(...)
string.join(x, y) => y.join(x)
string.zfill(x, ...) => x.zfill(...)
string.count(x, ...) => x.count(...)
hasattr(types, "UnicodeType") => try: unicode except NameError:
type(x) != types.TupleTuple => not isinstance(x, tuple)
isinstance(x, types.TupleType) => isinstance(x, tuple)
type(x) is types.IntType => isinstance(x, int)

Do not mention the string module in the rlcompleter docstring.

This partially applies SF patch http://www.python.org/sf/562373
(with basestring instead of string). (It excludes the changes to
unittest.py and does not change the os.stat stuff.)
This commit is contained in:
Walter Dörwald 2002-06-03 15:58:32 +00:00
parent a401ae4010
commit 65230a2de7
15 changed files with 44 additions and 72 deletions

View File

@ -83,7 +83,7 @@ ConfigParser -- responsible for for parsing a list of
write the configuration state in .ini format write the configuration state in .ini format
""" """
import string, types import types
import re import re
__all__ = ["NoSectionError","DuplicateSectionError","NoOptionError", __all__ = ["NoSectionError","DuplicateSectionError","NoOptionError",
@ -223,7 +223,7 @@ class ConfigParser:
configuration files in the list will be read. A single configuration files in the list will be read. A single
filename may also be given. filename may also be given.
""" """
if type(filenames) in types.StringTypes: if isinstance(filenames, basestring):
filenames = [filenames] filenames = [filenames]
for filename in filenames: for filename in filenames:
try: try:
@ -454,7 +454,7 @@ class ConfigParser:
# ';' is a comment delimiter only if it follows # ';' is a comment delimiter only if it follows
# a spacing character # a spacing character
pos = optval.find(';') pos = optval.find(';')
if pos and optval[pos-1] in string.whitespace: if pos and optval[pos-1].isspace():
optval = optval[:pos] optval = optval[:pos]
optval = optval.strip() optval = optval.strip()
# allow empty values # allow empty values

View File

@ -28,7 +28,6 @@ Notes:
bytes that occupy space in the buffer. bytes that occupy space in the buffer.
- There's a simple test set (see end of this file). - There's a simple test set (see end of this file).
""" """
import types
try: try:
from errno import EINVAL from errno import EINVAL
except ImportError: except ImportError:
@ -50,7 +49,7 @@ class StringIO:
""" """
def __init__(self, buf = ''): def __init__(self, buf = ''):
# Force self.buf to be a string or unicode # Force self.buf to be a string or unicode
if not isinstance(buf, types.StringTypes): if not isinstance(buf, basestring):
buf = str(buf) buf = str(buf)
self.buf = buf self.buf = buf
self.len = len(buf) self.len = len(buf)
@ -151,7 +150,7 @@ class StringIO:
raise ValueError, "I/O operation on closed file" raise ValueError, "I/O operation on closed file"
if not s: return if not s: return
# Force s to be a string or unicode # Force s to be a string or unicode
if not isinstance(s, types.StringTypes): if not isinstance(s, basestring):
s = str(s) s = str(s)
if self.pos > self.len: if self.pos > self.len:
self.buflist.append('\0'*(self.pos - self.len)) self.buflist.append('\0'*(self.pos - self.len))

View File

@ -18,9 +18,7 @@ available mechanisms for setting the properties which formatter objects
manage and inserting data into the output. manage and inserting data into the output.
""" """
import string
import sys import sys
from types import StringType
AS_IS = None AS_IS = None
@ -119,7 +117,7 @@ class AbstractFormatter:
self.writer.send_line_break() self.writer.send_line_break()
if not self.para_end: if not self.para_end:
self.writer.send_paragraph((blankline and 1) or 0) self.writer.send_paragraph((blankline and 1) or 0)
if type(format) is StringType: if isinstance(format, str):
self.writer.send_label_data(self.format_counter(format, counter)) self.writer.send_label_data(self.format_counter(format, counter))
else: else:
self.writer.send_label_data(format) self.writer.send_label_data(format)
@ -176,16 +174,13 @@ class AbstractFormatter:
return label.upper() return label.upper()
return label return label
def add_flowing_data(self, data, def add_flowing_data(self, data):
# These are only here to load them into locals:
whitespace = string.whitespace,
join = string.join, split = string.split):
if not data: return if not data: return
# The following looks a bit convoluted but is a great improvement over # The following looks a bit convoluted but is a great improvement over
# data = regsub.gsub('[' + string.whitespace + ']+', ' ', data) # data = regsub.gsub('[' + string.whitespace + ']+', ' ', data)
prespace = data[:1] in whitespace prespace = data[:1].isspace()
postspace = data[-1:] in whitespace postspace = data[-1:].isspace()
data = join(split(data)) data = " ".join(data.split())
if self.nospace and not data: if self.nospace and not data:
return return
elif prespace or self.softspace: elif prespace or self.softspace:
@ -411,7 +406,7 @@ class DumbWriter(NullWriter):
def send_flowing_data(self, data): def send_flowing_data(self, data):
if not data: return if not data: return
atbreak = self.atbreak or data[0] in string.whitespace atbreak = self.atbreak or data[0].isspace()
col = self.col col = self.col
maxcol = self.maxcol maxcol = self.maxcol
write = self.file.write write = self.file.write
@ -427,7 +422,7 @@ class DumbWriter(NullWriter):
col = col + len(word) col = col + len(word)
atbreak = 1 atbreak = 1
self.col = col self.col = col
self.atbreak = data[-1] in string.whitespace self.atbreak = data[-1].isspace()
def test(file = None): def test(file = None):

View File

@ -3,8 +3,6 @@
Implements the HMAC algorithm as described by RFC 2104. Implements the HMAC algorithm as described by RFC 2104.
""" """
import string
def _strxor(s1, s2): def _strxor(s1, s2):
"""Utility method. XOR the two strings s1 and s2 (must have same length). """Utility method. XOR the two strings s1 and s2 (must have same length).
""" """
@ -82,7 +80,7 @@ class HMAC:
def hexdigest(self): def hexdigest(self):
"""Like digest(), but returns a string of hexadecimal digits instead. """Like digest(), but returns a string of hexadecimal digits instead.
""" """
return "".join([string.zfill(hex(ord(x))[2:], 2) return "".join([hex(ord(x))[2:].zfill(2)
for x in tuple(self.digest())]) for x in tuple(self.digest())])
def new(key, msg = None, digestmod = None): def new(key, msg = None, digestmod = None):

View File

@ -1,7 +1,6 @@
"""Shared support for scanning document type declarations in HTML and XHTML.""" """Shared support for scanning document type declarations in HTML and XHTML."""
import re import re
import string
_declname_match = re.compile(r'[a-zA-Z][-_.a-zA-Z0-9]*\s*').match _declname_match = re.compile(r'[a-zA-Z][-_.a-zA-Z0-9]*\s*').match
_declstringlit_match = re.compile(r'(\'[^\']*\'|"[^"]*")\s*').match _declstringlit_match = re.compile(r'(\'[^\']*\'|"[^"]*")\s*').match
@ -151,7 +150,7 @@ class ParserBase:
j = j + 1 j = j + 1
elif c == "]": elif c == "]":
j = j + 1 j = j + 1
while j < n and rawdata[j] in string.whitespace: while j < n and rawdata[j].isspace():
j = j + 1 j = j + 1
if j < n: if j < n:
if rawdata[j] == ">": if rawdata[j] == ">":
@ -160,7 +159,7 @@ class ParserBase:
self.error("unexpected char after internal subset") self.error("unexpected char after internal subset")
else: else:
return -1 return -1
elif c in string.whitespace: elif c.isspace():
j = j + 1 j = j + 1
else: else:
self.updatepos(declstartpos, j) self.updatepos(declstartpos, j)
@ -203,7 +202,7 @@ class ParserBase:
j = rawdata.find(")", j) + 1 j = rawdata.find(")", j) + 1
else: else:
return -1 return -1
while rawdata[j:j+1] in string.whitespace: while rawdata[j:j+1].isspace():
j = j + 1 j = j + 1
if not rawdata[j:]: if not rawdata[j:]:
# end of buffer, incomplete # end of buffer, incomplete
@ -268,7 +267,7 @@ class ParserBase:
c = rawdata[j:j+1] c = rawdata[j:j+1]
if not c: if not c:
return -1 return -1
if c in string.whitespace: if c.isspace():
j = j + 1 j = j + 1
else: else:
break break

View File

@ -31,7 +31,6 @@ are strings, not numbers, since they are rarely used for calculations.
# Imports # Imports
import re import re
import socket import socket
import types
__all__ = ["NNTP","NNTPReplyError","NNTPTemporaryError", __all__ = ["NNTP","NNTPReplyError","NNTPTemporaryError",
"NNTPPermanentError","NNTPProtocolError","NNTPDataError", "NNTPPermanentError","NNTPProtocolError","NNTPDataError",
@ -218,7 +217,7 @@ class NNTP:
openedFile = None openedFile = None
try: try:
# If a string was passed then open a file with that name # If a string was passed then open a file with that name
if isinstance(file, types.StringType): if isinstance(file, str):
openedFile = file = open(file, "w") openedFile = file = open(file, "w")
resp = self.getresp() resp = self.getresp()

View File

@ -8,7 +8,6 @@ and popen3(cmd) which return two or three pipes to the spawned command.
import os import os
import sys import sys
import types
__all__ = ["popen2", "popen3", "popen4"] __all__ = ["popen2", "popen3", "popen4"]
@ -57,7 +56,7 @@ class Popen3:
_active.append(self) _active.append(self)
def _run_child(self, cmd): def _run_child(self, cmd):
if isinstance(cmd, types.StringTypes): if isinstance(cmd, basestring):
cmd = ['/bin/sh', '-c', cmd] cmd = ['/bin/sh', '-c', cmd]
for i in range(3, MAXFD): for i in range(3, MAXFD):
try: try:

View File

@ -208,12 +208,10 @@ def readmodule_ex(module, path=[], inpackage=0):
f.close() f.close()
# To avoid having to stop the regexp at each newline, instead # To avoid having to stop the regexp at each newline, instead
# when we need a line number we simply string.count the number of # when we need a line number we simply count the number of
# newlines in the string since the last time we did this; i.e., # newlines in the string since the last time we did this; i.e.,
# lineno = lineno + \ # lineno += src.count('\n', last_lineno_pos, here)
# string.count(src, '\n', last_lineno_pos, here)
# last_lineno_pos = here # last_lineno_pos = here
countnl = string.count
lineno, last_lineno_pos = 1, 0 lineno, last_lineno_pos = 1, 0
i = 0 i = 0
while 1: while 1:
@ -226,9 +224,7 @@ def readmodule_ex(module, path=[], inpackage=0):
# found a method definition or function # found a method definition or function
thisindent = _indent(m.group("MethodIndent")) thisindent = _indent(m.group("MethodIndent"))
meth_name = m.group("MethodName") meth_name = m.group("MethodName")
lineno = lineno + \ lineno += src.count('\n', last_lineno_pos, start)
countnl(src, '\n',
last_lineno_pos, start)
last_lineno_pos = start last_lineno_pos = start
# close all classes indented at least as much # close all classes indented at least as much
while classstack and \ while classstack and \
@ -254,8 +250,7 @@ def readmodule_ex(module, path=[], inpackage=0):
while classstack and \ while classstack and \
classstack[-1][1] >= thisindent: classstack[-1][1] >= thisindent:
del classstack[-1] del classstack[-1]
lineno = lineno + \ lineno += src.count('\n', last_lineno_pos, start)
countnl(src, '\n', last_lineno_pos, start)
last_lineno_pos = start last_lineno_pos = start
class_name = m.group("ClassName") class_name = m.group("ClassName")
inherit = m.group("ClassSupers") inherit = m.group("ClassSupers")

View File

@ -5,9 +5,9 @@ completes keywords, built-ins and globals in a selectable namespace (which
defaults to __main__); when completing NAME.NAME..., it evaluates (!) the defaults to __main__); when completing NAME.NAME..., it evaluates (!) the
expression up to the last dot and completes its attributes. expression up to the last dot and completes its attributes.
It's very cool to do "import string" type "string.", hit the It's very cool to do "import sys" type "sys.", hit the
completion key (twice), and see the list of names defined by the completion key (twice), and see the list of names defined by the
string module! sys module!
Tip: to use the tab key as the completion key, call Tip: to use the tab key as the completion key, call

View File

@ -44,7 +44,6 @@ Example:
import socket import socket
import re import re
import rfc822 import rfc822
import types
import base64 import base64
import hmac import hmac
@ -651,7 +650,7 @@ class SMTP:
self.rset() self.rset()
raise SMTPSenderRefused(code, resp, from_addr) raise SMTPSenderRefused(code, resp, from_addr)
senderrs={} senderrs={}
if isinstance(to_addrs, types.StringTypes): if isinstance(to_addrs, basestring):
to_addrs = [to_addrs] to_addrs = [to_addrs]
for each in to_addrs: for each in to_addrs:
(code,resp)=self.rcpt(each, rcpt_options) (code,resp)=self.rcpt(each, rcpt_options)

View File

@ -190,10 +190,6 @@ def rfind(s, *args):
_float = float _float = float
_int = int _int = int
_long = long _long = long
try:
_StringTypes = (str, unicode)
except NameError:
_StringTypes = (str,)
# Convert string to float # Convert string to float
def atof(s): def atof(s):
@ -279,7 +275,7 @@ def zfill(x, width):
of the specified width. The string x is never truncated. of the specified width. The string x is never truncated.
""" """
if not isinstance(x, _StringTypes): if not isinstance(x, basestring):
x = repr(x) x = repr(x)
return x.zfill(width) return x.zfill(width)

View File

@ -27,7 +27,6 @@ import socket
import os import os
import time import time
import sys import sys
import types
__all__ = ["urlopen", "URLopener", "FancyURLopener", "urlretrieve", __all__ = ["urlopen", "URLopener", "FancyURLopener", "urlretrieve",
"urlcleanup", "quote", "quote_plus", "unquote", "unquote_plus", "urlcleanup", "quote", "quote_plus", "unquote", "unquote_plus",
@ -254,7 +253,7 @@ class URLopener:
"""Use HTTP protocol.""" """Use HTTP protocol."""
import httplib import httplib
user_passwd = None user_passwd = None
if type(url) is types.StringType: if isinstance(url, str):
host, selector = splithost(url) host, selector = splithost(url)
if host: if host:
user_passwd, host = splituser(host) user_passwd, host = splituser(host)
@ -332,7 +331,7 @@ class URLopener:
"""Use HTTPS protocol.""" """Use HTTPS protocol."""
import httplib import httplib
user_passwd = None user_passwd = None
if type(url) is types.StringType: if isinstance(url, str):
host, selector = splithost(url) host, selector = splithost(url)
if host: if host:
user_passwd, host = splituser(host) user_passwd, host = splituser(host)
@ -906,12 +905,14 @@ def basejoin(base, url):
# unquote('abc%20def') -> 'abc def' # unquote('abc%20def') -> 'abc def'
# quote('abc def') -> 'abc%20def') # quote('abc def') -> 'abc%20def')
if hasattr(types, "UnicodeType"): try:
def _is_unicode(x): unicode
return isinstance(x, unicode) except NameError:
else:
def _is_unicode(x): def _is_unicode(x):
return 0 return 0
else:
def _is_unicode(x):
return isinstance(x, unicode)
def toBytes(url): def toBytes(url):
"""toBytes(u"URL") --> 'URL'.""" """toBytes(u"URL") --> 'URL'."""
@ -1173,7 +1174,7 @@ def urlencode(query,doseq=0):
try: try:
# non-sequence items should not work with len() # non-sequence items should not work with len()
# non-empty strings will fail this # non-empty strings will fail this
if len(query) and type(query[0]) != types.TupleType: if len(query) and not isinstance(query[0], tuple):
raise TypeError raise TypeError
# zero-length sequences of all types will get here and succeed, # zero-length sequences of all types will get here and succeed,
# but that's a minor nit - since the original implementation # but that's a minor nit - since the original implementation
@ -1193,7 +1194,7 @@ def urlencode(query,doseq=0):
else: else:
for k, v in query: for k, v in query:
k = quote_plus(str(k)) k = quote_plus(str(k))
if type(v) == types.StringType: if isinstance(v, str):
v = quote_plus(v) v = quote_plus(v)
l.append(k + '=' + v) l.append(k + '=' + v)
elif _is_unicode(v): elif _is_unicode(v):

View File

@ -92,7 +92,6 @@ import httplib
import inspect import inspect
import re import re
import base64 import base64
import types
import urlparse import urlparse
import md5 import md5
import mimetypes import mimetypes
@ -303,7 +302,7 @@ class OpenerDirector:
def open(self, fullurl, data=None): def open(self, fullurl, data=None):
# accept a URL or a Request object # accept a URL or a Request object
if isinstance(fullurl, types.StringTypes): if isinstance(fullurl, basestring):
req = Request(fullurl, data) req = Request(fullurl, data)
else: else:
req = fullurl req = fullurl
@ -516,7 +515,7 @@ class HTTPPasswordMgr:
def add_password(self, realm, uri, user, passwd): def add_password(self, realm, uri, user, passwd):
# uri could be a single URI or a sequence # uri could be a single URI or a sequence
if isinstance(uri, types.StringTypes): if isinstance(uri, basestring):
uri = [uri] uri = [uri]
uri = tuple(map(self.reduce_uri, uri)) uri = tuple(map(self.reduce_uri, uri))
if not realm in self.passwd: if not realm in self.passwd:
@ -1084,7 +1083,7 @@ if __name__ == "__main__":
install_opener(build_opener(cfh, GopherHandler)) install_opener(build_opener(cfh, GopherHandler))
for url in urls: for url in urls:
if isinstance(url, types.TupleType): if isinstance(url, tuple):
url, req = url url, req = url
else: else:
req = None req = None

View File

@ -125,11 +125,11 @@ def filterwarnings(action, message="", category=Warning, module="", lineno=0,
Use assertions to check that all arguments have the right type.""" Use assertions to check that all arguments have the right type."""
assert action in ("error", "ignore", "always", "default", "module", assert action in ("error", "ignore", "always", "default", "module",
"once"), "invalid action: %s" % `action` "once"), "invalid action: %s" % `action`
assert isinstance(message, types.StringType), "message must be a string" assert isinstance(message, str), "message must be a string"
assert isinstance(category, types.ClassType), "category must be a class" assert isinstance(category, types.ClassType), "category must be a class"
assert issubclass(category, Warning), "category must be a Warning subclass" assert issubclass(category, Warning), "category must be a Warning subclass"
assert type(module) is types.StringType, "module must be a string" assert isinstance(module, str), "module must be a string"
assert type(lineno) is types.IntType and lineno >= 0, \ assert isinstance(lineno, int) and lineno >= 0, \
"lineno must be an int >= 0" "lineno must be an int >= 0"
item = (action, re.compile(message, re.I), category, item = (action, re.compile(message, re.I), category,
re.compile(module), lineno) re.compile(module), lineno)

View File

@ -65,13 +65,6 @@ _FH_UNCOMPRESSED_SIZE = 9
_FH_FILENAME_LENGTH = 10 _FH_FILENAME_LENGTH = 10
_FH_EXTRA_FIELD_LENGTH = 11 _FH_EXTRA_FIELD_LENGTH = 11
# Used to compare file passed to ZipFile
import types
_STRING_TYPES = (types.StringType,)
if hasattr(types, "UnicodeType"):
_STRING_TYPES = _STRING_TYPES + (types.UnicodeType,)
def is_zipfile(filename): def is_zipfile(filename):
"""Quickly see if file is a ZIP file by checking the magic number. """Quickly see if file is a ZIP file by checking the magic number.
@ -175,7 +168,7 @@ class ZipFile:
self.mode = key = mode[0] self.mode = key = mode[0]
# Check if we were passed a file-like object # Check if we were passed a file-like object
if type(file) in _STRING_TYPES: if isinstance(file, basestring):
self._filePassed = 0 self._filePassed = 0
self.filename = file self.filename = file
modeDict = {'r' : 'rb', 'w': 'wb', 'a' : 'r+b'} modeDict = {'r' : 'rb', 'w': 'wb', 'a' : 'r+b'}