Merged revisions 55795-55816 via svnmerge from

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

........
  r55797 | neal.norwitz | 2007-06-07 00:00:57 -0700 (Thu, 07 Jun 2007) | 3 lines

  Get rid of some remnants of classic classes.  types.ClassType == type.
  Also get rid of almost all uses of the types module and use the builtin name.
........
  r55798 | neal.norwitz | 2007-06-07 00:12:36 -0700 (Thu, 07 Jun 2007) | 1 line

  Remove a use of types, verify commit hook works
........
  r55809 | guido.van.rossum | 2007-06-07 11:11:29 -0700 (Thu, 07 Jun 2007) | 2 lines

  Fix syntax error introduced by Neal in last checkin.
........
This commit is contained in:
Guido van Rossum 2007-06-07 23:15:56 +00:00
parent 7b955bd125
commit 1325790b93
40 changed files with 161 additions and 202 deletions

View file

@ -22,7 +22,6 @@
import copy
import xdrlib
import random
from types import ListType, StringType
import cPickle as pickle
try:
@ -229,7 +228,7 @@ def CreateTable(self, table, columns):
raises TableDBError if it already exists or for other DB errors.
"""
assert isinstance(columns, ListType)
assert isinstance(columns, list)
txn = None
try:
# checking sanity of the table and column names here on
@ -270,7 +269,7 @@ def ListTableColumns(self, table):
"""Return a list of columns in the given table.
[] if the table doesn't exist.
"""
assert isinstance(table, StringType)
assert isinstance(table, str)
if contains_metastrings(table):
raise ValueError, "bad table name: contains reserved metastrings"
@ -300,7 +299,7 @@ def CreateOrExtendTable(self, table, columns):
additional columns present in the given list as well as
all of its current columns.
"""
assert isinstance(columns, ListType)
assert isinstance(columns, list)
try:
self.CreateTable(table, columns)
except TableAlreadyExists:

View file

@ -96,10 +96,10 @@ def scanvars(reader, frame, locals):
def html(einfo, context=5):
"""Return a nice HTML document describing a given traceback."""
import os, types, time, traceback, linecache, inspect, pydoc
import os, time, traceback, linecache, inspect, pydoc
etype, evalue, etb = einfo
if type(etype) is types.ClassType:
if isinstance(etype, type):
etype = etype.__name__
pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
date = time.ctime(time.time())
@ -188,10 +188,10 @@ def reader(lnum=[lnum]):
def text(einfo, context=5):
"""Return a plain text document describing a given traceback."""
import os, types, time, traceback, linecache, inspect, pydoc
import os, time, traceback, linecache, inspect, pydoc
etype, evalue, etb = einfo
if type(etype) is types.ClassType:
if isinstance(etype, type):
etype = etype.__name__
pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
date = time.ctime(time.time())

View file

@ -100,12 +100,15 @@ def copy(x):
def _copy_immutable(x):
return x
for t in (type(None), int, float, bool, str, tuple,
frozenset, type, range, types.ClassType,
frozenset, type, range,
types.BuiltinFunctionType,
types.FunctionType):
d[t] = _copy_immutable
for name in ("ComplexType", "UnicodeType", "CodeType"):
t = getattr(types, name, None)
t = getattr(types, "CodeType", None)
if t is not None:
d[t] = _copy_immutable
for name in ("complex", "unicode"):
t = globals()['__builtins__'].get(name)
if t is not None:
d[t] = _copy_immutable
@ -192,7 +195,6 @@ def _deepcopy_atomic(x, memo):
pass
d[type] = _deepcopy_atomic
d[range] = _deepcopy_atomic
d[types.ClassType] = _deepcopy_atomic
d[types.BuiltinFunctionType] = _deepcopy_atomic
d[types.FunctionType] = _deepcopy_atomic

View file

@ -26,7 +26,7 @@ def dis(x=None):
items = sorted(x.__dict__.items())
for name, x1 in items:
if isinstance(x1, (types.MethodType, types.FunctionType,
types.CodeType, types.ClassType, type)):
types.CodeType, type)):
print("Disassembly of %s:" % name)
try:
dis(x1)

View file

@ -9,7 +9,6 @@
__revision__ = "$Id$"
import sys, os, re
from types import *
from distutils.errors import *
from distutils import util, dir_util, file_util, archive_util, dep_util
from distutils import log
@ -245,7 +244,7 @@ def ensure_string_list (self, option):
elif isinstance(val, basestring):
setattr(self, option, re.split(r',\s*|\s+', val))
else:
if type(val) is ListType:
if isinstance(val, list):
ok = all(isinstance(v, basestring) for v in val)
else:
ok = 0
@ -422,7 +421,7 @@ def make_file (self, infiles, outfile, func, args,
# Allow 'infiles' to be a single string
if isinstance(infiles, basestring):
infiles = (infiles,)
elif type(infiles) not in (ListType, TupleType):
elif not isinstance(infiles, (list, tuple)):
raise TypeError, \
"'infiles' must be a string, or a list or tuple of strings"

View file

@ -9,7 +9,6 @@
__revision__ = "$Id$"
import sys, os, re
from types import *
from copy import copy
try:
@ -527,7 +526,7 @@ def _parse_command_opts (self, parser, args):
# Also make sure that the command object provides a list of its
# known options.
if not (hasattr(cmd_class, 'user_options') and
type(cmd_class.user_options) is ListType):
isinstance(cmd_class.user_options, list)):
raise DistutilsClassError, \
("command class %s must provide " +
"'user_options' attribute (a list of tuples)") % \
@ -543,7 +542,7 @@ def _parse_command_opts (self, parser, args):
# Check for help_options in command class. They have a different
# format (tuple of four) so we need to preprocess them here.
if (hasattr(cmd_class, 'help_options') and
type(cmd_class.help_options) is ListType):
isinstance(cmd_class.help_options, list)):
help_options = fix_help_options(cmd_class.help_options)
else:
help_options = []
@ -561,7 +560,7 @@ def _parse_command_opts (self, parser, args):
return
if (hasattr(cmd_class, 'help_options') and
type(cmd_class.help_options) is ListType):
isinstance(cmd_class.help_options, list)):
help_option_found=0
for (help_option, short, desc, func) in cmd_class.help_options:
if hasattr(opts, parser.get_attr_name(help_option)):
@ -646,12 +645,12 @@ def _show_help (self,
print()
for command in self.commands:
if type(command) is ClassType and issubclass(command, Command):
if isinstance(command, type) and issubclass(command, Command):
klass = command
else:
klass = self.get_command_class(command)
if (hasattr(klass, 'help_options') and
type(klass.help_options) is ListType):
isinstance(klass.help_options, list)):
parser.set_option_table(klass.user_options +
fix_help_options(klass.help_options))
else:

