Patch# 1258 by Christian Heimes: kill basestring.

I like this because it makes the code shorter! :-)
This commit is contained in:
Guido van Rossum 2007-10-16 18:12:55 +00:00
parent 60d241f135
commit 3172c5d263
77 changed files with 171 additions and 217 deletions

View File

@ -48,7 +48,6 @@ typedef struct {
*/ */
} PyStringObject; } PyStringObject;
PyAPI_DATA(PyTypeObject) PyBaseString_Type;
PyAPI_DATA(PyTypeObject) PyString_Type; PyAPI_DATA(PyTypeObject) PyString_Type;
#define PyString_Check(op) \ #define PyString_Check(op) \

View File

@ -271,7 +271,7 @@ class RawConfigParser:
Return list of successfully read files. Return list of successfully read files.
""" """
if isinstance(filenames, basestring): if isinstance(filenames, str):
filenames = [filenames] filenames = [filenames]
read_ok = [] read_ok = []
for filename in filenames: for filename in filenames:
@ -652,7 +652,7 @@ class SafeConfigParser(ConfigParser):
def set(self, section, option, value): def set(self, section, option, value):
"""Set an option. Extend ConfigParser.set: check for string values.""" """Set an option. Extend ConfigParser.set: check for string values."""
if not isinstance(value, basestring): if not isinstance(value, str):
raise TypeError("option values must be strings") raise TypeError("option values must be strings")
# check for bad percent signs: # check for bad percent signs:
# first, replace all "good" interpolations # first, replace all "good" interpolations

View File

@ -11,7 +11,7 @@ __all__ = ["UserString","MutableString"]
class UserString: class UserString:
def __init__(self, seq): def __init__(self, seq):
if isinstance(seq, basestring): if isinstance(seq, str):
self.data = seq self.data = seq
elif isinstance(seq, UserString): elif isinstance(seq, UserString):
self.data = seq.data[:] self.data = seq.data[:]
@ -66,12 +66,12 @@ class UserString:
def __add__(self, other): def __add__(self, other):
if isinstance(other, UserString): if isinstance(other, UserString):
return self.__class__(self.data + other.data) return self.__class__(self.data + other.data)
elif isinstance(other, basestring): elif isinstance(other, str):
return self.__class__(self.data + other) return self.__class__(self.data + other)
else: else:
return self.__class__(self.data + str(other)) return self.__class__(self.data + str(other))
def __radd__(self, other): def __radd__(self, other):
if isinstance(other, basestring): if isinstance(other, str):
return self.__class__(other + self.data) return self.__class__(other + self.data)
else: else:
return self.__class__(str(other) + self.data) return self.__class__(str(other) + self.data)
@ -184,7 +184,7 @@ class MutableString(UserString):
if isinstance(index, slice): if isinstance(index, slice):
if isinstance(sub, UserString): if isinstance(sub, UserString):
sub = sub.data sub = sub.data
elif not isinstance(sub, basestring): elif not isinstance(sub, str):
sub = str(sub) sub = str(sub)
start, stop, step = index.indices(len(self.data)) start, stop, step = index.indices(len(self.data))
if step == -1: if step == -1:
@ -221,7 +221,7 @@ class MutableString(UserString):
def __iadd__(self, other): def __iadd__(self, other):
if isinstance(other, UserString): if isinstance(other, UserString):
self.data += other.data self.data += other.data
elif isinstance(other, basestring): elif isinstance(other, str):
self.data += other self.data += other
else: else:
self.data += str(other) self.data += str(other)

View File

@ -490,7 +490,8 @@ class Sequence(metaclass=ABCMeta):
return sum(1 for v in self if v == value) return sum(1 for v in self if v == value)
Sequence.register(tuple) Sequence.register(tuple)
Sequence.register(basestring) Sequence.register(str)
Sequence.register(str8)
Sequence.register(memoryview) Sequence.register(memoryview)

View File

@ -169,7 +169,7 @@ class _Rlecoderengine:
class BinHex: class BinHex:
def __init__(self, name_finfo_dlen_rlen, ofp): def __init__(self, name_finfo_dlen_rlen, ofp):
name, finfo, dlen, rlen = name_finfo_dlen_rlen name, finfo, dlen, rlen = name_finfo_dlen_rlen
if isinstance(ofp, basestring): if isinstance(ofp, str):
ofname = ofp ofname = ofp
ofp = io.open(ofname, 'wb') ofp = io.open(ofname, 'wb')
if os.name == 'mac': if os.name == 'mac':
@ -371,7 +371,7 @@ class _Rledecoderengine:
class HexBin: class HexBin:
def __init__(self, ifp): def __init__(self, ifp):
if isinstance(ifp, basestring): if isinstance(ifp, str):
ifp = io.open(ifp, 'rb') ifp = io.open(ifp, 'rb')
# #
# Find initial colon. # Find initial colon.

View File

@ -153,7 +153,7 @@ class Profile(_lsprof.Profiler):
# ____________________________________________________________ # ____________________________________________________________
def label(code): def label(code):
if isinstance(code, basestring): if isinstance(code, str):
return ('~', 0, code) # built-in functions ('~' sorts at the end) return ('~', 0, code) # built-in functions ('~' sorts at the end)
else: else:
return (code.co_filename, code.co_firstlineno, code.co_name) return (code.co_filename, code.co_firstlineno, code.co_name)

View File

@ -356,7 +356,7 @@ class Cmd:
return return
nonstrings = [i for i in range(len(list)) nonstrings = [i for i in range(len(list))
if not isinstance(list[i], basestring)] if not isinstance(list[i], str)]
if nonstrings: if nonstrings:
raise TypeError("list[i] not a string for i in %s" raise TypeError("list[i] not a string for i in %s"
% ", ".join(map(str, nonstrings))) % ", ".join(map(str, nonstrings)))

View File

@ -367,7 +367,7 @@ def split_header_words(header_values):
[[('Basic', None), ('realm', '"foobar"')]] [[('Basic', None), ('realm', '"foobar"')]]
""" """
assert not isinstance(header_values, basestring) assert not isinstance(header_values, str)
result = [] result = []
for text in header_values: for text in header_values:
orig_text = text orig_text = text

View File

@ -114,7 +114,7 @@ def _slotnames(cls):
if "__slots__" in c.__dict__: if "__slots__" in c.__dict__:
slots = c.__dict__['__slots__'] slots = c.__dict__['__slots__']
# if class has a single slot, it can be given as a string # if class has a single slot, it can be given as a string
if isinstance(slots, basestring): if isinstance(slots, str):
slots = (slots,) slots = (slots,)
for name in slots: for name in slots:
# special descriptors # special descriptors

View File

@ -588,7 +588,7 @@ class Decimal(object):
# From a string # From a string
# REs insist on real strings, so we can too. # REs insist on real strings, so we can too.
if isinstance(value, basestring): if isinstance(value, str):
if _isinfinity(value): if _isinfinity(value):
self._exp = 'F' self._exp = 'F'
self._int = (0,) self._int = (0,)

View File

@ -154,7 +154,7 @@ class CCompiler:
self.set_executable(key, value) self.set_executable(key, value)
def set_executable(self, key, value): def set_executable(self, key, value):
if isinstance(value, basestring): if isinstance(value, str):
setattr(self, key, split_quoted(value)) setattr(self, key, split_quoted(value))
else: else:
setattr(self, key, value) setattr(self, key, value)
@ -175,8 +175,8 @@ class CCompiler:
for defn in definitions: for defn in definitions:
if not (isinstance(defn, tuple) and if not (isinstance(defn, tuple) and
(len(defn) in (1, 2) and (len(defn) in (1, 2) and
(isinstance (defn[1], basestring) or defn[1] is None)) and (isinstance (defn[1], str) or defn[1] is None)) and
isinstance (defn[0], basestring)): isinstance (defn[0], str)):
raise TypeError(("invalid macro definition '%s': " % defn) + \ raise TypeError(("invalid macro definition '%s': " % defn) + \
"must be tuple (string,), (string, string), or " + \ "must be tuple (string,), (string, string), or " + \
"(string, None)") "(string, None)")
@ -318,7 +318,7 @@ class CCompiler:
""" """
if outdir is None: if outdir is None:
outdir = self.output_dir outdir = self.output_dir
elif not isinstance(outdir, basestring): elif not isinstance(outdir, str):
raise TypeError("'output_dir' must be a string or None") raise TypeError("'output_dir' must be a string or None")
if macros is None: if macros is None:
@ -415,7 +415,7 @@ class CCompiler:
""" """
if output_dir is None: if output_dir is None:
output_dir = self.output_dir output_dir = self.output_dir
elif not isinstance(output_dir, basestring): elif not isinstance(output_dir, str):
raise TypeError("'output_dir' must be a string or None") raise TypeError("'output_dir' must be a string or None")
if macros is None: if macros is None:
@ -494,7 +494,7 @@ class CCompiler:
if output_dir is None: if output_dir is None:
output_dir = self.output_dir output_dir = self.output_dir
elif not isinstance(output_dir, basestring): elif not isinstance(output_dir, str):
raise TypeError("'output_dir' must be a string or None") raise TypeError("'output_dir' must be a string or None")
return (objects, output_dir) return (objects, output_dir)

View File

@ -213,7 +213,7 @@ class Command:
if val is None: if val is None:
setattr(self, option, default) setattr(self, option, default)
return default return default
elif not isinstance(val, basestring): elif not isinstance(val, str):
raise DistutilsOptionError("'%s' must be a %s (got `%s`)" raise DistutilsOptionError("'%s' must be a %s (got `%s`)"
% (option, what, val)) % (option, what, val))
return val return val
@ -233,11 +233,11 @@ class Command:
val = getattr(self, option) val = getattr(self, option)
if val is None: if val is None:
return return
elif isinstance(val, basestring): elif isinstance(val, str):
setattr(self, option, re.split(r',\s*|\s+', val)) setattr(self, option, re.split(r',\s*|\s+', val))
else: else:
if isinstance(val, list): if isinstance(val, list):
ok = all(isinstance(v, basestring) for v in val) ok = all(isinstance(v, str) for v in val)
else: else:
ok = False ok = False
if not ok: if not ok:
@ -390,7 +390,7 @@ class Command:
# Allow 'infiles' to be a single string # Allow 'infiles' to be a single string
if isinstance(infiles, basestring): if isinstance(infiles, str):
infiles = (infiles,) infiles = (infiles,)
elif not isinstance(infiles, (list, tuple)): elif not isinstance(infiles, (list, tuple)):
raise TypeError( raise TypeError(

View File

@ -86,7 +86,7 @@ class build_clib(Command):
if self.include_dirs is None: if self.include_dirs is None:
self.include_dirs = self.distribution.include_dirs or [] self.include_dirs = self.distribution.include_dirs or []
if isinstance(self.include_dirs, basestring): if isinstance(self.include_dirs, str):
self.include_dirs = self.include_dirs.split(os.pathsep) self.include_dirs = self.include_dirs.split(os.pathsep)
# XXX same as for build_ext -- what about 'self.define' and # XXX same as for build_ext -- what about 'self.define' and
@ -134,7 +134,7 @@ class build_clib(Command):
raise DistutilsSetupError( raise DistutilsSetupError(
"each element of 'libraries' must a 2-tuple") "each element of 'libraries' must a 2-tuple")
if isinstance(lib[0], basestring): if isinstance(lib[0], str):
raise DistutilsSetupError( raise DistutilsSetupError(
"first element of each tuple in 'libraries' " "first element of each tuple in 'libraries' "
"must be a string (the library name)") "must be a string (the library name)")

View File

@ -133,7 +133,7 @@ class build_ext(Command):
plat_py_include = sysconfig.get_python_inc(plat_specific=1) plat_py_include = sysconfig.get_python_inc(plat_specific=1)
if self.include_dirs is None: if self.include_dirs is None:
self.include_dirs = self.distribution.include_dirs or [] self.include_dirs = self.distribution.include_dirs or []
if isinstance(self.include_dirs, basestring): if isinstance(self.include_dirs, str):
self.include_dirs = self.include_dirs.split(os.pathsep) self.include_dirs = self.include_dirs.split(os.pathsep)
# Put the Python "system" include dir at the end, so that # Put the Python "system" include dir at the end, so that
@ -142,7 +142,7 @@ class build_ext(Command):
if plat_py_include != py_include: if plat_py_include != py_include:
self.include_dirs.append(plat_py_include) self.include_dirs.append(plat_py_include)
if isinstance(self.libraries, basestring): if isinstance(self.libraries, str):
self.libraries = [self.libraries] self.libraries = [self.libraries]
# Life is easier if we're not forever checking for None, so # Life is easier if we're not forever checking for None, so
@ -151,12 +151,12 @@ class build_ext(Command):
self.libraries = [] self.libraries = []
if self.library_dirs is None: if self.library_dirs is None:
self.library_dirs = [] self.library_dirs = []
elif isinstance(self.library_dirs, basestring): elif isinstance(self.library_dirs, str):
self.library_dirs = self.library_dirs.split(os.pathsep) self.library_dirs = self.library_dirs.split(os.pathsep)
if self.rpath is None: if self.rpath is None:
self.rpath = [] self.rpath = []
elif isinstance(self.rpath, basestring): elif isinstance(self.rpath, str):
self.rpath = self.rpath.split(os.pathsep) self.rpath = self.rpath.split(os.pathsep)
# for extensions under windows use different directories # for extensions under windows use different directories
@ -309,7 +309,7 @@ class build_ext(Command):
"each element of 'ext_modules' option must be an " "each element of 'ext_modules' option must be an "
"Extension instance or 2-tuple") "Extension instance or 2-tuple")
if not (isinstance(ext_name, basestring) and if not (isinstance(ext_name, str) and
extension_name_re.match(ext_name)): extension_name_re.match(ext_name)):
raise DistutilsSetupError( raise DistutilsSetupError(
"first element of each tuple in 'ext_modules' " "first element of each tuple in 'ext_modules' "

View File

@ -325,7 +325,7 @@ class build_py (Command):
return outputs return outputs
def build_module(self, module, module_file, package): def build_module(self, module, module_file, package):
if isinstance(package, basestring): if isinstance(package, str):
package = package.split('.') package = package.split('.')
elif not isinstance(package, (list, tuple)): elif not isinstance(package, (list, tuple)):
raise TypeError( raise TypeError(

View File

@ -69,17 +69,17 @@ class config(Command):
def finalize_options(self): def finalize_options(self):
if self.include_dirs is None: if self.include_dirs is None:
self.include_dirs = self.distribution.include_dirs or [] self.include_dirs = self.distribution.include_dirs or []
elif isinstance(self.include_dirs, basestring): elif isinstance(self.include_dirs, str):
self.include_dirs = self.include_dirs.split(os.pathsep) self.include_dirs = self.include_dirs.split(os.pathsep)
if self.libraries is None: if self.libraries is None:
self.libraries = [] self.libraries = []
elif isinstance(self.libraries, basestring): elif isinstance(self.libraries, str):
self.libraries = [self.libraries] self.libraries = [self.libraries]
if self.library_dirs is None: if self.library_dirs is None:
self.library_dirs = [] self.library_dirs = []
elif isinstance(self.library_dirs, basestring): elif isinstance(self.library_dirs, str):
self.library_dirs = self.library_dirs.split(os.pathsep) self.library_dirs = self.library_dirs.split(os.pathsep)
def run(self): def run(self):
@ -204,7 +204,7 @@ class config(Command):
self._check_compiler() self._check_compiler()
(src, out) = self._preprocess(body, headers, include_dirs, lang) (src, out) = self._preprocess(body, headers, include_dirs, lang)
if isinstance(pattern, basestring): if isinstance(pattern, str):
pattern = re.compile(pattern) pattern = re.compile(pattern)
file = open(out) file = open(out)

View File

@ -449,7 +449,7 @@ class install (Command):
self.extra_path = self.distribution.extra_path self.extra_path = self.distribution.extra_path
if self.extra_path is not None: if self.extra_path is not None:
if isinstance(self.extra_path, basestring): if isinstance(self.extra_path, str):
self.extra_path = self.extra_path.split(',') self.extra_path = self.extra_path.split(',')
if len(self.extra_path) == 1: if len(self.extra_path) == 1:

View File

@ -45,7 +45,7 @@ class install_data(Command):
def run(self): def run(self):
self.mkpath(self.install_dir) self.mkpath(self.install_dir)
for f in self.data_files: for f in self.data_files:
if isinstance(f, basestring): if isinstance(f, str):
# it's a simple file, so copy it # it's a simple file, so copy it
f = convert_path(f) f = convert_path(f)
if self.warn_dir: if self.warn_dir:

View File

@ -28,7 +28,7 @@ def mkpath (name, mode=0o777, verbose=0, dry_run=0):
global _path_created global _path_created
# Detect a common bug -- name is None # Detect a common bug -- name is None
if not isinstance(name, basestring): if not isinstance(name, str):
raise DistutilsInternalError( raise DistutilsInternalError(
"mkpath: 'name' must be a string (got %r)" % (name,)) "mkpath: 'name' must be a string (got %r)" % (name,))

View File

@ -580,13 +580,13 @@ Common commands: (see '--help-commands' for more)
keywords = self.metadata.keywords keywords = self.metadata.keywords
if keywords is not None: if keywords is not None:
if isinstance(keywords, basestring): if isinstance(keywords, str):
keywordlist = keywords.split(',') keywordlist = keywords.split(',')
self.metadata.keywords = [x.strip() for x in keywordlist] self.metadata.keywords = [x.strip() for x in keywordlist]
platforms = self.metadata.platforms platforms = self.metadata.platforms
if platforms is not None: if platforms is not None:
if isinstance(platforms, basestring): if isinstance(platforms, str):
platformlist = platforms.split(',') platformlist = platforms.split(',')
self.metadata.platforms = [x.strip() for x in platformlist] self.metadata.platforms = [x.strip() for x in platformlist]
@ -874,7 +874,7 @@ Common commands: (see '--help-commands' for more)
neg_opt = {} neg_opt = {}
try: try:
is_string = isinstance(value, basestring) is_string = isinstance(value, str)
if option in neg_opt and is_string: if option in neg_opt and is_string:
setattr(command_obj, neg_opt[option], not strtobool(value)) setattr(command_obj, neg_opt[option], not strtobool(value))
elif option in bool_opts and is_string: elif option in bool_opts and is_string:

View File

@ -102,9 +102,9 @@ class Extension:
language=None, language=None,
**kw # To catch unknown keywords **kw # To catch unknown keywords
): ):
assert isinstance(name, basestring), "'name' must be a string" assert isinstance(name, str), "'name' must be a string"
assert (isinstance(sources, list) and assert (isinstance(sources, list) and
all(isinstance(v, basestring) for v in sources)), \ all(isinstance(v, str) for v in sources)), \
"'sources' must be a list of strings" "'sources' must be a list of strings"
self.name = name self.name = name

View File

@ -154,12 +154,12 @@ class FancyGetopt:
raise ValueError("invalid option tuple: %r" % (option,)) raise ValueError("invalid option tuple: %r" % (option,))
# Type- and value-check the option names # Type- and value-check the option names
if not isinstance(long, basestring) or len(long) < 2: if not isinstance(long, str) or len(long) < 2:
raise DistutilsGetoptError(("invalid long option '%s': " raise DistutilsGetoptError(("invalid long option '%s': "
"must be a string of length >= 2") % long) "must be a string of length >= 2") % long)
if (not ((short is None) or if (not ((short is None) or
(isinstance(short, basestring) and len(short) == 1))): (isinstance(short, str) and len(short) == 1))):
raise DistutilsGetoptError("invalid short option '%s': " raise DistutilsGetoptError("invalid short option '%s': "
"must a single character or None" % short) "must a single character or None" % short)

View File

@ -301,7 +301,7 @@ def translate_pattern(pattern, anchor=1, prefix=None, is_regex=0):
or just returned as-is (assumes it's a regex object). or just returned as-is (assumes it's a regex object).
""" """
if is_regex: if is_regex:
if isinstance(pattern, basestring): if isinstance(pattern, str):
return re.compile(pattern) return re.compile(pattern)
else: else:
return pattern return pattern

View File

@ -211,7 +211,7 @@ class UnixCCompiler(CCompiler):
lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs, lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs,
libraries) libraries)
if not isinstance(output_dir, (basestring, type(None))): if not isinstance(output_dir, (str, type(None))):
raise TypeError("'output_dir' must be a string or None") raise TypeError("'output_dir' must be a string or None")
if output_dir is not None: if output_dir is not None:
output_filename = os.path.join(output_dir, output_filename) output_filename = os.path.join(output_dir, output_filename)

View File

@ -443,7 +443,7 @@ class DocTest:
Create a new DocTest containing the given examples. The Create a new DocTest containing the given examples. The
DocTest's globals are initialized with a copy of `globs`. DocTest's globals are initialized with a copy of `globs`.
""" """
assert not isinstance(examples, basestring), \ assert not isinstance(examples, str), \
"DocTest no longer accepts str; use DocTestParser instead" "DocTest no longer accepts str; use DocTestParser instead"
self.examples = examples self.examples = examples
self.docstring = docstring self.docstring = docstring
@ -875,13 +875,13 @@ class DocTestFinder:
# Look for tests in a module's __test__ dictionary. # Look for tests in a module's __test__ dictionary.
if inspect.ismodule(obj) and self._recurse: if inspect.ismodule(obj) and self._recurse:
for valname, val in getattr(obj, '__test__', {}).items(): for valname, val in getattr(obj, '__test__', {}).items():
if not isinstance(valname, basestring): if not isinstance(valname, str):
raise ValueError("DocTestFinder.find: __test__ keys " raise ValueError("DocTestFinder.find: __test__ keys "
"must be strings: %r" % "must be strings: %r" %
(type(valname),)) (type(valname),))
if not (inspect.isfunction(val) or inspect.isclass(val) or if not (inspect.isfunction(val) or inspect.isclass(val) or
inspect.ismethod(val) or inspect.ismodule(val) or inspect.ismethod(val) or inspect.ismodule(val) or
isinstance(val, basestring)): isinstance(val, str)):
raise ValueError("DocTestFinder.find: __test__ values " raise ValueError("DocTestFinder.find: __test__ values "
"must be strings, functions, methods, " "must be strings, functions, methods, "
"classes, or modules: %r" % "classes, or modules: %r" %
@ -914,7 +914,7 @@ class DocTestFinder:
""" """
# Extract the object's docstring. If it doesn't have one, # Extract the object's docstring. If it doesn't have one,
# then return None (no test for this object). # then return None (no test for this object).
if isinstance(obj, basestring): if isinstance(obj, str):
docstring = obj docstring = obj
else: else:
try: try:
@ -922,7 +922,7 @@ class DocTestFinder:
docstring = '' docstring = ''
else: else:
docstring = obj.__doc__ docstring = obj.__doc__
if not isinstance(docstring, basestring): if not isinstance(docstring, str):
docstring = str(docstring) docstring = str(docstring)
except (TypeError, AttributeError): except (TypeError, AttributeError):
docstring = '' docstring = ''

View File

@ -365,7 +365,7 @@ class FeedParser:
self._last.epilogue = epilogue[:-end] self._last.epilogue = epilogue[:-end]
else: else:
payload = self._last.get_payload() payload = self._last.get_payload()
if isinstance(payload, basestring): if isinstance(payload, str):
mo = NLCRE_eol.search(payload) mo = NLCRE_eol.search(payload)
if mo: if mo:
payload = payload[:-len(mo.group(0))] payload = payload[:-len(mo.group(0))]

View File

@ -151,7 +151,7 @@ class Generator:
payload = msg.get_payload() payload = msg.get_payload()
if payload is None: if payload is None:
return return
if not isinstance(payload, basestring): if not isinstance(payload, str):
raise TypeError('string payload expected: %s' % type(payload)) raise TypeError('string payload expected: %s' % type(payload))
if self._mangle_from_: if self._mangle_from_:
payload = fcre.sub('>From ', payload) payload = fcre.sub('>From ', payload)
@ -168,7 +168,7 @@ class Generator:
subparts = msg.get_payload() subparts = msg.get_payload()
if subparts is None: if subparts is None:
subparts = [] subparts = []
elif isinstance(subparts, basestring): elif isinstance(subparts, str):
# e.g. a non-strict parse of a message with no starting boundary. # e.g. a non-strict parse of a message with no starting boundary.
self._fp.write(subparts) self._fp.write(subparts)
return return
@ -288,7 +288,7 @@ class DecodedGenerator(Generator):
for part in msg.walk(): for part in msg.walk():
maintype = part.get_content_maintype() maintype = part.get_content_maintype()
if maintype == 'text': if maintype == 'text':
print(part.get_payload(decode=True), file=self) print(part.get_payload(decode=False), file=self)
elif maintype == 'multipart': elif maintype == 'multipart':
# Just skip this # Just skip this
pass pass

View File

@ -39,7 +39,7 @@ def body_line_iterator(msg, decode=False):
""" """
for subpart in msg.walk(): for subpart in msg.walk():
payload = subpart.get_payload(decode=decode) payload = subpart.get_payload(decode=decode)
if isinstance(payload, basestring): if isinstance(payload, str):
for line in StringIO(payload): for line in StringIO(payload):
yield line yield line

View File

@ -196,7 +196,7 @@ class FileInput:
def __init__(self, files=None, inplace=0, backup="", bufsize=0, def __init__(self, files=None, inplace=0, backup="", bufsize=0,
mode="r", openhook=None): mode="r", openhook=None):
if isinstance(files, basestring): if isinstance(files, str):
files = (files,) files = (files,)
else: else:
if files is None: if files is None:

View File

@ -313,7 +313,7 @@ def getdoc(object):
doc = object.__doc__ doc = object.__doc__
except AttributeError: except AttributeError:
return None return None
if not isinstance(doc, basestring): if not isinstance(doc, str):
return None return None
try: try:
lines = doc.expandtabs().split('\n') lines = doc.expandtabs().split('\n')

View File

@ -103,13 +103,13 @@ def open(file, mode="r", buffering=None, encoding=None, newline=None):
binary stream, a buffered binary stream, or a buffered text binary stream, a buffered binary stream, or a buffered text
stream, open for reading and/or writing. stream, open for reading and/or writing.
""" """
if not isinstance(file, (basestring, int)): if not isinstance(file, (str, int)):
raise TypeError("invalid file: %r" % file) raise TypeError("invalid file: %r" % file)
if not isinstance(mode, basestring): if not isinstance(mode, str):
raise TypeError("invalid mode: %r" % mode) raise TypeError("invalid mode: %r" % mode)
if buffering is not None and not isinstance(buffering, int): if buffering is not None and not isinstance(buffering, int):
raise TypeError("invalid buffering: %r" % buffering) raise TypeError("invalid buffering: %r" % buffering)
if encoding is not None and not isinstance(encoding, basestring): if encoding is not None and not isinstance(encoding, str):
raise TypeError("invalid encoding: %r" % encoding) raise TypeError("invalid encoding: %r" % encoding)
modes = set(mode) modes = set(mode)
if modes - set("arwb+tU") or len(mode) > len(modes): if modes - set("arwb+tU") or len(mode) > len(modes):
@ -1092,7 +1092,7 @@ class TextIOWrapper(TextIOBase):
def write(self, s: str): def write(self, s: str):
if self.closed: if self.closed:
raise ValueError("write to closed file") raise ValueError("write to closed file")
if not isinstance(s, basestring): if not isinstance(s, str):
raise TypeError("can't write %s to text stream" % raise TypeError("can't write %s to text stream" %
s.__class__.__name__) s.__class__.__name__)
haslf = "\n" in s haslf = "\n" in s
@ -1394,7 +1394,7 @@ class StringIO(TextIOWrapper):
encoding=encoding, encoding=encoding,
newline=newline) newline=newline)
if initial_value: if initial_value:
if not isinstance(initial_value, basestring): if not isinstance(initial_value, str):
initial_value = str(initial_value) initial_value = str(initial_value)
self.write(initial_value) self.write(initial_value)
self.seek(0) self.seek(0)

