From f715366f23f47832a4b9914c54d5a63b19f17eba Mon Sep 17 00:00:00 2001 From: Raymond Hettinger Date: Mon, 7 Feb 2005 14:16:21 +0000 Subject: Reduce the usage of the types module. --- Lib/DocXMLRPCServer.py | 3 +-- Lib/cookielib.py | 3 +-- Lib/copy.py | 28 ++++++++++++++-------------- Lib/optparse.py | 11 +++++------ Lib/pickle.py | 30 +++++++++++++++--------------- Lib/subprocess.py | 17 ++++++++--------- Lib/unittest.py | 2 +- Lib/xmlrpclib.py | 38 +++++++++++++++++++------------------- 8 files changed, 64 insertions(+), 68 deletions(-) diff --git a/Lib/DocXMLRPCServer.py b/Lib/DocXMLRPCServer.py index 20958b2..259fb18 100644 --- a/Lib/DocXMLRPCServer.py +++ b/Lib/DocXMLRPCServer.py @@ -12,7 +12,6 @@ modules. import pydoc import inspect -import types import re import sys @@ -92,7 +91,7 @@ class ServerHTMLDoc(pydoc.HTMLDoc): else: argspec = '(...)' - if isinstance(object, types.TupleType): + if isinstance(object, tuple): argspec = object[0] or argspec docstring = object[1] or "" else: diff --git a/Lib/cookielib.py b/Lib/cookielib.py index 268cc20..7fec858 100644 --- a/Lib/cookielib.py +++ b/Lib/cookielib.py @@ -26,7 +26,6 @@ are available from http://wwwsearch.sf.net/): """ import sys, re, urlparse, copy, time, urllib, logging -from types import StringTypes try: import threading as _threading except ImportError: @@ -359,7 +358,7 @@ def split_header_words(header_values): [[('Basic', None), ('realm', '"foobar"')]] """ - assert type(header_values) not in StringTypes + assert not isinstance(header_values, basestring) result = [] for text in header_values: orig_text = text diff --git a/Lib/copy.py b/Lib/copy.py index af905f3..b216beb 100644 --- a/Lib/copy.py +++ b/Lib/copy.py @@ -99,7 +99,7 @@ _copy_dispatch = d = {} def _copy_immutable(x): return x -for t in (types.NoneType, int, long, float, bool, str, tuple, +for t in (type(None), int, long, float, bool, str, tuple, frozenset, type, xrange, types.ClassType, types.BuiltinFunctionType): d[t] = _copy_immutable @@ -195,26 +195,26 @@ _deepcopy_dispatch = d = {} def _deepcopy_atomic(x, memo): return x -d[types.NoneType] = _deepcopy_atomic -d[types.IntType] = _deepcopy_atomic -d[types.LongType] = _deepcopy_atomic -d[types.FloatType] = _deepcopy_atomic -d[types.BooleanType] = _deepcopy_atomic +d[type(None)] = _deepcopy_atomic +d[int] = _deepcopy_atomic +d[long] = _deepcopy_atomic +d[float] = _deepcopy_atomic +d[bool] = _deepcopy_atomic try: - d[types.ComplexType] = _deepcopy_atomic + d[complex] = _deepcopy_atomic except AttributeError: pass -d[types.StringType] = _deepcopy_atomic +d[str] = _deepcopy_atomic try: - d[types.UnicodeType] = _deepcopy_atomic + d[unicode] = _deepcopy_atomic except AttributeError: pass try: d[types.CodeType] = _deepcopy_atomic except AttributeError: pass -d[types.TypeType] = _deepcopy_atomic -d[types.XRangeType] = _deepcopy_atomic +d[type] = _deepcopy_atomic +d[xrange] = _deepcopy_atomic d[types.ClassType] = _deepcopy_atomic d[types.BuiltinFunctionType] = _deepcopy_atomic @@ -224,7 +224,7 @@ def _deepcopy_list(x, memo): for a in x: y.append(deepcopy(a, memo)) return y -d[types.ListType] = _deepcopy_list +d[list] = _deepcopy_list def _deepcopy_tuple(x, memo): y = [] @@ -243,7 +243,7 @@ def _deepcopy_tuple(x, memo): y = x memo[d] = y return y -d[types.TupleType] = _deepcopy_tuple +d[tuple] = _deepcopy_tuple def _deepcopy_dict(x, memo): y = {} @@ -251,7 +251,7 @@ def _deepcopy_dict(x, memo): for key, value in x.iteritems(): y[deepcopy(key, memo)] = deepcopy(value, memo) return y -d[types.DictionaryType] = _deepcopy_dict +d[dict] = _deepcopy_dict if PyStringMap is not None: d[PyStringMap] = _deepcopy_dict diff --git a/Lib/optparse.py b/Lib/optparse.py index 6d3c94b..ae3d00d 100644 --- a/Lib/optparse.py +++ b/Lib/optparse.py @@ -67,7 +67,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ import sys, os -import types import textwrap try: from gettext import gettext as _ @@ -590,7 +589,7 @@ class Option: 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 type(self.choices) not in (tuple, list): raise OptionError( "choices must be a list of strings ('%s' supplied)" % str(type(self.choices)).split("'")[1], self) @@ -634,12 +633,12 @@ class Option: 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): + type(self.callback_args) is not 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): + type(self.callback_kwargs) is not dict): raise OptionError( "callback_kwargs, if supplied, must be a dict: not %r" % self.callback_kwargs, self) @@ -927,7 +926,7 @@ class OptionContainer: """add_option(Option) add_option(opt_str, ..., kwarg=val, ...) """ - if type(args[0]) is types.StringType: + if type(args[0]) is str: option = self.option_class(*args, **kwargs) elif len(args) == 1 and not kwargs: option = args[0] @@ -1213,7 +1212,7 @@ class OptionParser (OptionContainer): def add_option_group(self, *args, **kwargs): # XXX lots of overlap with OptionContainer.add_option() - if type(args[0]) is types.StringType: + if type(args[0]) is str: group = OptionGroup(self, *args, **kwargs) elif len(args) == 1 and not kwargs: group = args[0] diff --git a/Lib/pickle.py b/Lib/pickle.py index 02a1b1d..2ac920e 100644 --- a/Lib/pickle.py +++ b/Lib/pickle.py @@ -288,7 +288,7 @@ class Pickler: # 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,12 +313,12 @@ class Pickler: (t.__name__, obj)) # Check for string returned by reduce(), meaning "save as global" - if type(rv) is StringType: + if type(rv) is str: self.save_global(obj, rv) return # Assert that reduce() returned a tuple - if type(rv) is not TupleType: + if type(rv) is not tuple: raise PicklingError("%s must return string or tuple" % reduce) # Assert that it returned an appropriately sized tuple @@ -347,7 +347,7 @@ class Pickler: # 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 @@ -425,7 +425,7 @@ class Pickler: 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: @@ -456,7 +456,7 @@ class Pickler: return # Text pickle, or int too big to fit in signed 4-byte format. self.write(INT + repr(obj) + '\n') - dispatch[IntType] = save_int + dispatch[int] = save_int def save_long(self, obj, pack=struct.pack): if self.proto >= 2: @@ -468,14 +468,14 @@ class Pickler: self.write(LONG4 + pack("d', obj)) else: self.write(FLOAT + repr(obj) + '\n') - dispatch[FloatType] = save_float + dispatch[float] = save_float def save_string(self, obj, pack=struct.pack): if self.bin: @@ -487,7 +487,7 @@ class Pickler: else: self.write(STRING + repr(obj) + '\n') self.memoize(obj) - dispatch[StringType] = save_string + dispatch[str] = save_string def save_unicode(self, obj, pack=struct.pack): if self.bin: @@ -501,7 +501,7 @@ class Pickler: self.memoize(obj) dispatch[UnicodeType] = save_unicode - if StringType == UnicodeType: + if str == UnicodeType: # This is true for Jython def save_string(self, obj, pack=struct.pack): unicode = obj.isunicode() @@ -527,7 +527,7 @@ class Pickler: else: self.write(STRING + repr(obj) + '\n') self.memoize(obj) - dispatch[StringType] = save_string + dispatch[str] = save_string def save_tuple(self, obj): write = self.write @@ -580,7 +580,7 @@ class Pickler: 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 @@ -599,7 +599,7 @@ class Pickler: 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. @@ -648,7 +648,7 @@ class Pickler: self.memoize(obj) self._batch_setitems(obj.iteritems()) - dispatch[DictionaryType] = save_dict + dispatch[dict] = save_dict if not PyStringMap is None: dispatch[PyStringMap] = save_dict @@ -770,7 +770,7 @@ class Pickler: dispatch[ClassType] = save_global dispatch[FunctionType] = save_global dispatch[BuiltinFunctionType] = save_global - dispatch[TypeType] = save_global + dispatch[type] = save_global # Pickling helpers diff --git a/Lib/subprocess.py b/Lib/subprocess.py index 5d0c5e6..da63148 100644 --- a/Lib/subprocess.py +++ b/Lib/subprocess.py @@ -372,7 +372,6 @@ import sys mswindows = (sys.platform == "win32") import os -import types import traceback # Exception classes used by this module. @@ -638,7 +637,7 @@ class Popen(object): # Detach and turn into fd p2cwrite = p2cwrite.Detach() p2cwrite = msvcrt.open_osfhandle(p2cwrite, 0) - elif type(stdin) == types.IntType: + elif type(stdin) == int: p2cread = msvcrt.get_osfhandle(stdin) else: # Assuming file-like object @@ -652,7 +651,7 @@ class Popen(object): # Detach and turn into fd c2pread = c2pread.Detach() c2pread = msvcrt.open_osfhandle(c2pread, 0) - elif type(stdout) == types.IntType: + elif type(stdout) == int: c2pwrite = msvcrt.get_osfhandle(stdout) else: # Assuming file-like object @@ -668,7 +667,7 @@ class Popen(object): errread = msvcrt.open_osfhandle(errread, 0) elif stderr == STDOUT: errwrite = c2pwrite - elif type(stderr) == types.IntType: + elif type(stderr) == int: errwrite = msvcrt.get_osfhandle(stderr) else: # Assuming file-like object @@ -711,7 +710,7 @@ class Popen(object): errread, errwrite): """Execute program (MS Windows version)""" - if not isinstance(args, types.StringTypes): + if not isinstance(args, basestring): args = list2cmdline(args) # Process startup details @@ -876,7 +875,7 @@ class Popen(object): pass elif stdin == PIPE: p2cread, p2cwrite = os.pipe() - elif type(stdin) == types.IntType: + elif type(stdin) == int: p2cread = stdin else: # Assuming file-like object @@ -886,7 +885,7 @@ class Popen(object): pass elif stdout == PIPE: c2pread, c2pwrite = os.pipe() - elif type(stdout) == types.IntType: + elif type(stdout) == int: c2pwrite = stdout else: # Assuming file-like object @@ -898,7 +897,7 @@ class Popen(object): errread, errwrite = os.pipe() elif stderr == STDOUT: errwrite = c2pwrite - elif type(stderr) == types.IntType: + elif type(stderr) == int: errwrite = stderr else: # Assuming file-like object @@ -937,7 +936,7 @@ class Popen(object): errread, errwrite): """Execute program (POSIX version)""" - if isinstance(args, types.StringTypes): + if isinstance(args, basestring): args = [args] if shell: diff --git a/Lib/unittest.py b/Lib/unittest.py index efb2b02..3f2d653 100644 --- a/Lib/unittest.py +++ b/Lib/unittest.py @@ -71,7 +71,7 @@ if sys.version_info[:2] < (2, 2): False, True = 0, 1 def isinstance(obj, clsinfo): import __builtin__ - if type(clsinfo) in (types.TupleType, types.ListType): + if type(clsinfo) in (tuple, list): for cls in clsinfo: if cls is type: cls = types.ClassType if __builtin__.isinstance(obj, cls): diff --git a/Lib/xmlrpclib.py b/Lib/xmlrpclib.py index 7b68196..4d3305a 100644 --- a/Lib/xmlrpclib.py +++ b/Lib/xmlrpclib.py @@ -138,7 +138,7 @@ Exported functions: import re, string, time, operator -from types import * +from types import InstanceType # -------------------------------------------------------------------- # Internal stuff @@ -348,8 +348,8 @@ class DateTime: """ def __init__(self, value=0): - if not isinstance(value, StringType): - if not isinstance(value, (TupleType, time.struct_time)): + if not isinstance(value, str): + if not isinstance(value, (tuple, time.struct_time)): if value == 0: value = time.time() value = time.localtime(value) @@ -618,7 +618,7 @@ class Marshaller: if not self.allow_none: raise TypeError, "cannot marshal None unless allow_none is enabled" write("") - dispatch[NoneType] = dump_nil + dispatch[type(None)] = dump_nil def dump_int(self, value, write): # in case ints are > 32 bits @@ -627,7 +627,7 @@ class Marshaller: write("") write(str(value)) write("\n") - dispatch[IntType] = dump_int + dispatch[int] = dump_int if _bool_is_builtin: def dump_bool(self, value, write): @@ -642,19 +642,19 @@ class Marshaller: write("") write(str(int(value))) write("\n") - dispatch[LongType] = dump_long + dispatch[long] = dump_long def dump_double(self, value, write): write("") write(repr(value)) write("\n") - dispatch[FloatType] = dump_double + dispatch[float] = dump_double def dump_string(self, value, write, escape=escape): write("") write(escape(value)) write("\n") - dispatch[StringType] = dump_string + dispatch[str] = dump_string if unicode: def dump_unicode(self, value, write, escape=escape): @@ -662,7 +662,7 @@ class Marshaller: write("") write(escape(value)) write("\n") - dispatch[UnicodeType] = dump_unicode + dispatch[unicode] = dump_unicode def dump_array(self, value, write): i = id(value) @@ -675,8 +675,8 @@ class Marshaller: dump(v, write) write("\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) @@ -687,8 +687,8 @@ class Marshaller: write("\n") for k, v in value.items(): write("\n") - if type(k) is not StringType: - if unicode and type(k) is UnicodeType: + if type(k) is not str: + if unicode and type(k) is unicode: k = k.encode(self.encoding) else: raise TypeError, "dictionary key must be string" @@ -697,7 +697,7 @@ class Marshaller: write("\n") write("\n") del self.memo[i] - dispatch[DictType] = dump_struct + dispatch[dict] = dump_struct def dump_instance(self, value, write): # check for special wrappers @@ -1010,12 +1010,12 @@ def dumps(params, methodname=None, methodresponse=None, encoding=None, where necessary. """ - assert isinstance(params, TupleType) or isinstance(params, Fault),\ + assert isinstance(params, tuple) or isinstance(params, 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: @@ -1036,7 +1036,7 @@ def dumps(params, methodname=None, methodresponse=None, encoding=None, # standard XML-RPC wrappings if methodname: # a method call - if not isinstance(methodname, StringType): + if not isinstance(methodname, str): methodname = methodname.encode(encoding) data = ( xmlheader, @@ -1168,7 +1168,7 @@ class Transport: def get_host_info(self, host): x509 = {} - if isinstance(host, TupleType): + if isinstance(host, tuple): host, x509 = host import urllib @@ -1218,7 +1218,7 @@ class Transport: 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) -- cgit v0.12