PEP8 quantum cleanup

Fixes bug #911663

The None, True, and False values are singletons.

All variable *comparisons* to singletons should use 'is' or 'is not'.
All variable *evaluations* to boolean should use 'if' or 'if not'.
All Object type comparisons should use isinstance()
instead of comparing types directly.

Change-Id: Id5c797d3339d0d7015bac386088133540f0c0c9e
This commit is contained in:
lzyeval 2012-01-04 17:10:35 +08:00
parent 5b23b5ef6b
commit 4572e6500a
16 changed files with 37 additions and 38 deletions

View File

@ -90,7 +90,7 @@ def APIFaultWrapper(errors=None):
try: try:
return func(*args, **kwargs) return func(*args, **kwargs)
except Exception as e: except Exception as e:
if errors != None and type(e) in errors: if errors is not None and type(e) in errors:
raise faults.QuantumHTTPError(e) raise faults.QuantumHTTPError(e)
# otherwise just re-raise # otherwise just re-raise
raise raise

View File

@ -160,7 +160,7 @@ class Client(object):
action = self.action_prefix + action action = self.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)
if body: if body:
body = self.serialize(body) body = self.serialize(body)
@ -174,7 +174,7 @@ class Client(object):
headers[AUTH_TOKEN_HEADER] = self.auth_token headers[AUTH_TOKEN_HEADER] = self.auth_token
# Open connection and send request, handling SSL certs # Open connection and send request, handling SSL certs
certs = {'key_file': self.key_file, 'cert_file': self.cert_file} certs = {'key_file': self.key_file, 'cert_file': self.cert_file}
certs = dict((x, certs[x]) for x in certs if certs[x] != None) certs = dict((x, certs[x]) for x in certs if certs[x] is not None)
if self.use_ssl and len(certs): if self.use_ssl and len(certs):
conn = connection_type(self.host, self.port, **certs) conn = connection_type(self.host, self.port, **certs)
@ -226,7 +226,7 @@ class Client(object):
""" """
if data is None: if data is None:
return None return None
elif type(data) is dict: elif isinstance(data, dict):
return Serializer().serialize(data, self.content_type()) return Serializer().serialize(data, self.content_type())
else: else:
raise Exception("unable to serialize object of type = '%s'" \ raise Exception("unable to serialize object of type = '%s'" \

View File

@ -135,7 +135,7 @@ class FlagValues(gflags.FlagValues):
if self.IsDirty(name): if self.IsDirty(name):
self.ParseNewFlags() self.ParseNewFlags()
val = gflags.FlagValues.__getattr__(self, name) val = gflags.FlagValues.__getattr__(self, name)
if type(val) is str: if isinstance(val, str):
tmpl = string.Template(val) tmpl = string.Template(val)
context = [self, self.__dict__['__extra_context']] context = [self, self.__dict__['__extra_context']]
return tmpl.substitute(StrWrapper(context)) return tmpl.substitute(StrWrapper(context))

View File

@ -110,7 +110,7 @@ class Serializer(object):
xmlns = metadata.get('xmlns', None) xmlns = metadata.get('xmlns', None)
if xmlns: if xmlns:
result.setAttribute('xmlns', xmlns) result.setAttribute('xmlns', xmlns)
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]
@ -128,7 +128,7 @@ class Serializer(object):
for item in data: for item in data:
node = self._to_xml_node(doc, metadata, singular, item) node = self._to_xml_node(doc, metadata, singular, item)
result.appendChild(node) result.appendChild(node)
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]

View File

@ -37,7 +37,6 @@ import re
import string import string
import struct import struct
import time import time
import types
from quantum.common import flags from quantum.common import flags
from quantum.common import exceptions as exception from quantum.common import exceptions as exception
@ -66,12 +65,12 @@ def import_object(import_str):
def to_primitive(value): def to_primitive(value):
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)) o.append(to_primitive(v))
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) o[k] = to_primitive(v)
@ -124,7 +123,7 @@ def bool_from_string(subject):
Useful for JSON-decoded stuff and config file parsing Useful for JSON-decoded stuff and config file parsing
""" """
if type(subject) == type(bool): if isinstance(subject, bool):
return subject return subject
if hasattr(subject, 'startswith'): # str or unicode... if hasattr(subject, 'startswith'): # str or unicode...
if subject.strip().lower() in ('true', 'on', '1'): if subject.strip().lower() in ('true', 'on', '1'):
@ -152,7 +151,7 @@ def execute(cmd, process_input=None, addl_env=None, check_exit_code=True):
obj = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, obj = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
result = None result = None
if process_input != None: if process_input is not None:
result = obj.communicate(process_input) result = obj.communicate(process_input)
else: else:
result = obj.communicate() result = obj.communicate()
@ -252,7 +251,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:

View File

@ -51,7 +51,7 @@ class ViewBuilder(object):
def _build_detail(self, portprofile_data): def _build_detail(self, portprofile_data):
"""Return a detailed info of a portprofile.""" """Return a detailed info of a portprofile."""
if (portprofile_data['assignment'] == None): if (portprofile_data['assignment'] is None):
return dict(portprofile=dict(id=portprofile_data['profile_id'], return dict(portprofile=dict(id=portprofile_data['profile_id'],
name=portprofile_data['profile_name'], name=portprofile_data['profile_name'],
qos_name=portprofile_data['qos_name'])) qos_name=portprofile_data['qos_name']))

View File