View File

@ -255,7 +255,7 @@ class StringVar(Variable):
def get(self): def get(self):
"""Return value of variable as string.""" """Return value of variable as string."""
value = self._tk.globalgetvar(self._name) value = self._tk.globalgetvar(self._name)
if isinstance(value, basestring): if isinstance(value, str):
return value return value
return str(value) return str(value)

View File

@ -12,6 +12,7 @@
""" """
import sys, encodings, encodings.aliases import sys, encodings, encodings.aliases
from __builtin__ import str as _builtin_str
# Try importing the _locale module. # Try importing the _locale module.
# #
@ -472,7 +473,7 @@ def setlocale(category, locale=None):
category may be given as one of the LC_* values. category may be given as one of the LC_* values.
""" """
if locale and not isinstance(locale, basestring): if locale and not isinstance(locale, _builtin_str):
# convert to string # convert to string
locale = normalize(_build_localename(locale)) locale = normalize(_build_localename(locale))
return _setlocale(category, locale) return _setlocale(category, locale)

View File

@ -281,7 +281,7 @@ class LogRecord:
msg = str(self.msg) msg = str(self.msg)
else: else:
msg = self.msg msg = self.msg
if not isinstance(msg, basestring): if not isinstance(msg, str):
try: try:
msg = str(self.msg) msg = str(self.msg)
except UnicodeError: except UnicodeError:

View File

@ -101,7 +101,7 @@ def add_data(db, table, values):
field = value[i] field = value[i]
if isinstance(field, int): if isinstance(field, int):
r.SetInteger(i+1,field) r.SetInteger(i+1,field)
elif isinstance(field, basestring): elif isinstance(field, str):
r.SetString(i+1,field) r.SetString(i+1,field)
elif field is None: elif field is None:
pass pass

View File

@ -815,9 +815,6 @@ class Option:
SUPPRESS_HELP = "SUPPRESS"+"HELP" SUPPRESS_HELP = "SUPPRESS"+"HELP"
SUPPRESS_USAGE = "SUPPRESS"+"USAGE" SUPPRESS_USAGE = "SUPPRESS"+"USAGE"
def isbasestring(x):
return isinstance(x, basestring)
class Values: class Values:
def __init__(self, defaults=None): def __init__(self, defaults=None):
@ -994,7 +991,7 @@ class OptionContainer:
"""add_option(Option) """add_option(Option)
add_option(opt_str, ..., kwarg=val, ...) add_option(opt_str, ..., kwarg=val, ...)
""" """
if isbasestring(args[0]): if isinstance(args[0], str):
option = self.option_class(*args, **kwargs) option = self.option_class(*args, **kwargs)
elif len(args) == 1 and not kwargs: elif len(args) == 1 and not kwargs:
option = args[0] option = args[0]
@ -1294,7 +1291,7 @@ class OptionParser (OptionContainer):
defaults = self.defaults.copy() defaults = self.defaults.copy()
for option in self._get_all_options(): for option in self._get_all_options():
default = defaults.get(option.dest) default = defaults.get(option.dest)
if isbasestring(default): if isinstance(default, str):
opt_str = option.get_opt_string() opt_str = option.get_opt_string()
defaults[option.dest] = option.check_value(opt_str, default) defaults[option.dest] = option.check_value(opt_str, default)
@ -1305,7 +1302,7 @@ class OptionParser (OptionContainer):
def add_option_group(self, *args, **kwargs): def add_option_group(self, *args, **kwargs):
# XXX lots of overlap with OptionContainer.add_option() # XXX lots of overlap with OptionContainer.add_option()
if isbasestring(args[0]): if isinstance(args[0], str):
group = OptionGroup(self, *args, **kwargs) group = OptionGroup(self, *args, **kwargs)
elif len(args) == 1 and not kwargs: elif len(args) == 1 and not kwargs:
group = args[0] group = args[0]

View File

@ -636,7 +636,7 @@ if not _exists("urandom"):
# Supply os.popen() # Supply os.popen()
def popen(cmd, mode="r", buffering=None): def popen(cmd, mode="r", buffering=None):
if not isinstance(cmd, basestring): if not isinstance(cmd, str):
raise TypeError("invalid cmd type (%s, expected string)" % type(cmd)) raise TypeError("invalid cmd type (%s, expected string)" % type(cmd))
if mode not in ("r", "w"): if mode not in ("r", "w"):
raise ValueError("invalid mode %r" % mode) raise ValueError("invalid mode %r" % mode)

View File

@ -307,7 +307,7 @@ class Pickler:
(t.__name__, obj)) (t.__name__, obj))
# Check for string returned by reduce(), meaning "save as global" # Check for string returned by reduce(), meaning "save as global"
if isinstance(rv, basestring): if isinstance(rv, str):
self.save_global(obj, rv) self.save_global(obj, rv)
return return

View File

@ -701,7 +701,7 @@ class StackObject(object):
) )
def __init__(self, name, obtype, doc): def __init__(self, name, obtype, doc):
assert isinstance(name, basestring) assert isinstance(name, str)
self.name = name self.name = name
assert isinstance(obtype, type) or isinstance(obtype, tuple) assert isinstance(obtype, type) or isinstance(obtype, tuple)
@ -710,7 +710,7 @@ class StackObject(object):
assert isinstance(contained, type) assert isinstance(contained, type)
self.obtype = obtype self.obtype = obtype
assert isinstance(doc, basestring) assert isinstance(doc, str)
self.doc = doc self.doc = doc
def __repr__(self): def __repr__(self):
@ -846,10 +846,10 @@ class OpcodeInfo(object):
def __init__(self, name, code, arg, def __init__(self, name, code, arg,
stack_before, stack_after, proto, doc): stack_before, stack_after, proto, doc):
assert isinstance(name, basestring) assert isinstance(name, str)
self.name = name self.name = name
assert isinstance(code, basestring) assert isinstance(code, str)
assert len(code) == 1 assert len(code) == 1
self.code = code self.code = code
@ -869,7 +869,7 @@ class OpcodeInfo(object):
assert isinstance(proto, int) and 0 <= proto <= 2 assert isinstance(proto, int) and 0 <= proto <= 2
self.proto = proto self.proto = proto
assert isinstance(doc, basestring) assert isinstance(doc, str)
self.doc = doc self.doc = doc
I = OpcodeInfo I = OpcodeInfo

View File

@ -516,7 +516,7 @@ def extend_path(path, name):
path = path[:] # Start with a copy of the existing path path = path[:] # Start with a copy of the existing path
for dir in sys.path: for dir in sys.path:
if not isinstance(dir, basestring) or not os.path.isdir(dir): if not isinstance(dir, str) or not os.path.isdir(dir):
continue continue
subdir = os.path.join(dir, pname) subdir = os.path.join(dir, pname)
# XXX This may still add duplicate entries to path on # XXX This may still add duplicate entries to path on

View File

@ -116,7 +116,7 @@ class Stats:
def load_stats(self, arg): def load_stats(self, arg):
if not arg: self.stats = {} if not arg: self.stats = {}
elif isinstance(arg, basestring): elif isinstance(arg, str):
f = open(arg, 'rb') f = open(arg, 'rb')
self.stats = marshal.load(f) self.stats = marshal.load(f)
f.close() f.close()