View file

@ -6,7 +6,6 @@
__revision__ = "$Id$"
import os, sys
from types import *
try:
import warnings
@ -104,7 +103,7 @@ def __init__ (self, name, sources,
**kw # To catch unknown keywords
):
assert isinstance(name, basestring), "'name' must be a string"
assert (type(sources) is ListType and
assert (isinstance(sources, list) and
all(isinstance(v, basestring) for v in sources)), \
"'sources' must be a list of strings"

View file

@ -6,7 +6,6 @@
__revision__ = "$Id$"
from types import *
import sys, os, io
@ -137,7 +136,7 @@ def gen_error (self, msg, line=None):
if line is None:
line = self.current_line
outmsg.append(self.filename + ", ")
if type (line) in (ListType, TupleType):
if isinstance (line, (list, tuple)):
outmsg.append("lines %d-%d: " % tuple (line))
else:
outmsg.append("line %d: " % line)
@ -239,7 +238,7 @@ def readline (self):
line = buildup_line + line
# careful: pay attention to line number when incrementing it
if type (self.current_line) is ListType:
if isinstance (self.current_line, list):
self.current_line[1] = self.current_line[1] + 1
else:
self.current_line = [self.current_line,
@ -250,7 +249,7 @@ def readline (self):
return None
# still have to be careful about incrementing the line number!
if type (self.current_line) is ListType:
if isinstance (self.current_line, list):
self.current_line = self.current_line[1] + 1
else:
self.current_line = self.current_line + 1

View file

@ -16,7 +16,6 @@
__revision__ = "$Id$"
import os, sys
from types import NoneType
from copy import copy
from distutils import sysconfig
@ -212,7 +211,7 @@ def link(self, target_desc, objects,
lib_opts = gen_lib_options(self, library_dirs, runtime_library_dirs,
libraries)
if not isinstance(output_dir, (basestring, NoneType)):
if not isinstance(output_dir, (basestring, type(None))):
raise TypeError, "'output_dir' must be a string or None"
if output_dir is not None:
output_filename = os.path.join(output_dir, output_filename)

View file

@ -131,14 +131,14 @@ def get_arg_text(ob):
arg_text = ""
if ob is not None:
arg_offset = 0
if type(ob) in (types.ClassType, types.TypeType):
if isinstance(ob, type):
# Look for the highest __init__ in the class chain.
fob = _find_constructor(ob)
if fob is None:
fob = lambda: None
else:
arg_offset = 1
elif type(ob)==types.MethodType:
elif isinstace(ob, types.MethodType):
# bit of a hack for methods - turn it into a function
# but we drop the "self" param.
fob = ob.im_func
@ -146,7 +146,7 @@ def get_arg_text(ob):
else:
fob = ob
# Try to build one for Python defined functions
if type(fob) in [types.FunctionType, types.LambdaType]:
if isinstance(fob, (types.FunctionType, types.LambdaType)):
argcount = fob.__code__.co_argcount
real_args = fob.__code__.co_varnames[arg_offset:argcount]
defaults = fob.__defaults__ or []

View file

@ -101,17 +101,14 @@ def keys(self):
pass
return keys
from types import *
dispatch = {
IntType: AtomicObjectTreeItem,
LongType: AtomicObjectTreeItem,
FloatType: AtomicObjectTreeItem,
StringType: AtomicObjectTreeItem,
TupleType: SequenceTreeItem,
ListType: SequenceTreeItem,
DictType: DictTreeItem,
ClassType: ClassTreeItem,
int: AtomicObjectTreeItem,
float: AtomicObjectTreeItem,
str: AtomicObjectTreeItem,
tuple: SequenceTreeItem,
list: SequenceTreeItem,
dict: DictTreeItem,
type: ClassTreeItem,
}
def make_objecttreeitem(labeltext, object, setfunction=None):

View file

@ -287,7 +287,7 @@ def getresponse(self, myseq, wait):
def _proxify(self, obj):
if isinstance(obj, RemoteProxy):
return RPCProxy(self, obj.oid)
if isinstance(obj, types.ListType):
if isinstance(obj, list):
return map(self._proxify, obj)
# XXX Check for other types -- not currently needed
return obj
@ -574,7 +574,7 @@ def _getmethods(obj, methods):
attr = getattr(obj, name)
if hasattr(attr, '__call__'):
methods[name] = 1
if type(obj) == types.ClassType:
if isinstance(obj, type):
for super in obj.__bases__:
_getmethods(super, methods)

View file

@ -47,7 +47,7 @@ def isclass(object):
Class objects provide these attributes:
__doc__ documentation string
__module__ name of module in which this class was defined"""
return isinstance(object, types.ClassType) or hasattr(object, '__bases__')
return isinstance(object, type) or hasattr(object, '__bases__')
def ismethod(object):
"""Return true if the object is an instance method.

View file

@ -21,7 +21,7 @@ def __init__(self, master=None, cnf=None, **kw):
cnf = _cnfmerge((cnf, kw))
fcnf = {}
for k in cnf.keys():
if type(k) == ClassType or k == 'name':
if isinstace(k, type) or k == 'name':
fcnf[k] = cnf[k]
del cnf[k]
self.frame = Frame(master, **fcnf)

View file

@ -38,7 +38,6 @@
import _tkinter # If this fails your Python may not be configured for Tk
tkinter = _tkinter # b/w compat for export
TclError = _tkinter.TclError
from types import *
from Tkconstants import *
try:
import MacOS; _MacOS = MacOS; del MacOS
@ -61,11 +60,11 @@
except AttributeError: _tkinter.deletefilehandler = None
def _flatten(tuple):
def _flatten(seq):
"""Internal function."""
res = ()
for item in tuple:
if type(item) in (TupleType, ListType):
for item in seq:
if isinstance(item, (tuple, list)):
res = res + _flatten(item)
elif item is not None:
res = res + (item,)
@ -76,9 +75,9 @@ def _flatten(tuple):
def _cnfmerge(cnfs):
"""Internal function."""
if type(cnfs) is DictionaryType:
if isinstance(cnfs, dict):
return cnfs
elif type(cnfs) in (NoneType, StringType):
elif isinstance(cnfs, (type(None), str)):
return cnfs
else:
cnf = {}
@ -867,7 +866,7 @@ def winfo_visualsavailable(self, includeids=0):
data = self.tk.split(
self.tk.call('winfo', 'visualsavailable', self._w,
includeids and 'includeids' or None))
if type(data) is StringType:
if isinstance(data, str):
data = [self.tk.split(data)]
return map(self.__winfo_parseitem, data)
def __winfo_parseitem(self, t):
@ -934,7 +933,7 @@ def bindtags(self, tagList=None):
self.tk.call('bindtags', self._w, tagList)
def _bind(self, what, sequence, func, add, needcleanup=1):
"""Internal function."""
if type(func) is StringType:
if isinstance(func, str):
self.tk.call(what + (sequence, func))
elif func:
funcid = self._register(func, self._substitute,
@ -1181,7 +1180,7 @@ def _configure(self, cmd, cnf, kw):
self.tk.call(_flatten((self._w, cmd)))):
cnf[x[0][1:]] = (x[0][1:],) + x[1:]
return cnf
if type(cnf) is StringType:
if isinstance(cnf, str):
x = self.tk.split(
self.tk.call(_flatten((self._w, cmd, '-'+cnf))))
return (x[0][1:],) + x[1:]
@ -1262,7 +1261,7 @@ def grid_bbox(self, column=None, row=None, col2=None, row2=None):
bbox = grid_bbox
def _grid_configure(self, command, index, cnf, kw):
"""Internal function."""
if type(cnf) is StringType and not kw:
if isinstance(cnf, str) and not kw:
if cnf[-1:] == '_':
cnf = cnf[:-1]
if cnf[:1] != '-':
@ -1923,7 +1922,7 @@ def __init__(self, master, widgetName, cnf={}, kw={}, extra=()):
BaseWidget._setup(self, master, cnf)
classes = []
for k in cnf.keys():
if type(k) is ClassType:
if isinstance(k, type):
classes.append((k, cnf[k]))
del cnf[k]
self.tk.call(
@ -2136,7 +2135,7 @@ def _create(self, itemType, args, kw): # Args: (val, val, ..., cnf={})
"""Internal function."""
args = _flatten(args)
cnf = args[-1]
if type(cnf) in (DictionaryType, TupleType):
if isinstance(cnf, (dict, tuple)):
args = args[:-1]
else:
cnf = {}
@ -3695,7 +3694,7 @@ def paneconfigure(self, tagOrId, cnf=None, **kw):
'paneconfigure', tagOrId)):
cnf[x[0][1:]] = (x[0][1:],) + x[1:]
return cnf
if type(cnf) == StringType and not kw:
if isinstance(cnf, str) and not kw:
x = self.tk.split(self.tk.call(
self._w, 'paneconfigure', tagOrId, '-'+cnf))
return (x[0][1:],) + x[1:]

View file

@ -26,7 +26,7 @@
To use, simply 'import logging' and log away!
"""
import sys, os, types, time, cStringIO, traceback
import sys, os, time, cStringIO, traceback
try:
import codecs
@ -48,6 +48,8 @@
# Miscellaneous module data
#---------------------------------------------------------------------------
_unicode = 'unicode' in dir(__builtins__)
#
# _srcfile is used when walking the stack to check when we've got the first
# caller stack frame.
@ -234,7 +236,7 @@ def __init__(self, name, level, pathname, lineno,
# 'Value is %d' instead of 'Value is 0'.
# For the use case of passing a dictionary, this should not be a
# problem.
if args and (len(args) == 1) and args[0] and (type(args[0]) == types.DictType):
if args and (len(args) == 1) and args[0] and isinstance(args[0], dict):
args = args[0]
self.args = args
self.levelname = getLevelName(level)
@ -275,11 +277,11 @@ def getMessage(self):
Return the message for this LogRecord after merging any user-supplied
arguments with the message.
"""
if not hasattr(types, "UnicodeType"): #if no unicode support...
if not _unicode: #if no unicode support...
msg = str(self.msg)
else:
msg = self.msg
if type(msg) not in (types.UnicodeType, types.StringType):
if not isinstance(msg, basestring):
try:
msg = str(self.msg)
except UnicodeError:
@ -743,7 +745,7 @@ def emit(self, record):
try:
msg = self.format(record)
fs = "%s\n"
if not hasattr(types, "UnicodeType"): #if no unicode support...
if not _unicode: #if no unicode support...
self.stream.write(fs % msg)
else:
try:
@ -1053,7 +1055,7 @@ def log(self, level, msg, *args, **kwargs):
logger.log(level, "We have a %s", "mysterious problem", exc_info=1)
"""
if type(level) != types.IntType:
if not isinstance(level, int):
if raiseExceptions:
raise TypeError, "level must be an integer"
else:
@ -1103,7 +1105,7 @@ def _log(self, level, msg, args, exc_info=None, extra=None):
else:
fn, lno, func = "(unknown file)", 0, "(unknown function)"
if exc_info:
if type(exc_info) != types.TupleType:
if not isinstance(exc_info, tuple):
exc_info = sys.exc_info()
record = self.makeRecord(self.name, level, fn, lno, msg, args, exc_info, func, extra)
self.handle(record)

View file

@ -27,7 +27,7 @@
To use, simply 'import logging' and log away!
"""
import sys, logging, logging.handlers, socket, struct, os, traceback, types
import sys, logging, logging.handlers, socket, struct, os, traceback
try:
import thread
@ -289,7 +289,7 @@ def handle(self):
traceback.print_exc()
os.remove(file)
except socket.error as e:
if type(e.args) != types.TupleType:
if not isinstancetype(e.args, tuple):
raise
else:
errcode = e.args[0]

View file

@ -27,7 +27,7 @@
To use, simply 'import logging' and log away!
"""
import sys, logging, socket, types, os, struct, time, glob
import sys, logging, socket, os, struct, time, glob
try:
import cPickle as pickle
except ImportError:
@ -637,7 +637,7 @@ def __init__(self, address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER):
self.address = address
self.facility = facility
if type(address) == types.StringType:
if isinstance(address, str):
self.unixsocket = 1
self._connect_unixsocket(address)
else:
@ -669,9 +669,9 @@ def encodePriority(self, facility, priority):
priority_names mapping dictionaries are used to convert them to
integers.
"""
if type(facility) == types.StringType:
if isinstance(facility, str):
facility = self.facility_names[facility]
if type(priority) == types.StringType:
if isinstance(priority, str):
priority = self.priority_names[priority]
return (facility << 3) | priority
@ -738,16 +738,16 @@ def __init__(self, mailhost, fromaddr, toaddrs, subject, credentials=None):
for the credentials argument.
"""
logging.Handler.__init__(self)
if type(mailhost) == types.TupleType:
if isinstance(mailhost, tuple):
self.mailhost, self.mailport = mailhost
else:
self.mailhost, self.mailport = mailhost, None
if type(credentials) == types.TupleType:
if isinstance(credentials, tuple):
self.username, self.password = credentials
else:
self.username = None
self.fromaddr = fromaddr
if type(toaddrs) == types.StringType:
if isinstance(toaddrs, str):
toaddrs = [toaddrs]
self.toaddrs = toaddrs
self.subject = subject

View file

@ -4,7 +4,7 @@
Objects of most types can now be created by calling the type object.
"""
from types import ClassType as classobj
classobj = type
from types import FunctionType as function
from types import MethodType as instancemethod
from types import ModuleType as module

View file

@ -67,7 +67,6 @@
"""
import sys, os
import types
import textwrap
def _repr(self):
@ -641,7 +640,7 @@ def _check_type(self):
# Python 2.1 and earlier, and is short-circuited by the
# first check on modern Pythons.)
import __builtin__
if ( type(self.type) is types.TypeType or
if ( isinstance(self.type, type) or
(hasattr(self.type, "__name__") and
getattr(__builtin__, self.type.__name__, None) is self.type) ):
self.type = self.type.__name__
@ -660,7 +659,7 @@ def _check_choice(self):
if self.choices is None:
raise OptionError(
"must supply a list of choices for type 'choice'", self)
elif type(self.choices) not in (types.TupleType, types.ListType):
elif not isinstance(self.choices, (tuple, list)):
raise OptionError(
"choices must be a list of strings ('%s' supplied)"
% str(type(self.choices)).split("'")[1], self)
@ -704,12 +703,12 @@ def _check_callback(self):
raise OptionError(
"callback not callable: %r" % self.callback, self)
if (self.callback_args is not None and
type(self.callback_args) is not types.TupleType):
not isinstance(self.callback_args, tuple)):
raise OptionError(
"callback_args, if supplied, must be a tuple: not %r"
% self.callback_args, self)
if (self.callback_kwargs is not None and
type(self.callback_kwargs) is not types.DictType):
not isinstance(self.callback_kwargs, dict)):
raise OptionError(
"callback_kwargs, if supplied, must be a dict: not %r"
% self.callback_kwargs, self)
@ -834,7 +833,7 @@ def __str__(self):
def __eq__(self, other):
if isinstance(other, Values):
return self.__dict__ == other.__dict__
elif isinstance(other, types.DictType):
elif isinstance(other, dict):
return self.__dict__ == other
else:
return NotImplemented

View file

@ -26,7 +26,7 @@
__version__ = "$Revision$" # Code version
from types import *
from types import FunctionType, BuiltinFunctionType
from copy_reg import dispatch_table
from copy_reg import _extension_registry, _inverted_registry, _extension_cache
import marshal
@ -283,7 +283,7 @@ def save(self, obj):
# Check for a class with a custom metaclass; treat as regular class
try:
issc = issubclass(t, TypeType)
issc = issubclass(t, type)
except TypeError: # t is not a class (old Boost; see SF #502085)
issc = 0
if issc:
@ -313,7 +313,7 @@ def save(self, obj):
return
# Assert that reduce() returned a tuple
if type(rv) is not TupleType:
if not isinstance(rv, tuple):
raise PicklingError("%s must return string or tuple" % reduce)
# Assert that it returned an appropriately sized tuple
@ -342,7 +342,7 @@ def save_reduce(self, func, args, state=None,
# This API is called by some subclasses
# Assert that args is a tuple or None
if not isinstance(args, TupleType):
if not isinstance(args, tuple):
raise PicklingError("args from reduce() should be a tuple")
# Assert that func is callable
@ -420,7 +420,7 @@ def save_reduce(self, func, args, state=None,
def save_none(self, obj):
self.write(NONE)
dispatch[NoneType] = save_none
dispatch[type(None)] = save_none
def save_bool(self, obj):
if self.proto >= 2:
@ -452,7 +452,7 @@ def save_int(self, obj, pack=struct.pack):
# Text pickle, or int too big to fit in signed 4-byte format.
self.write(INT + bytes(repr(obj)) + b'\n')
# XXX save_int is merged into save_long
# dispatch[IntType] = save_int
# dispatch[int] = save_int
def save_long(self, obj, pack=struct.pack):
if self.bin:
@ -483,14 +483,14 @@ def save_long(self, obj, pack=struct.pack):
self.write(LONG4 + pack("<i", n) + encoded)
return
self.write(LONG + bytes(repr(obj)) + b'\n')
dispatch[LongType] = save_long
dispatch[int] = save_long
def save_float(self, obj, pack=struct.pack):
if self.bin:
self.write(BINFLOAT + pack('>d', obj))
else:
self.write(FLOAT + bytes(repr(obj)) + b'\n')
dispatch[FloatType] = save_float
dispatch[float] = save_float
def save_string(self, obj, pack=struct.pack):
if self.bin:
@ -568,7 +568,7 @@ def save_tuple(self, obj):
self.write(TUPLE)
self.memoize(obj)
dispatch[TupleType] = save_tuple
dispatch[tuple] = save_tuple
# save_empty_tuple() isn't used by anything in Python 2.3. However, I
# found a Pickler subclass in Zope3 that calls it, so it's not harmless
@ -587,7 +587,7 @@ def save_list(self, obj):
self.memoize(obj)
self._batch_appends(iter(obj))
dispatch[ListType] = save_list
dispatch[list] = save_list
# Keep in synch with cPickle's BATCHSIZE. Nothing will break if it gets
# out of synch, though.
@ -636,8 +636,8 @@ def save_dict(self, obj):
self.memoize(obj)
self._batch_setitems(iter(obj.items()))
dispatch[DictionaryType] = save_dict
if not PyStringMap is None:
dispatch[dict] = save_dict
if PyStringMap is not None:
dispatch[PyStringMap] = save_dict
def _batch_setitems(self, items):
@ -715,10 +715,9 @@ def save_global(self, obj, name=None, pack=struct.pack):
write(GLOBAL + bytes(module) + b'\n' + bytes(name) + b'\n')
self.memoize(obj)
dispatch[ClassType] = save_global
dispatch[FunctionType] = save_global
dispatch[BuiltinFunctionType] = save_global
dispatch[TypeType] = save_global
dispatch[type] = save_global
# Pickling helpers
@ -1007,7 +1006,7 @@ def _instantiate(self, klass, k):
del self.stack[k:]
instantiated = 0
if (not args and
type(klass) is ClassType and
isinstance(klass, type) and
not hasattr(klass, "__getinitargs__")):
value = _EmptyClass()
value.__class__ = klass

View file

@ -1531,7 +1531,7 @@ def __init__(self, name, code, arg,
opcode is followed by code to create setstate's argument, and then a
BUILD opcode to apply __setstate__ to that argument.
If type(callable) is not ClassType, REDUCE complains unless the
If not isinstance(callable, type), REDUCE complains unless the
callable has been registered with the copy_reg module's
safe_constructors dict, or the callable has a magic
'__safe_for_unpickling__' attribute with a true value. I'm not sure
@ -1587,9 +1587,6 @@ def __init__(self, name, code, arg,
+ The argtuple is empty (markobject was at the top of the stack
at the start).
+ It's an old-style class object (the type of the class object is
ClassType).
+ The class object does not have a __getinitargs__ attribute.
then we want to create an old-style class instance without invoking

View file

@ -13,8 +13,6 @@
#
import struct
import types
from types import *
from Carbon import AE
from Carbon.AppleEvents import *
import MacOS
@ -74,7 +72,7 @@ def pack(x, forcetype = None):
"""Pack a python object into an AE descriptor"""
if forcetype:
if type(x) is StringType:
if isinstance(x, str):
return AE.AECreateDesc(forcetype, x)
else:
return pack(x).AECoerceDesc(forcetype)
@ -90,29 +88,29 @@ def pack(x, forcetype = None):
return AE.AECreateDesc('fsrf', x.data)
if isinstance(x, AliasType):
return AE.AECreateDesc('alis', x.data)
if isinstance(x, IntType):
if isinstance(x, int):
return AE.AECreateDesc('long', struct.pack('l', x))
if isinstance(x, FloatType):
if isinstance(x, float):
return AE.AECreateDesc('doub', struct.pack('d', x))
if isinstance(x, StringType):
if isinstance(x, str):
return AE.AECreateDesc('TEXT', x)
if isinstance(x, UnicodeType):
if isinstance(x, unicode):
data = x.encode('utf16')
if data[:2] == '\xfe\xff':
data = data[2:]
return AE.AECreateDesc('utxt', data)
if isinstance(x, ListType):
if isinstance(x, list):
list = AE.AECreateList('', 0)
for item in x:
list.AEPutDesc(0, pack(item))
return list
if isinstance(x, DictionaryType):
if isinstance(x, dict):
record = AE.AECreateList('', 1)
for key, value in x.items():
packkey(record, key, value)
#record.AEPutParamDesc(key, pack(value))
return record
if type(x) == types.ClassType and issubclass(x, ObjectSpecifier):
if isinstance(x, type) and issubclass(x, ObjectSpecifier):
# Note: we are getting a class object here, not an instance
return AE.AECreateDesc('type', x.want)
if hasattr(x, '__aepack__'):
@ -340,7 +338,7 @@ def mkobject(dict):
# to __class__ is safe. Moreover, shouldn't there be a better
# initializer for the classes in the suites?
def mkobjectfrommodule(dict, modulename):
if type(dict['want']) == types.ClassType and issubclass(dict['want'], ObjectSpecifier):
if isinstance(dict['want'], type) and issubclass(dict['want'], ObjectSpecifier):
# The type has already been converted to Python. Convert back:-(
classtype = dict['want']
dict['want'] = aetypes.mktype(classtype.want)

View file

@ -2,7 +2,6 @@
from Carbon.AppleEvents import *
import struct
from types import *
#
# convoluted, since there are cyclic dependencies between this file and
@ -14,7 +13,7 @@ def pack(*args, **kwargs):
def nice(s):
"""'nice' representation of an object"""
if type(s) is StringType: return repr(s)
if isinstance(s, str): return repr(s)
else: return str(s)
class Unknown:
@ -222,7 +221,7 @@ def __repr__(self):
return "Logical(%r, %r)" % (self.logc, self.term)
def __str__(self):
if type(self.term) == ListType and len(self.term) == 2:
if isinstance(self.term, list) and len(self.term) == 2:
return "%s %s %s" % (nice(self.term[0]),
self.logc.strip(),
nice(self.term[1]))
@ -481,13 +480,13 @@ class SelectableItem(ObjectSpecifier):
def __init__(self, want, seld, fr = None):
t = type(seld)
if t == StringType:
if isinstance(t, str):
form = 'name'
elif IsRange(seld):
form = 'rang'
elif IsComparison(seld) or IsLogical(seld):
form = 'test'
elif t == TupleType:
elif isinstance(t, tuple):
# Breakout: specify both form and seld in a tuple
# (if you want ID or rele or somesuch)
form, seld = seld
@ -513,7 +512,7 @@ def __repr__(self):
def __str__(self):
seld = self.seld
if type(seld) == StringType:
if isinstance(seld, str):
ss = repr(seld)
elif IsRange(seld):
start, stop = seld.start, seld.stop

View file

@ -279,9 +279,9 @@ def decode(data, verbose=None):
def simplify(item):
"""Recursively replace singleton tuples by their constituent item"""
if type(item) is types.ListType:
if isinstance(item, list):
return map(simplify, item)
elif type(item) == types.TupleType and len(item) == 2:
elif isinstance(item, tuple) and len(item) == 2:
return simplify(item[1])
else:
return item
@ -352,7 +352,7 @@ def alt_generic(what, f, *args):
def generic(what, f, *args):
if type(what) == types.FunctionType:
return what(f, *args)
if type(what) == types.ListType:
if isinstance(what, list):
record = []
for thing in what:
item = generic(thing[:1], f, *thing[1:])

View file

@ -101,7 +101,7 @@ def __init__(self, pattern, data=None):
self.width = None
def dump(self, level=0):
nl = 1
seqtypes = type(()), type([])
seqtypes = (tuple, list)
for op, av in self.data:
print(level*" " + op, end=' '); nl = 0
if op == "in":
@ -117,7 +117,7 @@ def dump(self, level=0):
print(level*" " + "or")
a.dump(level+1); nl = 1
i = i + 1
elif type(av) in seqtypes:
elif isinstance(av, seqtypes):
for a in av:
if isinstance(a, SubPattern):
if not nl: print()
@ -709,7 +709,7 @@ def literal(literal, p=p, pappend=a):
else:
pappend((LITERAL, literal))
sep = source[:0]
if type(sep) is type(""):
if isinstance(sep, str):
makechar = chr
else:
makechar = chr

View file

@ -4103,7 +4103,8 @@ def check(expr, x, y):
N1 = sys.maxint + 1 # might trigger OverflowErrors instead of TypeErrors
N2 = sys.maxint # if sizeof(int) < sizeof(long), might trigger
# ValueErrors instead of TypeErrors
for metaclass in [type, types.ClassType]:
if 1:
metaclass = type
for name, expr, iexpr in [
('__add__', 'x + y', 'x += y'),
('__sub__', 'x - y', 'x -= y'),

View file

@ -15,7 +15,7 @@ class TestIsInstanceExceptions(unittest.TestCase):
# (leading to an "undetected error" in the debug build). Set up is,
# isinstance(inst, cls) where:
#
# - cls isn't a ClassType, a TypeType, or a TupleType
# - cls isn't a a type, or a tuple
# - cls has a __bases__ attribute
# - inst has a __class__ attribute
# - inst.__class__ as no __bases__ attribute

View file

@ -25,7 +25,7 @@
"""
import select
import os, sys, struct, types, pickle, cStringIO
import os, sys, struct, pickle, cStringIO
import socket, tempfile, threading, time
import logging, logging.handlers, logging.config
from test.test_support import run_with_locale

View file

@ -12,7 +12,6 @@
import os
import re
import copy
import types
import unittest
from StringIO import StringIO
@ -171,7 +170,7 @@ def assertOutput(self,
except InterceptedError as err:
self.assert_(
type(output) is types.StringType,
isinstance(output, str),
"expected output to be an ordinary string, not %r"
% type(output))
@ -432,18 +431,12 @@ def test_str_aliases_string(self):
self.parser.add_option("-s", type="str")
self.assertEquals(self.parser.get_option("-s").type, "string")
def test_new_type_object(self):
def test_type_object(self):
self.parser.add_option("-s", type=str)
self.assertEquals(self.parser.get_option("-s").type, "string")
self.parser.add_option("-x", type=int)
self.assertEquals(self.parser.get_option("-x").type, "int")
def test_old_type_object(self):
self.parser.add_option("-s", type=types.StringType)
self.assertEquals(self.parser.get_option("-s").type, "string")
self.parser.add_option("-x", type=types.IntType)
self.assertEquals(self.parser.get_option("-x").type, "int")
# Custom type for testing processing of default values.
_time_units = { 's' : 1, 'm' : 60, 'h' : 60*60, 'd' : 60*60*24 }
@ -1470,7 +1463,7 @@ def make_parser(self, columns):
os.environ['COLUMNS'] = orig_columns
def assertHelpEquals(self, expected_output):
if type(expected_output) is types.UnicodeType:
if isinstance(expected_output, unicode):
encoding = self.parser._get_encoding(sys.stdout)
expected_output = expected_output.encode(encoding, "replace")

View file

@ -4,7 +4,7 @@
'''
from test.test_support import run_unittest
import unittest, sys
from types import ClassType, FunctionType, MethodType, BuiltinFunctionType
from types import FunctionType, MethodType, BuiltinFunctionType
import pyclbr
from unittest import TestCase
@ -95,7 +95,7 @@ def ismethod(oclass, obj, name):
continue # skip functions that came from somewhere else
self.assertEquals(py_item.__module__, value.module)
else:
self.failUnless(isinstance(py_item, (ClassType, type)))
self.failUnless(isinstance(py_item, type))
if py_item.__module__ != moduleName:
continue # skip classes that came from somewhere else
@ -133,14 +133,14 @@ def ismethod(oclass, obj, name):
# Now check for missing stuff.
def defined_in(item, module):
if isinstance(item, ClassType):
if isinstance(item, type):
return item.__module__ == module.__name__
if isinstance(item, FunctionType):
return item.__globals__ is module.__dict__
return False
for name in dir(module):
item = getattr(module, name)
if isinstance(item, (ClassType, FunctionType)):
if isinstance(item, (type, FunctionType)):
if defined_in(item, module):
self.assertHaskey(dict, name, ignore)

View file

@ -39,7 +39,7 @@ def _g():
class _C:
def _m(self): pass
ClassType = type(_C)
ClassType = type
UnboundMethodType = type(_C._m) # Same as MethodType
MethodType = type(_C()._m)

View file

@ -412,8 +412,7 @@ def addTest(self, test):
# sanity checks
if not hasattr(test, '__call__'):
raise TypeError("the test to add must be callable")
if (isinstance(test, (type, types.ClassType)) and
issubclass(test, (TestCase, TestSuite))):
if isinstance(test, type) and issubclass(test, (TestCase, TestSuite)):
raise TypeError("TestCases and TestSuites must be instantiated "
"before passing them to addTest()")
self._tests.append(test)
@ -525,8 +524,7 @@ def loadTestsFromModule(self, module):
tests = []
for name in dir(module):
obj = getattr(module, name)
if (isinstance(obj, (type, types.ClassType)) and
issubclass(obj, TestCase)):
if isinstance(obj, type) and issubclass(obj, TestCase):
tests.append(self.loadTestsFromTestCase(obj))
return self.suiteClass(tests)
@ -556,11 +554,10 @@ def loadTestsFromName(self, name, module=None):
if type(obj) == types.ModuleType:
return self.loadTestsFromModule(obj)
elif (isinstance(obj, (type, types.ClassType)) and
issubclass(obj, TestCase)):
elif isinstance(obj, type) and issubclass(obj, TestCase):
return self.loadTestsFromTestCase(obj)
elif (type(obj) == types.UnboundMethodType and
isinstance(parent, (type, types.ClassType)) and
elif (isinstance(obj, types.UnboundMethodType) and
isinstance(parent, type) and
issubclass(parent, TestCase)):
return TestSuite([parent(obj.__name__)])
elif isinstance(obj, TestSuite):
@ -816,7 +813,7 @@ def createTests(self):
self.module)
def runTests(self):
if isinstance(self.testRunner, (type, types.ClassType)):
if isinstance(self.testRunner, type):
try:
testRunner = self.testRunner(verbosity=self.verbosity)
except TypeError:

View file

@ -428,9 +428,8 @@ def build_opener(*handlers):
If any of the handlers passed as arguments are subclasses of the
default handlers, the default handlers will not be used.
"""
import types
def isclass(obj):
return isinstance(obj, types.ClassType) or hasattr(obj, "__bases__")
return isinstance(obj, type) or hasattr(obj, "__bases__")
opener = OpenerDirector()
default_classes = [ProxyHandler, UnknownHandler, HTTPHandler,

View file

@ -3,7 +3,7 @@
# Note: function level imports should *not* be used
# in this module as it may cause import lock deadlock.
# See bug 683658.
import sys, types
import sys
import linecache
__all__ = ["warn", "showwarning", "formatwarning", "filterwarnings",
@ -151,8 +151,7 @@ def filterwarnings(action, message="", category=Warning, module="", lineno=0,
assert action in ("error", "ignore", "always", "default", "module",
"once"), "invalid action: %r" % (action,)
assert isinstance(message, basestring), "message must be a string"
assert isinstance(category, (type, types.ClassType)), \
"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 isinstance(module, basestring), "module must be a string"
assert isinstance(lineno, int) and lineno >= 0, \

View file

@ -5,8 +5,6 @@
written by Barry Warsaw.
"""
from types import ListType, TupleType
# Regular expression that matches `special' characters in parameters, the
# existance of which force quoting of the parameter value.
import re
@ -44,7 +42,7 @@ class Headers:
"""Manage a collection of HTTP response headers"""
def __init__(self,headers):
if type(headers) is not ListType:
if not isinstance(headers, list):
raise TypeError("Headers must be a list of name/value tuples")
self._headers = headers

View file

@ -113,7 +113,6 @@
import re
import sys
from types import DictType, StringType, TupleType, ListType
import warnings
header_re = re.compile(r'^[a-zA-Z][a-zA-Z0-9\-_]*$')
@ -191,20 +190,20 @@ def __init__(self, wsgi_input):
def read(self, *args):
assert_(len(args) <= 1)
v = self.input.read(*args)
assert_(type(v) is type(""))
assert_(isinstance(v, str))
return v
def readline(self):
v = self.input.readline()
assert_(type(v) is type(""))
assert_(isinstance(v, str))
return v
def readlines(self, *args):
assert_(len(args) <= 1)
lines = self.input.readlines(*args)
assert_(type(lines) is type([]))
assert_(isinstance(lines, list))
for line in lines:
assert_(type(line) is type(""))
assert_(isinstance(line, str))
return lines
def __iter__(self):
@ -223,7 +222,7 @@ def __init__(self, wsgi_errors):
self.errors = wsgi_errors
def write(self, s):
assert_(type(s) is type(""))
assert_(isinstance(s, str))
self.errors.write(s)
def flush(self):
@ -242,7 +241,7 @@ def __init__(self, wsgi_writer):
self.writer = wsgi_writer
def __call__(self, s):
assert_(type(s) is type(""))
assert_(isinstance(s, str))
self.writer(s)
class PartialIteratorWrapper:
@ -288,7 +287,7 @@ def __del__(self):
"Iterator garbage collected without being closed")
def check_environ(environ):
assert_(type(environ) is DictType,
assert_(isinstance(environ, dict),
"Environment is not of the right type: %r (environment: %r)"
% (type(environ), environ))
@ -315,11 +314,11 @@ def check_environ(environ):
if '.' in key:
# Extension, we don't care about its type
continue
assert_(type(environ[key]) is StringType,
assert_(isinstance(environ[key], str),
"Environmental variable %s is not a string: %r (value: %r)"
% (key, type(environ[key]), environ[key]))
assert_(type(environ['wsgi.version']) is TupleType,
assert_(isinstance(environ['wsgi.version'], tuple),
"wsgi.version should be a tuple (%r)" % (environ['wsgi.version'],))
assert_(environ['wsgi.url_scheme'] in ('http', 'https'),
"wsgi.url_scheme unknown: %r" % environ['wsgi.url_scheme'])
@ -365,7 +364,7 @@ def check_errors(wsgi_errors):
% (wsgi_errors, attr))
def check_status(status):
assert_(type(status) is StringType,
assert_(isinstance(status, str),
"Status must be a string (not %r)" % status)
# Implicitly check that we can turn it into an integer:
status_code = status.split(None, 1)[0]
@ -380,12 +379,12 @@ def check_status(status):
% status, WSGIWarning)
def check_headers(headers):
assert_(type(headers) is ListType,
assert_(isinstance(headers, list),
"Headers (%r) must be of type list: %r"
% (headers, type(headers)))
header_names = {}
for item in headers:
assert_(type(item) is TupleType,
assert_(isinstance(item, tuple),
"Individual headers (%r) must be of type tuple: %r"
% (item, type(item)))
assert_(len(item) == 2)
@ -419,7 +418,7 @@ def check_content_type(status, headers):
assert_(0, "No Content-Type header found in headers (%s)" % headers)
def check_exc_info(exc_info):
assert_(exc_info is None or type(exc_info) is type(()),
assert_(exc_info is None or isinstance(exc_info, tuple),
"exc_info (%r) is not a tuple: %r" % (exc_info, type(exc_info)))
# More exc_info checks?

View file

@ -3,18 +3,10 @@
convenience of application and driver writers.
"""
import os, urlparse, urllib, types
import os, urlparse, urllib
from . import handler
from . import xmlreader
try:
_StringTypes = [types.StringType, types.UnicodeType]
except AttributeError:
try:
_StringTypes = [types.StringType]
except AttributeError:
_StringTypes = [str]
# See whether the xmlcharrefreplace error handler is
# supported
try:
@ -280,7 +272,7 @@ def prepare_input_source(source, base = ""):
"""This function takes an InputSource and an optional base URL and
returns a fully resolved InputSource object ready for reading."""
if type(source) in _StringTypes:
if isinstance(source, basestring):
source = xmlreader.InputSource(source)
elif hasattr(source, "read"):
f = source

View file

@ -138,8 +138,6 @@
import re, time, operator
from types import *
# --------------------------------------------------------------------
# Internal stuff
@ -306,7 +304,7 @@ def __init__(self, value=0):
today = datetime.datetime.now().strftime("%Y%m%d")
self.value = value.strftime(today+"T%H:%M:%S")
return
if not isinstance(value, (TupleType, time.struct_time)):
if not isinstance(value, (tuple, time.struct_time)):
if value == 0:
value = time.time()
value = time.localtime(value)
@ -580,7 +578,7 @@ def dump_nil (self, value, write):
if not self.allow_none:
raise TypeError, "cannot marshal None unless allow_none is enabled"
write("<value><nil/></value>")
dispatch[NoneType] = dump_nil
dispatch[type(None)] = dump_nil
def dump_int(self, value, write):
# in case ints are > 32 bits
@ -589,7 +587,7 @@ def dump_int(self, value, write):
write("<value><int>")
write(str(value))
write("</int></value>\n")
dispatch[IntType] = dump_int
#dispatch[int] = dump_int
if _bool_is_builtin:
def dump_bool(self, value, write):
@ -604,13 +602,13 @@ def dump_long(self, value, write):
write("<value><int>")
write(str(int(value)))
write("</int></value>\n")
dispatch[LongType] = dump_long
dispatch[int] = dump_long
def dump_double(self, value, write):
write("<value><double>")
write(repr(value))
write("</double></value>\n")
dispatch[FloatType] = dump_double
dispatch[float] = dump_double
def dump_string(self, value, write, escape=escape):
write("<value><string>")
@ -636,8 +634,8 @@ def dump_array(self, value, write):
dump(v, write)
write("</data></array></value>\n")
del self.memo[i]
dispatch[TupleType] = dump_array
dispatch[ListType] = dump_array
dispatch[tuple] = dump_array
dispatch[list] = dump_array
def dump_struct(self, value, write, escape=escape):
i = id(value)
@ -657,7 +655,7 @@ def dump_struct(self, value, write, escape=escape):
write("</member>\n")
write("</struct></value>\n")
del self.memo[i]
dispatch[DictType] = dump_struct
dispatch[dict] = dump_struct
if datetime:
def dump_datetime(self, value, write):
@ -1005,12 +1003,10 @@ def dumps(params, methodname=None, methodresponse=None, encoding=None,
where necessary.
"""
assert isinstance(params, TupleType) or isinstance(params, Fault),\
"argument must be tuple or Fault instance"
assert isinstance(params, (tuple, Fault)), "argument must be tuple or Fault instance"
if isinstance(params, Fault):
methodresponse = 1
elif methodresponse and isinstance(params, TupleType):
elif methodresponse and isinstance(params, tuple):
assert len(params) == 1, "response tuple must be a singleton"
if not encoding:
@ -1166,7 +1162,7 @@ def getparser(self):
def get_host_info(self, host):
x509 = {}
if isinstance(host, TupleType):
if isinstance(host, tuple):
host, x509 = host
import urllib
@ -1216,7 +1212,7 @@ def send_host(self, connection, host):
host, extra_headers, x509 = self.get_host_info(host)
connection.putheader("Host", host)
if extra_headers:
if isinstance(extra_headers, DictType):
if isinstance(extra_headers, dict):
extra_headers = extra_headers.items()
for key, value in extra_headers:
connection.putheader(key, value)

View file

@ -1,5 +1,4 @@
"""pyversioncheck - Module to help with checking versions"""
import types
import rfc822
import urllib
import sys
@ -35,7 +34,7 @@ def versioncheck(package, url, version, verbose=0):
def checkonly(package, url, version, verbose=0):
if verbose >= VERBOSE_EACHFILE:
print '%s:'%package
if type(url) == types.StringType:
if isinstance(url, str):
ok, newversion, fp = _check1version(package, url, version, verbose)
else:
for u in url: