PEP8 remove direct type comparisons

Fixes bug #910763

According to PEP8,
- Object type comparisons should always use isinstance() instead
      of comparing types directly.

        Yes: if isinstance(obj, int):

        No: if type(obj) is type(1):

      When checking if an object is a string, keep in mind that it might be a
      unicode string too! In Python 2.3, str and unicode have a common base
      class, basestring, so you can do:

        if isinstance(obj, basestring):

Change-Id: I7c0fdecf99872f5b8f72b2c2ed4f5c539c33def1
This commit is contained in:
lzyeval 2012-01-02 17:31:36 +08:00
parent ea21fe6965
commit ae1654bc59
18 changed files with 31 additions and 35 deletions

View File

@ -1084,7 +1084,7 @@ class ServiceCommands(object):
{"method": "show_host_resources", {"method": "show_host_resources",
"args": {"host": host}}) "args": {"host": host}})
if type(result) != dict: if not isinstance(result, dict):
print _('An unexpected error has occurred.') print _('An unexpected error has occurred.')
print _('[Result]'), result print _('[Result]'), result
else: else:

View File

@ -285,7 +285,7 @@ class ServiceWrapper(object):
params = dict([(str(k), v) for (k, v) in params.iteritems()]) params = dict([(str(k), v) for (k, v) in params.iteritems()])
result = method(context, **params) result = method(context, **params)
if result is None or type(result) is str or type(result) is unicode: if result is None or isinstance(result, basestring):
return result return result
try: try:

View File

@ -812,7 +812,7 @@ class CloudController(object):
LOG.audit(_("Get console output for instance %s"), instance_id, LOG.audit(_("Get console output for instance %s"), instance_id,
context=context) context=context)
# instance_id may be passed in as a list of instances # instance_id may be passed in as a list of instances
if type(instance_id) == list: if isinstance(instance_id, list):
ec2_id = instance_id[0] ec2_id = instance_id[0]
else: else:
ec2_id = instance_id ec2_id = instance_id

View File