View File

@ -18,7 +18,7 @@ __all__ = ["shlex", "split"]
class shlex: class shlex:
"A lexical analyzer class for simple shell-like syntaxes." "A lexical analyzer class for simple shell-like syntaxes."
def __init__(self, instream=None, infile=None, posix=False): def __init__(self, instream=None, infile=None, posix=False):
if isinstance(instream, basestring): if isinstance(instream, str):
instream = StringIO(instream) instream = StringIO(instream)
if instream is not None: if instream is not None:
self.instream = instream self.instream = instream
@ -61,7 +61,7 @@ class shlex:
def push_source(self, newstream, newfile=None): def push_source(self, newstream, newfile=None):
"Push an input source onto the lexer's input source stack." "Push an input source onto the lexer's input source stack."
if isinstance(newstream, basestring): if isinstance(newstream, str):
newstream = StringIO(newstream) newstream = StringIO(newstream)
self.filestack.appendleft((self.infile, self.instream, self.lineno)) self.filestack.appendleft((self.infile, self.instream, self.lineno))
self.infile = newfile self.infile = newfile
@ -247,7 +247,7 @@ class shlex:
if newfile[0] == '"': if newfile[0] == '"':
newfile = newfile[1:-1] newfile = newfile[1:-1]
# This implements cpp-like semantics for relative-path inclusion. # This implements cpp-like semantics for relative-path inclusion.
if isinstance(self.infile, basestring) and not os.path.isabs(newfile): if isinstance(self.infile, str) and not os.path.isabs(newfile):
newfile = os.path.join(os.path.dirname(self.infile), newfile) newfile = os.path.join(os.path.dirname(self.infile), newfile)
return (newfile, open(newfile, "r")) return (newfile, open(newfile, "r"))

View File

@ -668,7 +668,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, basestring): if isinstance(to_addrs, str):
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

@ -472,7 +472,7 @@ def _compile_info(code, pattern, flags):
code[skip] = len(code) - skip code[skip] = len(code) - skip
def isstring(obj): def isstring(obj):
return isinstance(obj, basestring) return isinstance(obj, str)
def _code(p, flags): def _code(p, flags):

View File

@ -698,7 +698,7 @@ class Popen(object):
errread, errwrite): errread, errwrite):
"""Execute program (MS Windows version)""" """Execute program (MS Windows version)"""
if not isinstance(args, basestring): if not isinstance(args, str):
args = list2cmdline(args) args = list2cmdline(args)
# Process startup details # Process startup details
@ -913,7 +913,7 @@ class Popen(object):
errread, errwrite): errread, errwrite):
"""Execute program (POSIX version)""" """Execute program (POSIX version)"""
if isinstance(args, basestring): if isinstance(args, str):
args = [args] args = [args]
else: else:
args = list(args) args = list(args)

View File

@ -2041,7 +2041,7 @@ class TarFile(object):
""" """
self._check("r") self._check("r")
if isinstance(member, basestring): if isinstance(member, str):
tarinfo = self.getmember(member) tarinfo = self.getmember(member)
else: else:
tarinfo = member tarinfo = member
@ -2077,7 +2077,7 @@ class TarFile(object):
""" """
self._check("r") self._check("r")
if isinstance(member, basestring): if isinstance(member, str):
tarinfo = self.getmember(member) tarinfo = self.getmember(member)
else: else:
tarinfo = member tarinfo = member

View File

@ -39,7 +39,7 @@ class FutureTest(unittest.TestCase):
a(isinstance(major, int), "%s major isn't int" % name) a(isinstance(major, int), "%s major isn't int" % name)
a(isinstance(minor, int), "%s minor isn't int" % name) a(isinstance(minor, int), "%s minor isn't int" % name)
a(isinstance(micro, int), "%s micro isn't int" % name) a(isinstance(micro, int), "%s micro isn't int" % name)
a(isinstance(level, basestring), a(isinstance(level, str),
"%s level isn't string" % name) "%s level isn't string" % name)
a(level in GOOD_SERIALS, a(level in GOOD_SERIALS,
"%s level string has unknown value" % name) "%s level string has unknown value" % name)

View File

@ -81,9 +81,11 @@ class TestABC(unittest.TestCase):
self.assertEqual(issubclass(int, A), True) self.assertEqual(issubclass(int, A), True)
class B(A): class B(A):
pass pass
B.register(basestring) B.register(str)
class C(str): pass
self.assertEqual(isinstance("", A), True) self.assertEqual(isinstance("", A), True)
self.assertEqual(issubclass(str, A), True) self.assertEqual(issubclass(str, A), True)
self.assertEqual(issubclass(C, A), True)
def test_registration_edge_cases(self): def test_registration_edge_cases(self):
class A(metaclass=abc.ABCMeta): class A(metaclass=abc.ABCMeta):

View File

@ -2,7 +2,7 @@ import sys, itertools
import _ast import _ast
def to_tuple(t): def to_tuple(t):
if t is None or isinstance(t, (basestring, int, int, complex)): if t is None or isinstance(t, (str, int, complex)):
return t return t
elif isinstance(t, list): elif isinstance(t, list):
return [to_tuple(e) for e in t] return [to_tuple(e) for e in t]

View File

@ -140,17 +140,17 @@ class CodecCallbackTest(unittest.TestCase):
sin += chr(sys.maxunicode) sin += chr(sys.maxunicode)
sout = b"a\\xac\\u1234\\u20ac\\u8000" sout = b"a\\xac\\u1234\\u20ac\\u8000"
if sys.maxunicode > 0xffff: if sys.maxunicode > 0xffff:
sout += bytes("\\U%08x" % sys.maxunicode) sout += bytes("\\U%08x" % sys.maxunicode, "ascii")
self.assertEqual(sin.encode("ascii", "backslashreplace"), sout) self.assertEqual(sin.encode("ascii", "backslashreplace"), sout)
sout = b"a\xac\\u1234\\u20ac\\u8000" sout = b"a\xac\\u1234\\u20ac\\u8000"
if sys.maxunicode > 0xffff: if sys.maxunicode > 0xffff:
sout += bytes("\\U%08x" % sys.maxunicode) sout += bytes("\\U%08x" % sys.maxunicode, "ascii")
self.assertEqual(sin.encode("latin-1", "backslashreplace"), sout) self.assertEqual(sin.encode("latin-1", "backslashreplace"), sout)
sout = b"a\xac\\u1234\xa4\\u8000" sout = b"a\xac\\u1234\xa4\\u8000"
if sys.maxunicode > 0xffff: if sys.maxunicode > 0xffff:
sout += bytes("\\U%08x" % sys.maxunicode) sout += bytes("\\U%08x" % sys.maxunicode, "ascii")
self.assertEqual(sin.encode("iso-8859-15", "backslashreplace"), sout) self.assertEqual(sin.encode("iso-8859-15", "backslashreplace"), sout)
def test_decoderelaxedutf8(self): def test_decoderelaxedutf8(self):

View File

@ -803,8 +803,9 @@ class UnicodeInternalTest(unittest.TestCase):
codecs.register_error("UnicodeInternalTest", codecs.ignore_errors) codecs.register_error("UnicodeInternalTest", codecs.ignore_errors)
decoder = codecs.getdecoder("unicode_internal") decoder = codecs.getdecoder("unicode_internal")
ab = "ab".encode("unicode_internal") ab = "ab".encode("unicode_internal")
ignored = decoder(bytes("%s\x22\x22\x22\x22%s" % (ab[:4], ab[4:])), ignored = decoder(bytes("%s\x22\x22\x22\x22%s" % (ab[:4], ab[4:]),
"UnicodeInternalTest") "ascii"),
"UnicodeInternalTest")
self.assertEquals(("ab", 12), ignored) self.assertEquals(("ab", 12), ignored)
# From http://www.gnu.org/software/libidn/draft-josefsson-idn-test-vectors.html # From http://www.gnu.org/software/libidn/draft-josefsson-idn-test-vectors.html

View File

@ -235,7 +235,7 @@ class TestCollectionABCs(unittest.TestCase):
for sample in [tuple, list, bytes, str]: for sample in [tuple, list, bytes, str]:
self.failUnless(isinstance(sample(), Sequence)) self.failUnless(isinstance(sample(), Sequence))
self.failUnless(issubclass(sample, Sequence)) self.failUnless(issubclass(sample, Sequence))
self.failUnless(issubclass(basestring, Sequence)) self.failUnless(issubclass(str, Sequence))
def test_MutableSequence(self): def test_MutableSequence(self):
for sample in [tuple, str]: for sample in [tuple, str]:
@ -244,7 +244,7 @@ class TestCollectionABCs(unittest.TestCase):
for sample in [list, bytes]: for sample in [list, bytes]:
self.failUnless(isinstance(sample(), MutableSequence)) self.failUnless(isinstance(sample(), MutableSequence))
self.failUnless(issubclass(sample, MutableSequence)) self.failUnless(issubclass(sample, MutableSequence))
self.failIf(issubclass(basestring, MutableSequence)) self.failIf(issubclass(str, MutableSequence))
def test_main(verbose=None): def test_main(verbose=None):