@ -253,7 +253,7 @@ class L2Network(QuantumPluginBase):
network = db.network_get(net_id) network = db.network_get(net_id)
port = db.port_get(net_id, port_id) port = db.port_get(net_id, port_id)
attachment_id = port[const.INTERFACEID] attachment_id = port[const.INTERFACEID]
if attachment_id == None: if attachment_id is None:
raise cexc.InvalidAttach(port_id=port_id, net_id=net_id, raise cexc.InvalidAttach(port_id=port_id, net_id=net_id,
att_id=remote_interface_id) att_id=remote_interface_id)
attachment_id = attachment_id[:const.UUID_LENGTH] attachment_id = attachment_id[:const.UUID_LENGTH]
@ -281,7 +281,7 @@ class L2Network(QuantumPluginBase):
network = db.network_get(net_id) network = db.network_get(net_id)
port = db.port_get(net_id, port_id) port = db.port_get(net_id, port_id)
attachment_id = port[const.INTERFACEID] attachment_id = port[const.INTERFACEID]
if attachment_id == None: if attachment_id is None:
raise exc.InvalidDetach(port_id=port_id, net_id=net_id, raise exc.InvalidDetach(port_id=port_id, net_id=net_id,
att_id=remote_interface_id) att_id=remote_interface_id)
self._invoke_device_plugins(self._func_name(), [tenant_id, net_id, self._invoke_device_plugins(self._func_name(), [tenant_id, net_id,

View File

@ -91,7 +91,7 @@ class L2NetworkSingleBlade(L2NetworkModelBase):
def _invoke_plugin(self, plugin_key, function_name, args, kwargs): def _invoke_plugin(self, plugin_key, function_name, args, kwargs):
"""Invoke only the device plugin""" """Invoke only the device plugin"""
# If the last param is a dict, add it to kwargs # If the last param is a dict, add it to kwargs
if args and type(args[-1]) is dict: if args and isinstance(args[-1], dict):
kwargs.update(args.pop()) kwargs.update(args.pop())
return getattr(self._plugins[plugin_key], function_name)(*args, return getattr(self._plugins[plugin_key], function_name)(*args,

View File

@ -50,7 +50,7 @@ class ServicesLogistics():
service_args.append(image_name) service_args.append(image_name)
counter = 0 counter = 0
flag = False flag = False
while flag == False and counter <= 5: while not flag and counter <= 5:
counter = counter + 1 counter = counter + 1
time.sleep(2.5) time.sleep(2.5)
process = subprocess.Popen(service_args, \ process = subprocess.Popen(service_args, \
@ -71,7 +71,7 @@ class ServicesLogistics():
service_args.append(image_name) service_args.append(image_name)
counter = 0 counter = 0
flag = False flag = False
while flag == False and counter <= 10: while not flag and counter <= 10:
counter = counter + 1 counter = counter + 1
time.sleep(2.5) time.sleep(2.5)
process = subprocess.Popen(service_args, \ process = subprocess.Popen(service_args, \

View File

@ -1063,9 +1063,9 @@ class L2networkDBTest(unittest.TestCase):
self.assertTrue(len(vlanids) > 0) self.assertTrue(len(vlanids) > 0)
vlanid = l2network_db.reserve_vlanid() vlanid = l2network_db.reserve_vlanid()
used = l2network_db.is_vlanid_used(vlanid) used = l2network_db.is_vlanid_used(vlanid)
self.assertTrue(used == True) self.assertTrue(used)
used = l2network_db.release_vlanid(vlanid) used = l2network_db.release_vlanid(vlanid)
self.assertTrue(used == False) self.assertFalse(used)
#counting on default teardown here to clear db #counting on default teardown here to clear db
def teardown_network(self): def teardown_network(self):
@ -1208,7 +1208,7 @@ class QuantumDBTest(unittest.TestCase):
self.assertTrue(port[0]["int-id"] == "vif1.1") self.assertTrue(port[0]["int-id"] == "vif1.1")
self.dbtest.unplug_interface(net1["net-id"], port1["port-id"]) self.dbtest.unplug_interface(net1["net-id"], port1["port-id"])
port = self.dbtest.get_port(net1["net-id"], port1["port-id"]) port = self.dbtest.get_port(net1["net-id"], port1["port-id"])
self.assertTrue(port[0]["int-id"] == None) self.assertTrue(port[0]["int-id"] is None)
self.teardown_network_port() self.teardown_network_port()
def testh_joined_test(self): def testh_joined_test(self):

View File

@ -223,7 +223,7 @@ class UCSVICTestPlugin(unittest.TestCase):
self.assertEqual(port_dict[const.PORTID], new_port[const.UUID]) self.assertEqual(port_dict[const.PORTID], new_port[const.UUID])
profile_name = self._cisco_ucs_plugin.\ profile_name = self._cisco_ucs_plugin.\
_get_profile_name(port_dict[const.PORTID]) _get_profile_name(port_dict[const.PORTID])
self.assertTrue(profile_name != None) self.assertTrue(profile_name is not None)
self.tear_down_network_port( self.tear_down_network_port(
self.tenant_id, new_net_dict[const.NET_ID], self.tenant_id, new_net_dict[const.NET_ID],
port_dict[const.PORTID]) port_dict[const.PORTID])

View File

@ -277,10 +277,10 @@ class UCSInventory(L2NetworkDeviceInventoryBase):
for blade_intf in blade_intf_data.keys(): for blade_intf in blade_intf_data.keys():
tmp = deepcopy(blade_intf_data[blade_intf]) tmp = deepcopy(blade_intf_data[blade_intf])
intf_data = blade_intf_data[blade_intf] intf_data = blade_intf_data[blade_intf]
if intf_data[const.BLADE_INTF_RESERVATION] == \ if (intf_data[const.BLADE_INTF_RESERVATION] ==
const.BLADE_INTF_RESERVED and \ const.BLADE_INTF_RESERVED and
intf_data[const.TENANTID] == tenant_id and \ intf_data[const.TENANTID] == tenant_id and
intf_data[const.INSTANCE_ID] == None: intf_data[const.INSTANCE_ID] is None):
intf_data[const.INSTANCE_ID] = instance_id intf_data[const.INSTANCE_ID] = instance_id
host_name = self._get_host_name(ucsm_ip, host_name = self._get_host_name(ucsm_ip,
chassis_id, chassis_id,

View File

@ -51,7 +51,7 @@ class VlanMap(object):
def acquire(self, network_id): def acquire(self, network_id):
for x in xrange(2, 4094): for x in xrange(2, 4094):
if self.vlans[x] == None: if self.vlans[x] is None:
self.vlans[x] = network_id self.vlans[x] = network_id
# LOG.debug("VlanMap::acquire %s -> %s" % (x, network_id)) # LOG.debug("VlanMap::acquire %s -> %s" % (x, network_id))
return x return x
@ -73,13 +73,13 @@ class OVSQuantumPlugin(QuantumPluginBase):
def __init__(self, configfile=None): def __init__(self, configfile=None):
config = ConfigParser.ConfigParser() config = ConfigParser.ConfigParser()
if configfile == None: if configfile is None:
if os.path.exists(CONF_FILE): if os.path.exists(CONF_FILE):
configfile = CONF_FILE configfile = CONF_FILE
else: else:
configfile = find_config(os.path.abspath( configfile = find_config(os.path.abspath(
os.path.dirname(__file__))) os.path.dirname(__file__)))
if configfile == None: if configfile is None:
raise Exception("Configuration file \"%s\" doesn't exist" % raise Exception("Configuration file \"%s\" doesn't exist" %
(configfile)) (configfile))
LOG.debug("Using configuration file: %s" % configfile) LOG.debug("Using configuration file: %s" % configfile)

View File

@ -33,4 +33,4 @@ class VlanMapTest(unittest.TestCase):
def testReleaseVlan(self): def testReleaseVlan(self):
vlan_id = self.vmap.acquire("foobar") vlan_id = self.vmap.acquire("foobar")
self.vmap.release("foobar") self.vmap.release("foobar")
self.assertTrue(self.vmap.get(vlan_id) == None) self.assertTrue(self.vmap.get(vlan_id) is None)

View File

@ -115,4 +115,4 @@ class QuantumDBTest(unittest.TestCase):
self.assertTrue(port[0]["attachment"] == "vif1.1") self.assertTrue(port[0]["attachment"] == "vif1.1")
self.dbtest.unplug_interface(net1["id"], port1["id"]) self.dbtest.unplug_interface(net1["id"], port1["id"])
port = self.dbtest.get_port(net1["id"], port1["id"]) port = self.dbtest.get_port(net1["id"], port1["id"])
self.assertTrue(port[0]["attachment"] == None) self.assertTrue(port[0]["attachment"] is None)

View File

@ -228,7 +228,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]
@ -247,7 +247,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]
@ -744,7 +744,7 @@ class Resource(Application):
LOG.info(_("HTTP exception thrown: %s"), unicode(ex)) LOG.info(_("HTTP exception thrown: %s"), unicode(ex))
action_result = Fault(ex, self._xmlns) action_result = Fault(ex, self._xmlns)
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(action_result, response = self.serializer.serialize(action_result,
accept, accept,
action=action) action=action)
@ -839,7 +839,7 @@ class Controller(object):
arg_dict['request'] = req arg_dict['request'] = req
result = method(**arg_dict) result = method(**arg_dict)
if type(result) is dict: if isinstance(result, dict):
content_type = req.best_match_content_type() content_type = req.best_match_content_type()
default_xmlns = self.get_default_xmlns(req) default_xmlns = self.get_default_xmlns(req)
body = self._serialize(result, content_type, default_xmlns) body = self._serialize(result, content_type, default_xmlns)
@ -993,7 +993,7 @@ class Serializer(object):
xmlns = metadata.get('xmlns', None) xmlns = metadata.get('xmlns', None)
if xmlns: if xmlns:
result.setAttribute('xmlns', xmlns) result.setAttribute('xmlns', xmlns)
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]
@ -1011,7 +1011,7 @@ class Serializer(object):
for item in data: for item in data:
node = self._to_xml_node(doc, metadata, singular, item) node = self._to_xml_node(doc, metadata, singular, item)
result.appendChild(node) result.appendChild(node)
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]