@ -366,7 +366,7 @@ class XMLDictSerializer(DictSerializer):
result.setAttribute('xmlns', xmlns) result.setAttribute('xmlns', xmlns)
#TODO(bcwaldon): accomplish this without a type-check #TODO(bcwaldon): accomplish this without a type-check
if type(data) is list: if isinstance(data, list):
collections = metadata.get('list_collections', {}) collections = metadata.get('list_collections', {})
if nodename in collections: if nodename in collections:
metadata = collections[nodename] metadata = collections[nodename]
@ -385,7 +385,7 @@ class XMLDictSerializer(DictSerializer):
node = self._to_xml_node(doc, metadata, singular, item) node = self._to_xml_node(doc, metadata, singular, item)
result.appendChild(node) result.appendChild(node)
#TODO(bcwaldon): accomplish this without a type-check #TODO(bcwaldon): accomplish this without a type-check
elif type(data) is dict: elif isinstance(data, dict):
collections = metadata.get('dict_collections', {}) collections = metadata.get('dict_collections', {})
if nodename in collections: if nodename in collections:
metadata = collections[nodename] metadata = collections[nodename]
@ -573,7 +573,7 @@ class Resource(wsgi.Application):
LOG.info(_("HTTP exception thrown: %s"), unicode(ex)) LOG.info(_("HTTP exception thrown: %s"), unicode(ex))
action_result = Fault(ex) action_result = Fault(ex)
if type(action_result) is dict or action_result is None: if isinstance(action_result, dict) or action_result is None:
response = self.serializer.serialize(request, response = self.serializer.serialize(request,
action_result, action_result,
accept, accept,

View File

@ -29,7 +29,7 @@ XMLNS_ATOM = 'http://www.w3.org/2005/Atom'
def validate_schema(xml, schema_name): def validate_schema(xml, schema_name):
if type(xml) is str: if isinstance(xml, str):
xml = etree.fromstring(xml) xml = etree.fromstring(xml)
base_path = 'nova/api/openstack/v2/schemas/v1.1/' base_path = 'nova/api/openstack/v2/schemas/v1.1/'
if schema_name in ('atom', 'atom-link'): if schema_name in ('atom', 'atom-link'):

View File

@ -85,7 +85,7 @@ def _clean(attr):
"""Clean attr for insertion into ldap""" """Clean attr for insertion into ldap"""
if attr is None: if attr is None:
return None return None
if type(attr) is unicode: if isinstance(attr, unicode):
return str(attr) return str(attr)
return attr return attr

View File

@ -962,9 +962,9 @@ class ConfigOpts(object):
:param value: the string value, or list of string values :param value: the string value, or list of string values
:returns: the substituted string(s) :returns: the substituted string(s)
""" """
if type(value) is list: if isinstance(value, list):
return [self._substitute(i) for i in value] return [self._substitute(i) for i in value]
elif type(value) is str: elif isinstance(value, str):
tmpl = string.Template(value) tmpl = string.Template(value)
return tmpl.safe_substitute(self.StrSubWrapper(self)) return tmpl.safe_substitute(self.StrSubWrapper(self))
else: else:

View File

@ -17,7 +17,6 @@
import json import json
import netaddr import netaddr
import types
from nova import exception from nova import exception
@ -247,7 +246,7 @@ class NetworkInfo(list):
@classmethod @classmethod
def hydrate(cls, network_info): def hydrate(cls, network_info):
if isinstance(network_info, types.StringTypes): if isinstance(network_info, basestring):
network_info = json.loads(network_info) network_info = json.loads(network_info)
return NetworkInfo([VIF.hydrate(vif) for vif in network_info]) return NetworkInfo([VIF.hydrate(vif) for vif in network_info])

View File

@ -155,7 +155,7 @@ class Client(object):
action = Client.action_prefix + action action = Client.action_prefix + action
action = action.replace('{tenant_id}', self.tenant) action = action.replace('{tenant_id}', self.tenant)
if type(params) is dict: if isinstance(params, dict):
action += '?' + urllib.urlencode(params) action += '?' + urllib.urlencode(params)
try: try:
@ -219,7 +219,7 @@ class Client(object):
def serialize(self, data): def serialize(self, data):
if not data: if not data:
return None return None
elif type(data) is dict: elif isinstance(data, dict):
return JSONSerializer().serialize(data, self.content_type()) return JSONSerializer().serialize(data, self.content_type())
else: else:
raise Exception(_("unable to deserialize object of type = '%s'" % raise Exception(_("unable to deserialize object of type = '%s'" %

View File

@ -24,11 +24,11 @@ No fan-out support yet.
""" """
import inspect
import json import json
import sys import sys
import time import time
import traceback import traceback
import types
import uuid import uuid
from carrot import connection as carrot_connection from carrot import connection as carrot_connection
@ -284,7 +284,7 @@ class AdapterConsumer(Consumer):
try: try:
rval = node_func(context=ctxt, **node_args) rval = node_func(context=ctxt, **node_args)
# Check if the result was a generator # Check if the result was a generator
if isinstance(rval, types.GeneratorType): if inspect.isgenerator(rval):
for x in rval: for x in rval:
ctxt.reply(x, None) ctxt.reply(x, None)
else: else:

View File

@ -17,9 +17,9 @@
queues. Casts will block, but this is very useful for tests. queues. Casts will block, but this is very useful for tests.
""" """
import inspect
import sys import sys
import traceback import traceback
import types
from nova import context from nova import context
from nova.rpc import common as rpc_common from nova.rpc import common as rpc_common
@ -60,7 +60,7 @@ class Consumer(object):
# if ending not 'sent'...we might have more data to # if ending not 'sent'...we might have more data to
# return from the function itself # return from the function itself
if not ctxt._done: if not ctxt._done:
if isinstance(rval, types.GeneratorType): if inspect.isgenerator(rval):
for val in rval: for val in rval:
yield val yield val
else: else:

View File

@ -18,11 +18,11 @@ import kombu
import kombu.entity import kombu.entity
import kombu.messaging import kombu.messaging
import kombu.connection import kombu.connection
import inspect
import itertools import itertools
import sys import sys
import time import time
import traceback import traceback
import types
import uuid import uuid
import eventlet import eventlet
@ -651,7 +651,7 @@ class ProxyCallback(object):
try: try:
rval = node_func(context=ctxt, **node_args) rval = node_func(context=ctxt, **node_args)
# Check if the result was a generator # Check if the result was a generator
if isinstance(rval, types.GeneratorType): if inspect.isgenerator(rval):
for x in rval: for x in rval:
ctxt.reply(x, None) ctxt.reply(x, None)
else: else:

View File

@ -21,7 +21,6 @@ Weighing Functions.
import json import json
import operator import operator
import types
import M2Crypto import M2Crypto
@ -358,7 +357,7 @@ class DistributedScheduler(driver.Scheduler):
return getattr(filters, nm) return getattr(filters, nm)
return [get_itm(itm) for itm in dir(filters) return [get_itm(itm) for itm in dir(filters)
if (type(get_itm(itm)) is types.TypeType) if isinstance(get_itm(itm), type)
and issubclass(get_itm(itm), filters.AbstractHostFilter) and issubclass(get_itm(itm), filters.AbstractHostFilter)
and get_itm(itm) is not filters.AbstractHostFilter] and get_itm(itm) is not filters.AbstractHostFilter]

View File

@ -140,7 +140,7 @@ class ReadOnlyDict(UserDict.IterableUserDict):
return return
elif isinstance(source, UserDict.UserDict): elif isinstance(source, UserDict.UserDict):
self.data = source.data self.data = source.data
elif isinstance(source, type({})): elif isinstance(source, dict):
self.data = source self.data = source
else: else:
raise TypeError raise TypeError

View File

@ -17,7 +17,6 @@
"""This modules stubs out functions in nova.utils.""" """This modules stubs out functions in nova.utils."""
import re import re
import types
from eventlet import greenthread from eventlet import greenthread

View File

@ -33,7 +33,6 @@ import socket
import struct import struct
import sys import sys
import time import time
import types
import uuid import uuid
import pyclbr import pyclbr
from xml.sax import saxutils from xml.sax import saxutils
@ -176,11 +175,11 @@ def execute(*cmd, **kwargs):
process_input = kwargs.pop('process_input', None) process_input = kwargs.pop('process_input', None)
check_exit_code = kwargs.pop('check_exit_code', [0]) check_exit_code = kwargs.pop('check_exit_code', [0])
ignore_exit_code = False ignore_exit_code = False
if type(check_exit_code) == int: if isinstance(check_exit_code, bool):
check_exit_code = [check_exit_code]
elif type(check_exit_code) == bool:
ignore_exit_code = not check_exit_code ignore_exit_code = not check_exit_code
check_exit_code = [0] check_exit_code = [0]
elif isinstance(check_exit_code, int):
check_exit_code = [check_exit_code]
delay_on_retry = kwargs.pop('delay_on_retry', True) delay_on_retry = kwargs.pop('delay_on_retry', True)
attempts = kwargs.pop('attempts', 1) attempts = kwargs.pop('attempts', 1)
run_as_root = kwargs.pop('run_as_root', False) run_as_root = kwargs.pop('run_as_root', False)
@ -569,7 +568,7 @@ class LazyPluggable(object):
raise exception.Error(_('Invalid backend: %s') % backend_name) raise exception.Error(_('Invalid backend: %s') % backend_name)
backend = self.__backends[backend_name] backend = self.__backends[backend_name]
if type(backend) == type(tuple()): if isinstance(backend, tuple):
name = backend[0] name = backend[0]
fromlist = backend[1] fromlist = backend[1]
else: else:
@ -696,13 +695,13 @@ def to_primitive(value, convert_instances=False, level=0):
# The try block may not be necessary after the class check above, # The try block may not be necessary after the class check above,
# but just in case ... # but just in case ...
try: try:
if type(value) is type([]) or type(value) is type((None,)): if isinstance(value, (list, tuple)):
o = [] o = []
for v in value: for v in value:
o.append(to_primitive(v, convert_instances=convert_instances, o.append(to_primitive(v, convert_instances=convert_instances,
level=level)) level=level))
return o return o
elif type(value) is type({}): elif isinstance(value, dict):
o = {} o = {}
for k, v in value.iteritems(): for k, v in value.iteritems():
o[k] = to_primitive(v, convert_instances=convert_instances, o[k] = to_primitive(v, convert_instances=convert_instances,
@ -858,7 +857,7 @@ def get_from_path(items, path):
if items is None: if items is None:
return results return results
if not isinstance(items, types.ListType): if not isinstance(items, list):
# Wrap single objects in a list # Wrap single objects in a list
items = [items] items = [items]
@ -871,7 +870,7 @@ def get_from_path(items, path):
child = get_method(first_token) child = get_method(first_token)
if child is None: if child is None:
continue continue
if isinstance(child, types.ListType): if isinstance(child, list):
# Flatten intermediate lists # Flatten intermediate lists
for x in child: for x in child:
results.append(x) results.append(x)

View File

@ -167,7 +167,7 @@ class Vim:
def _request_managed_object_builder(self, managed_object): def _request_managed_object_builder(self, managed_object):
"""Builds the request managed object.""" """Builds the request managed object."""
# Request Managed Object Builder # Request Managed Object Builder
if type(managed_object) == type(""): if isinstance(managed_object, str):
mo = suds.sudsobject.Property(managed_object) mo = suds.sudsobject.Property(managed_object)
mo._type = managed_object mo._type = managed_object
else: else:

View File

@ -1035,7 +1035,7 @@ class QWebRequest:
name_dict = cgi.parse_header(sub['Content-Disposition'])[1] name_dict = cgi.parse_header(sub['Content-Disposition'])[1]
if 'filename' in name_dict: if 'filename' in name_dict:
# Nested MIME Messages are not supported' # Nested MIME Messages are not supported'
if type([]) == type(sub.get_payload()): if isinstance(sub.get_payload(), list):
continue continue
if not name_dict['filename'].strip(): if not name_dict['filename'].strip():
continue continue