View File

@ -11,9 +11,9 @@ class GroupDatabaseTestCase(unittest.TestCase):
# attributes promised by the docs # attributes promised by the docs
self.assertEqual(len(value), 4) self.assertEqual(len(value), 4)
self.assertEqual(value[0], value.gr_name) self.assertEqual(value[0], value.gr_name)
self.assert_(isinstance(value.gr_name, basestring)) self.assert_(isinstance(value.gr_name, str))
self.assertEqual(value[1], value.gr_passwd) self.assertEqual(value[1], value.gr_passwd)
self.assert_(isinstance(value.gr_passwd, basestring)) self.assert_(isinstance(value.gr_passwd, str))
self.assertEqual(value[2], value.gr_gid) self.assertEqual(value[2], value.gr_gid)
self.assert_(isinstance(value.gr_gid, int)) self.assert_(isinstance(value.gr_gid, int))
self.assertEqual(value[3], value.gr_mem) self.assertEqual(value[3], value.gr_mem)

View File

@ -242,7 +242,7 @@ class TestIsInstanceIsSubclass(unittest.TestCase):
self.assertEqual(True, issubclass(NewSuper, (NewChild, (NewSuper,)))) self.assertEqual(True, issubclass(NewSuper, (NewChild, (NewSuper,))))
self.assertEqual(True, issubclass(int, (int, (float, int)))) self.assertEqual(True, issubclass(int, (int, (float, int))))
self.assertEqual(True, issubclass(str, (str, (Child, NewChild, basestring)))) self.assertEqual(True, issubclass(str, (str, (Child, NewChild, str))))
def test_subclass_recursion_limit(self): def test_subclass_recursion_limit(self):
# make sure that issubclass raises RuntimeError before the C stack is # make sure that issubclass raises RuntimeError before the C stack is

View File

@ -335,15 +335,15 @@ class PosixPathTest(unittest.TestCase):
except ImportError: except ImportError:
pass pass
else: else:
self.assert_(isinstance(posixpath.expanduser("~/"), basestring)) self.assert_(isinstance(posixpath.expanduser("~/"), str))
# if home directory == root directory, this test makes no sense # if home directory == root directory, this test makes no sense
if posixpath.expanduser("~") != '/': if posixpath.expanduser("~") != '/':
self.assertEqual( self.assertEqual(
posixpath.expanduser("~") + "/", posixpath.expanduser("~") + "/",
posixpath.expanduser("~/") posixpath.expanduser("~/")
) )
self.assert_(isinstance(posixpath.expanduser("~root/"), basestring)) self.assert_(isinstance(posixpath.expanduser("~root/"), str))
self.assert_(isinstance(posixpath.expanduser("~foo/"), basestring)) self.assert_(isinstance(posixpath.expanduser("~foo/"), str))
self.assertRaises(TypeError, posixpath.expanduser) self.assertRaises(TypeError, posixpath.expanduser)

View File

@ -13,19 +13,19 @@ class PwdTest(unittest.TestCase):
for e in entries: for e in entries:
self.assertEqual(len(e), 7) self.assertEqual(len(e), 7)
self.assertEqual(e[0], e.pw_name) self.assertEqual(e[0], e.pw_name)
self.assert_(isinstance(e.pw_name, basestring)) self.assert_(isinstance(e.pw_name, str))
self.assertEqual(e[1], e.pw_passwd) self.assertEqual(e[1], e.pw_passwd)
self.assert_(isinstance(e.pw_passwd, basestring)) self.assert_(isinstance(e.pw_passwd, str))
self.assertEqual(e[2], e.pw_uid) self.assertEqual(e[2], e.pw_uid)
self.assert_(isinstance(e.pw_uid, int)) self.assert_(isinstance(e.pw_uid, int))
self.assertEqual(e[3], e.pw_gid) self.assertEqual(e[3], e.pw_gid)
self.assert_(isinstance(e.pw_gid, int)) self.assert_(isinstance(e.pw_gid, int))
self.assertEqual(e[4], e.pw_gecos) self.assertEqual(e[4], e.pw_gecos)
self.assert_(isinstance(e.pw_gecos, basestring)) self.assert_(isinstance(e.pw_gecos, str))
self.assertEqual(e[5], e.pw_dir) self.assertEqual(e[5], e.pw_dir)
self.assert_(isinstance(e.pw_dir, basestring)) self.assert_(isinstance(e.pw_dir, str))
self.assertEqual(e[6], e.pw_shell) self.assertEqual(e[6], e.pw_shell)
self.assert_(isinstance(e.pw_shell, basestring)) self.assert_(isinstance(e.pw_shell, str))
# The following won't work, because of duplicate entries # The following won't work, because of duplicate entries
# for one uid # for one uid

View File

@ -591,9 +591,10 @@ class ReTests(unittest.TestCase):
self.assertEqual([item.group(0) for item in iter], self.assertEqual([item.group(0) for item in iter],
[":", "::", ":::"]) [":", "::", ":::"])
def test_bug_926075(self): # XXX This needs to be restored for str vs. bytes.
self.assert_(re.compile('bug_926075') is not ## def test_bug_926075(self):
re.compile(str8('bug_926075'))) ## self.assert_(re.compile('bug_926075') is not
## re.compile(str8('bug_926075')))
def test_bug_931848(self): def test_bug_931848(self):
pattern = eval('"[\u002E\u3002\uFF0E\uFF61]"') pattern = eval('"[\u002E\u3002\uFF0E\uFF61]"')

View File

@ -529,7 +529,7 @@ def run_unittest(*classes):
valid_types = (unittest.TestSuite, unittest.TestCase) valid_types = (unittest.TestSuite, unittest.TestCase)
suite = unittest.TestSuite() suite = unittest.TestSuite()
for cls in classes: for cls in classes:
if isinstance(cls, basestring): if isinstance(cls, str):
if cls in sys.modules: if cls in sys.modules:
suite.addTest(unittest.findTestCases(sys.modules[cls])) suite.addTest(unittest.findTestCases(sys.modules[cls]))
else: else:

View File

@ -126,7 +126,7 @@ class SysModuleTest(unittest.TestCase):
def test_getdefaultencoding(self): def test_getdefaultencoding(self):
self.assertRaises(TypeError, sys.getdefaultencoding, 42) self.assertRaises(TypeError, sys.getdefaultencoding, 42)
# can't check more than the type, as the user might have changed it # can't check more than the type, as the user might have changed it
self.assert_(isinstance(sys.getdefaultencoding(), basestring)) self.assert_(isinstance(sys.getdefaultencoding(), str))
# testing sys.settrace() is done in test_trace.py # testing sys.settrace() is done in test_trace.py
# testing sys.setprofile() is done in test_profile.py # testing sys.setprofile() is done in test_profile.py
@ -275,15 +275,15 @@ class SysModuleTest(unittest.TestCase):
self.assert_(isinstance(sys.argv, list)) self.assert_(isinstance(sys.argv, list))
self.assert_(sys.byteorder in ("little", "big")) self.assert_(sys.byteorder in ("little", "big"))
self.assert_(isinstance(sys.builtin_module_names, tuple)) self.assert_(isinstance(sys.builtin_module_names, tuple))
self.assert_(isinstance(sys.copyright, basestring)) self.assert_(isinstance(sys.copyright, str))
self.assert_(isinstance(sys.exec_prefix, basestring)) self.assert_(isinstance(sys.exec_prefix, str))
self.assert_(isinstance(sys.executable, basestring)) self.assert_(isinstance(sys.executable, str))
self.assert_(isinstance(sys.hexversion, int)) self.assert_(isinstance(sys.hexversion, int))
self.assert_(isinstance(sys.maxint, int)) self.assert_(isinstance(sys.maxint, int))
self.assert_(isinstance(sys.maxunicode, int)) self.assert_(isinstance(sys.maxunicode, int))
self.assert_(isinstance(sys.platform, basestring)) self.assert_(isinstance(sys.platform, str))
self.assert_(isinstance(sys.prefix, basestring)) self.assert_(isinstance(sys.prefix, str))
self.assert_(isinstance(sys.version, basestring)) self.assert_(isinstance(sys.version, str))
vi = sys.version_info vi = sys.version_info
self.assert_(isinstance(vi, tuple)) self.assert_(isinstance(vi, tuple))
self.assertEqual(len(vi), 5) self.assertEqual(len(vi), 5)

View File

@ -143,7 +143,7 @@ class test__candidate_tempdir_list(TC):
self.failIf(len(cand) == 0) self.failIf(len(cand) == 0)
for c in cand: for c in cand:
self.assert_(isinstance(c, basestring), self.assert_(isinstance(c, str),
"%s is not a string" % c) "%s is not a string" % c)
def test_wanted_dirs(self): def test_wanted_dirs(self):
@ -328,7 +328,7 @@ class test_gettempprefix(TC):
# gettempprefix returns a nonempty prefix string # gettempprefix returns a nonempty prefix string
p = tempfile.gettempprefix() p = tempfile.gettempprefix()
self.assert_(isinstance(p, basestring)) self.assert_(isinstance(p, str))
self.assert_(len(p) > 0) self.assert_(len(p) > 0)
def test_usable_template(self): def test_usable_template(self):
@ -463,7 +463,7 @@ class test_mkdtemp(TC):
extant[i] = self.do_create(pre="aa") extant[i] = self.do_create(pre="aa")
finally: finally:
for i in extant: for i in extant:
if(isinstance(i, basestring)): if(isinstance(i, str)):
os.rmdir(i) os.rmdir(i)
def test_choose_directory(self): def test_choose_directory(self):

View File

@ -23,7 +23,7 @@ class BaseTestCase(unittest.TestCase):
for i in range(len(textin)): for i in range(len(textin)):
result.append(" %d: %r" % (i, textin[i])) result.append(" %d: %r" % (i, textin[i]))
result = '\n'.join(result) result = '\n'.join(result)
elif isinstance(textin, basestring): elif isinstance(textin, str):
result = " %s\n" % repr(textin) result = " %s\n" % repr(textin)
return result return result

View File

@ -1718,7 +1718,7 @@ class Test_FunctionTestCase(TestCase):
def test_id(self): def test_id(self):
test = unittest.FunctionTestCase(lambda: None) test = unittest.FunctionTestCase(lambda: None)
self.failUnless(isinstance(test.id(), basestring)) self.failUnless(isinstance(test.id(), str))
# "Returns a one-line description of the test, or None if no description # "Returns a one-line description of the test, or None if no description
# has been provided. The default implementation of this method returns # has been provided. The default implementation of this method returns
@ -2239,7 +2239,7 @@ class Test_TestCase(TestCase, TestEquality, TestHashing):
def runTest(self): def runTest(self):
pass pass
self.failUnless(isinstance(Foo().id(), basestring)) self.failUnless(isinstance(Foo().id(), str))
# "Returns a one-line description of the test, or None if no description # "Returns a one-line description of the test, or None if no description
# has been provided. The default implementation of this method returns # has been provided. The default implementation of this method returns

View File

@ -121,9 +121,9 @@ class Timer:
"""Constructor. See class doc string.""" """Constructor. See class doc string."""
self.timer = timer self.timer = timer
ns = {} ns = {}
if isinstance(stmt, basestring): if isinstance(stmt, str):
stmt = reindent(stmt, 8) stmt = reindent(stmt, 8)
if isinstance(setup, basestring): if isinstance(setup, str):
setup = reindent(setup, 4) setup = reindent(setup, 4)
src = template % {'stmt': stmt, 'setup': setup} src = template % {'stmt': stmt, 'setup': setup}
elif hasattr(setup, '__call__'): elif hasattr(setup, '__call__'):
@ -137,7 +137,7 @@ class Timer:
self.inner = ns["inner"] self.inner = ns["inner"]
elif hasattr(stmt, '__call__'): elif hasattr(stmt, '__call__'):
self.src = None self.src = None
if isinstance(setup, basestring): if isinstance(setup, str):
_setup = setup _setup = setup
def setup(): def setup():
exec(_setup, globals(), ns) exec(_setup, globals(), ns)

View File

@ -418,7 +418,7 @@ class TestSuite:
self._tests.append(test) self._tests.append(test)
def addTests(self, tests): def addTests(self, tests):
if isinstance(tests, basestring): if isinstance(tests, str):
raise TypeError("tests must be an iterable of tests, not a string") raise TypeError("tests must be an iterable of tests, not a string")
for test in tests: for test in tests:
self.addTest(test) self.addTest(test)

View File

@ -359,7 +359,7 @@ class OpenerDirector:
def open(self, fullurl, data=None, timeout=None): def open(self, fullurl, data=None, timeout=None):
# accept a URL or a Request object # accept a URL or a Request object
if isinstance(fullurl, basestring): if isinstance(fullurl, str):
req = Request(fullurl, data) req = Request(fullurl, data)
else: else:
req = fullurl req = fullurl
@ -702,7 +702,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, basestring): if isinstance(uri, str):
uri = [uri] uri = [uri]
if not realm in self.passwd: if not realm in self.passwd:
self.passwd[realm] = {} self.passwd[realm] = {}

View File

@ -46,7 +46,7 @@ def encode(in_file, out_file, name=None, mode=None):
# #
if in_file == '-': if in_file == '-':
in_file = sys.stdin.buffer in_file = sys.stdin.buffer
elif isinstance(in_file, basestring): elif isinstance(in_file, str):
if name is None: if name is None:
name = os.path.basename(in_file) name = os.path.basename(in_file)
if mode is None: if mode is None:
@ -60,7 +60,7 @@ def encode(in_file, out_file, name=None, mode=None):
# #
if out_file == '-': if out_file == '-':
out_file = sys.stdout.buffer out_file = sys.stdout.buffer
elif isinstance(out_file, basestring): elif isinstance(out_file, str):
out_file = open(out_file, 'wb') out_file = open(out_file, 'wb')
# #
# Set defaults for name and mode # Set defaults for name and mode
@ -87,7 +87,7 @@ def decode(in_file, out_file=None, mode=None, quiet=0):
# #
if in_file == '-': if in_file == '-':
in_file = sys.stdin.buffer in_file = sys.stdin.buffer
elif isinstance(in_file, basestring): elif isinstance(in_file, str):
in_file = open(in_file, 'rb') in_file = open(in_file, 'rb')
# #
# Read until a begin is encountered or we've exhausted the file # Read until a begin is encountered or we've exhausted the file
@ -118,7 +118,7 @@ def decode(in_file, out_file=None, mode=None, quiet=0):
opened = False opened = False
if out_file == '-': if out_file == '-':
out_file = sys.stdout.buffer out_file = sys.stdout.buffer
elif isinstance(out_file, basestring): elif isinstance(out_file, str):
fp = open(out_file, 'wb') fp = open(out_file, 'wb')
try: try:
os.path.chmod(out_file, mode) os.path.chmod(out_file, mode)
@ -169,7 +169,7 @@ def test():
if options.decode: if options.decode:
if options.text: if options.text:
if isinstance(output, basestring): if isinstance(output, str):
output = open(output, 'wb') output = open(output, 'wb')
else: else:
print(sys.argv[0], ': cannot do -t to stdout') print(sys.argv[0], ': cannot do -t to stdout')
@ -177,7 +177,7 @@ def test():
decode(input, output) decode(input, output)
else: else:
if options.text: if options.text:
if isinstance(input, basestring): if isinstance(input, str):
input = open(input, 'rb') input = open(input, 'rb')
else: else:
print(sys.argv[0], ': cannot do -t from stdin') print(sys.argv[0], ': cannot do -t from stdin')

View File

@ -150,10 +150,10 @@ def filterwarnings(action, message="", category=Warning, module="", lineno=0,
import re import re
assert action in ("error", "ignore", "always", "default", "module", assert action in ("error", "ignore", "always", "default", "module",
"once"), "invalid action: %r" % (action,) "once"), "invalid action: %r" % (action,)
assert isinstance(message, basestring), "message must be a string" assert isinstance(message, str), "message must be a string"
assert isinstance(category, type), "category must be a class" assert isinstance(category, type), "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 isinstance(module, basestring), "module must be a string" assert isinstance(module, str), "module must be a string"
assert isinstance(lineno, int) 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,

View File

@ -155,7 +155,7 @@ class Wave_read:
def __init__(self, f): def __init__(self, f):
self._i_opened_the_file = None self._i_opened_the_file = None
if isinstance(f, basestring): if isinstance(f, str):
f = __builtin__.open(f, 'rb') f = __builtin__.open(f, 'rb')
self._i_opened_the_file = f self._i_opened_the_file = f
# else, assume it is an open file object already # else, assume it is an open file object already
@ -299,7 +299,7 @@ class Wave_write:
def __init__(self, f): def __init__(self, f):
self._i_opened_the_file = None self._i_opened_the_file = None
if isinstance(f, basestring): if isinstance(f, str):
f = __builtin__.open(f, 'wb') f = __builtin__.open(f, 'wb')
self._i_opened_the_file = f self._i_opened_the_file = f
try: try:

View File

@ -159,7 +159,7 @@ class GenericBrowser(BaseBrowser):
and without remote functionality.""" and without remote functionality."""
def __init__(self, name): def __init__(self, name):
if isinstance(name, basestring): if isinstance(name, str):
self.name = name self.name = name
self.args = ["%s"] self.args = ["%s"]
else: else:

View File

@ -325,7 +325,7 @@ default_bufsize = (2 ** 14) - 20
def parse(stream_or_string, parser=None, bufsize=None): def parse(stream_or_string, parser=None, bufsize=None):
if bufsize is None: if bufsize is None:
bufsize = default_bufsize bufsize = default_bufsize
if isinstance(stream_or_string, basestring): if isinstance(stream_or_string, str):
stream = open(stream_or_string) stream = open(stream_or_string)
else: else:
stream = stream_or_string stream = stream_or_string

View File

@ -272,7 +272,7 @@ def prepare_input_source(source, base = ""):
"""This function takes an InputSource and an optional base URL and """This function takes an InputSource and an optional base URL and
returns a fully resolved InputSource object ready for reading.""" returns a fully resolved InputSource object ready for reading."""
if isinstance(source, basestring): if isinstance(source, str):
source = xmlreader.InputSource(source) source = xmlreader.InputSource(source)
elif hasattr(source, "read"): elif hasattr(source, "read"):
f = source f = source

View File

@ -294,7 +294,7 @@ class DateTime:
""" """
def __init__(self, value=0): def __init__(self, value=0):
if not isinstance(value, basestring): if not isinstance(value, str):
if datetime and isinstance(value, datetime.datetime): if datetime and isinstance(value, datetime.datetime):
self.value = value.strftime("%Y%m%dT%H:%M:%S") self.value = value.strftime("%Y%m%dT%H:%M:%S")
return return
@ -653,7 +653,7 @@ class Marshaller:
write("<value><struct>\n") write("<value><struct>\n")
for k, v in value.items(): for k, v in value.items():
write("<member>\n") write("<member>\n")
if not isinstance(k, basestring): if not isinstance(k, str):
raise TypeError("dictionary key must be string") raise TypeError("dictionary key must be string")
write("<name>%s</name>\n" % escape(k)) write("<name>%s</name>\n" % escape(k))
dump(v, write) dump(v, write)
@ -1031,7 +1031,7 @@ def dumps(params, methodname=None, methodresponse=None, encoding=None,
# standard XML-RPC wrappings # standard XML-RPC wrappings
if methodname: if methodname:
# a method call # a method call
if not isinstance(methodname, basestring): if not isinstance(methodname, str):
methodname = methodname.encode(encoding) methodname = methodname.encode(encoding)
data = ( data = (
xmlheader, xmlheader,

View File

@ -596,7 +596,7 @@ class ZipFile:
self.pwd = None self.pwd = None
# Check if we were passed a file-like object # Check if we were passed a file-like object
if isinstance(file, basestring): if isinstance(file, str):
# No, it's a filename # No, it's a filename
self._filePassed = 0 self._filePassed = 0
self.filename = file self.filename = file

View File

@ -62,7 +62,7 @@ module instead.
/* end 2.2 compatibility macros */ /* end 2.2 compatibility macros */
#define IS_BASESTRING(o) \ #define IS_BASESTRING(o) \
PyObject_TypeCheck(o, &PyBaseString_Type) PyUnicode_Check(o)
static PyObject *error_obj; /* CSV exception */ static PyObject *error_obj; /* CSV exception */
static PyObject *dialects; /* Dialect registry */ static PyObject *dialects; /* Dialect registry */

View File

@ -3072,14 +3072,6 @@ str_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
return pnew; return pnew;
} }
static PyObject *
basestring_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
PyErr_SetString(PyExc_TypeError,
"The basestring type cannot be instantiated");
return NULL;
}
static PyObject * static PyObject *
string_mod(PyObject *v, PyObject *w) string_mod(PyObject *v, PyObject *w)
{ {
@ -3090,9 +3082,6 @@ string_mod(PyObject *v, PyObject *w)
return PyString_Format(v, w); return PyString_Format(v, w);
} }
PyDoc_STRVAR(basestring_doc,
"Type basestring cannot be instantiated; it is the base for str8 and str.");
static PyNumberMethods string_as_number = { static PyNumberMethods string_as_number = {
0, /*nb_add*/ 0, /*nb_add*/
0, /*nb_subtract*/ 0, /*nb_subtract*/
@ -3100,49 +3089,6 @@ static PyNumberMethods string_as_number = {
string_mod, /*nb_remainder*/ string_mod, /*nb_remainder*/
}; };
PyTypeObject PyBaseString_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"basestring",
0,
0,
0, /* tp_dealloc */
0, /* tp_print */
0, /* tp_getattr */
0, /* tp_setattr */
0, /* tp_compare */
0, /* tp_repr */
0, /* tp_as_number */
0, /* tp_as_sequence */
0, /* tp_as_mapping */
0, /* tp_hash */
0, /* tp_call */
0, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
basestring_doc, /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
0, /* tp_methods */
0, /* tp_members */
0, /* tp_getset */
&PyBaseObject_Type, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
0, /* tp_init */
0, /* tp_alloc */
basestring_new, /* tp_new */
0, /* tp_free */
};
PyDoc_STRVAR(string_doc, PyDoc_STRVAR(string_doc,
"str(object) -> string\n\ "str(object) -> string\n\
\n\ \n\
@ -3183,7 +3129,7 @@ PyTypeObject PyString_Type = {
string_methods, /* tp_methods */ string_methods, /* tp_methods */
0, /* tp_members */ 0, /* tp_members */
0, /* tp_getset */ 0, /* tp_getset */
&PyBaseString_Type, /* tp_base */ &PyBaseObject_Type, /* tp_base */
0, /* tp_dict */ 0, /* tp_dict */
0, /* tp_descr_get */ 0, /* tp_descr_get */
0, /* tp_descr_set */ 0, /* tp_descr_set */
@ -3615,7 +3561,7 @@ PyString_Format(PyObject *format, PyObject *args)
argidx = -2; argidx = -2;
} }
if (Py_Type(args)->tp_as_mapping && !PyTuple_Check(args) && if (Py_Type(args)->tp_as_mapping && !PyTuple_Check(args) &&
!PyObject_TypeCheck(args, &PyBaseString_Type)) !PyString_Check(args) && !PyUnicode_Check(args))
dict = args; dict = args;
while (--fmtcnt >= 0) { while (--fmtcnt >= 0) {
if (*fmt != '%') { if (*fmt != '%') {

View File

@ -8441,7 +8441,7 @@ PyObject *PyUnicode_Format(PyObject *format,
argidx = -2; argidx = -2;
} }
if (Py_Type(args)->tp_as_mapping && !PyTuple_Check(args) && if (Py_Type(args)->tp_as_mapping && !PyTuple_Check(args) &&
!PyObject_TypeCheck(args, &PyBaseString_Type)) !PyString_Check(args) && !PyUnicode_Check(args))
dict = args; dict = args;
while (--fmtcnt >= 0) { while (--fmtcnt >= 0) {
@ -8935,7 +8935,7 @@ PyTypeObject PyUnicode_Type = {
unicode_methods, /* tp_methods */ unicode_methods, /* tp_methods */
0, /* tp_members */ 0, /* tp_members */
0, /* tp_getset */ 0, /* tp_getset */
&PyBaseString_Type, /* tp_base */ &PyBaseObject_Type, /* tp_base */
0, /* tp_dict */ 0, /* tp_dict */
0, /* tp_descr_get */ 0, /* tp_descr_get */
0, /* tp_descr_set */ 0, /* tp_descr_set */

View File

@ -1595,12 +1595,19 @@ builtin_sum(PyObject *self, PyObject *args)
} }
} else { } else {
/* reject string values for 'start' parameter */ /* reject string values for 'start' parameter */
if (PyObject_TypeCheck(result, &PyBaseString_Type)) { if (PyUnicode_Check(result)) {
PyErr_SetString(PyExc_TypeError, PyErr_SetString(PyExc_TypeError,
"sum() can't sum strings [use ''.join(seq) instead]"); "sum() can't sum strings [use ''.join(seq) instead]");
Py_DECREF(iter); Py_DECREF(iter);
return NULL; return NULL;
} }
if (PyBytes_Check(result)) {
PyErr_SetString(PyExc_TypeError,
"sum() can't sum bytes [use b''.join(seq) instead]");
Py_DECREF(iter);
return NULL;
}
Py_INCREF(result); Py_INCREF(result);
} }
@ -1788,7 +1795,6 @@ _PyBuiltin_Init(void)
SETBUILTIN("NotImplemented", Py_NotImplemented); SETBUILTIN("NotImplemented", Py_NotImplemented);
SETBUILTIN("False", Py_False); SETBUILTIN("False", Py_False);
SETBUILTIN("True", Py_True); SETBUILTIN("True", Py_True);
SETBUILTIN("basestring", &PyBaseString_Type);
SETBUILTIN("bool", &PyBool_Type); SETBUILTIN("bool", &PyBool_Type);
SETBUILTIN("memoryview", &PyMemoryView_Type); SETBUILTIN("memoryview", &PyMemoryView_Type);
SETBUILTIN("bytes", &PyBytes_Type); SETBUILTIN("bytes", &PyBytes_Type);