From 4572e6500ace4996f63fb12f09808346e87f9551 Mon Sep 17 00:00:00 2001 From: lzyeval Date: Wed, 4 Jan 2012 17:10:35 +0800 Subject: [PATCH] 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 --- quantum/api/api_common.py | 2 +- quantum/client/__init__.py | 6 +++--- quantum/common/flags.py | 2 +- quantum/common/serializer.py | 4 ++-- quantum/common/utils.py | 11 +++++------ quantum/extensions/_pprofiles.py | 2 +- quantum/plugins/cisco/l2network_plugin.py | 4 ++-- .../plugins/cisco/models/l2network_single_blade.py | 2 +- quantum/plugins/cisco/services/services_logistics.py | 4 ++-- quantum/plugins/cisco/tests/unit/test_database.py | 6 +++--- quantum/plugins/cisco/tests/unit/test_ucs_plugin.py | 2 +- quantum/plugins/cisco/ucs/cisco_ucs_inventory.py | 8 ++++---- quantum/plugins/openvswitch/ovs_quantum_plugin.py | 6 +++--- .../plugins/openvswitch/tests/unit/test_vlan_map.py | 2 +- quantum/tests/unit/test_database.py | 2 +- quantum/wsgi.py | 12 ++++++------ 16 files changed, 37 insertions(+), 38 deletions(-) diff --git a/quantum/api/api_common.py b/quantum/api/api_common.py index 96fe70a2080..7c9235116f2 100644 --- a/quantum/api/api_common.py +++ b/quantum/api/api_common.py @@ -90,7 +90,7 @@ def APIFaultWrapper(errors=None): try: return func(*args, **kwargs) 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) # otherwise just re-raise raise diff --git a/quantum/client/__init__.py b/quantum/client/__init__.py index d4e032c135c..6f02126385e 100644 --- a/quantum/client/__init__.py +++ b/quantum/client/__init__.py @@ -160,7 +160,7 @@ class Client(object): action = self.action_prefix + action action = action.replace('{tenant_id}', self.tenant) - if type(params) is dict: + if isinstance(params, dict): action += '?' + urllib.urlencode(params) if body: body = self.serialize(body) @@ -174,7 +174,7 @@ class Client(object): headers[AUTH_TOKEN_HEADER] = self.auth_token # Open connection and send request, handling SSL certs 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): conn = connection_type(self.host, self.port, **certs) @@ -226,7 +226,7 @@ class Client(object): """ if data is None: return None - elif type(data) is dict: + elif isinstance(data, dict): return Serializer().serialize(data, self.content_type()) else: raise Exception("unable to serialize object of type = '%s'" \ diff --git a/quantum/common/flags.py b/quantum/common/flags.py index 16badd33293..ef61e7e140f 100644 --- a/quantum/common/flags.py +++ b/quantum/common/flags.py @@ -135,7 +135,7 @@ class FlagValues(gflags.FlagValues): if self.IsDirty(name): self.ParseNewFlags() val = gflags.FlagValues.__getattr__(self, name) - if type(val) is str: + if isinstance(val, str): tmpl = string.Template(val) context = [self, self.__dict__['__extra_context']] return tmpl.substitute(StrWrapper(context)) diff --git a/quantum/common/serializer.py b/quantum/common/serializer.py index b596cf89e79..6fc09f602cd 100644 --- a/quantum/common/serializer.py +++ b/quantum/common/serializer.py @@ -110,7 +110,7 @@ class Serializer(object): xmlns = metadata.get('xmlns', None) if xmlns: result.setAttribute('xmlns', xmlns) - if type(data) is list: + if isinstance(data, list): collections = metadata.get('list_collections', {}) if nodename in collections: metadata = collections[nodename] @@ -128,7 +128,7 @@ class Serializer(object): for item in data: node = self._to_xml_node(doc, metadata, singular, item) result.appendChild(node) - elif type(data) is dict: + elif isinstance(data, dict): collections = metadata.get('dict_collections', {}) if nodename in collections: metadata = collections[nodename] diff --git a/quantum/common/utils.py b/quantum/common/utils.py index 1d425a033d6..50343b64c4c 100644 --- a/quantum/common/utils.py +++ b/quantum/common/utils.py @@ -37,7 +37,6 @@ import re import string import struct import time -import types from quantum.common import flags from quantum.common import exceptions as exception @@ -66,12 +65,12 @@ def import_object(import_str): def to_primitive(value): - if type(value) is type([]) or type(value) is type((None,)): + if isinstance(value, (list, tuple)): o = [] for v in value: o.append(to_primitive(v)) return o - elif type(value) is type({}): + elif isinstance(value, dict): o = {} for k, v in value.iteritems(): o[k] = to_primitive(v) @@ -124,7 +123,7 @@ def bool_from_string(subject): Useful for JSON-decoded stuff and config file parsing """ - if type(subject) == type(bool): + if isinstance(subject, bool): return subject if hasattr(subject, 'startswith'): # str or unicode... 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, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env) result = None - if process_input != None: + if process_input is not None: result = obj.communicate(process_input) else: result = obj.communicate() @@ -252,7 +251,7 @@ class LazyPluggable(object): raise exception.Error('Invalid backend: %s' % backend_name) backend = self.__backends[backend_name] - if type(backend) == type(tuple()): + if isinstance(backend, tuple): name = backend[0] fromlist = backend[1] else: diff --git a/quantum/extensions/_pprofiles.py b/quantum/extensions/_pprofiles.py index 285cef0b6eb..5fb088fc991 100644 --- a/quantum/extensions/_pprofiles.py +++ b/quantum/extensions/_pprofiles.py @@ -51,7 +51,7 @@ class ViewBuilder(object): def _build_detail(self, portprofile_data): """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'], name=portprofile_data['profile_name'], qos_name=portprofile_data['qos_name'])) diff --git a/quantum/plugins/cisco/l2network_plugin.py b/quantum/plugins/cisco/l2network_plugin.py index b5da80f1167..fb36b8cfb1c 100644 --- a/quantum/plugins/cisco/l2network_plugin.py +++ b/quantum/plugins/cisco/l2network_plugin.py @@ -253,7 +253,7 @@ class L2Network(QuantumPluginBase): network = db.network_get(net_id) port = db.port_get(net_id, port_id) 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, att_id=remote_interface_id) attachment_id = attachment_id[:const.UUID_LENGTH] @@ -281,7 +281,7 @@ class L2Network(QuantumPluginBase): network = db.network_get(net_id) port = db.port_get(net_id, port_id) 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, att_id=remote_interface_id) self._invoke_device_plugins(self._func_name(), [tenant_id, net_id, diff --git a/quantum/plugins/cisco/models/l2network_single_blade.py b/quantum/plugins/cisco/models/l2network_single_blade.py index 256c8098289..93958561584 100644 --- a/quantum/plugins/cisco/models/l2network_single_blade.py +++ b/quantum/plugins/cisco/models/l2network_single_blade.py @@ -91,7 +91,7 @@ class L2NetworkSingleBlade(L2NetworkModelBase): def _invoke_plugin(self, plugin_key, function_name, args, kwargs): """Invoke only the device plugin""" # 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()) return getattr(self._plugins[plugin_key], function_name)(*args, diff --git a/quantum/plugins/cisco/services/services_logistics.py b/quantum/plugins/cisco/services/services_logistics.py index 7550ac53e0a..4b630e0b198 100644 --- a/quantum/plugins/cisco/services/services_logistics.py +++ b/quantum/plugins/cisco/services/services_logistics.py @@ -50,7 +50,7 @@ class ServicesLogistics(): service_args.append(image_name) counter = 0 flag = False - while flag == False and counter <= 5: + while not flag and counter <= 5: counter = counter + 1 time.sleep(2.5) process = subprocess.Popen(service_args, \ @@ -71,7 +71,7 @@ class ServicesLogistics(): service_args.append(image_name) counter = 0 flag = False - while flag == False and counter <= 10: + while not flag and counter <= 10: counter = counter + 1 time.sleep(2.5) process = subprocess.Popen(service_args, \ diff --git a/quantum/plugins/cisco/tests/unit/test_database.py b/quantum/plugins/cisco/tests/unit/test_database.py index f1e2f86f731..345348bd028 100644 --- a/quantum/plugins/cisco/tests/unit/test_database.py +++ b/quantum/plugins/cisco/tests/unit/test_database.py @@ -1063,9 +1063,9 @@ class L2networkDBTest(unittest.TestCase): self.assertTrue(len(vlanids) > 0) vlanid = l2network_db.reserve_vlanid() used = l2network_db.is_vlanid_used(vlanid) - self.assertTrue(used == True) + self.assertTrue(used) used = l2network_db.release_vlanid(vlanid) - self.assertTrue(used == False) + self.assertFalse(used) #counting on default teardown here to clear db def teardown_network(self): @@ -1208,7 +1208,7 @@ class QuantumDBTest(unittest.TestCase): self.assertTrue(port[0]["int-id"] == "vif1.1") self.dbtest.unplug_interface(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() def testh_joined_test(self): diff --git a/quantum/plugins/cisco/tests/unit/test_ucs_plugin.py b/quantum/plugins/cisco/tests/unit/test_ucs_plugin.py index b8fa34de6e9..9e1b93c7b7e 100644 --- a/quantum/plugins/cisco/tests/unit/test_ucs_plugin.py +++ b/quantum/plugins/cisco/tests/unit/test_ucs_plugin.py @@ -223,7 +223,7 @@ class UCSVICTestPlugin(unittest.TestCase): self.assertEqual(port_dict[const.PORTID], new_port[const.UUID]) profile_name = self._cisco_ucs_plugin.\ _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.tenant_id, new_net_dict[const.NET_ID], port_dict[const.PORTID]) diff --git a/quantum/plugins/cisco/ucs/cisco_ucs_inventory.py b/quantum/plugins/cisco/ucs/cisco_ucs_inventory.py index 7e78fb26a43..2f530a0e09a 100644 --- a/quantum/plugins/cisco/ucs/cisco_ucs_inventory.py +++ b/quantum/plugins/cisco/ucs/cisco_ucs_inventory.py @@ -277,10 +277,10 @@ class UCSInventory(L2NetworkDeviceInventoryBase): for blade_intf in blade_intf_data.keys(): tmp = deepcopy(blade_intf_data[blade_intf]) intf_data = blade_intf_data[blade_intf] - if intf_data[const.BLADE_INTF_RESERVATION] == \ - const.BLADE_INTF_RESERVED and \ - intf_data[const.TENANTID] == tenant_id and \ - intf_data[const.INSTANCE_ID] == None: + if (intf_data[const.BLADE_INTF_RESERVATION] == + const.BLADE_INTF_RESERVED and + intf_data[const.TENANTID] == tenant_id and + intf_data[const.INSTANCE_ID] is None): intf_data[const.INSTANCE_ID] = instance_id host_name = self._get_host_name(ucsm_ip, chassis_id, diff --git a/quantum/plugins/openvswitch/ovs_quantum_plugin.py b/quantum/plugins/openvswitch/ovs_quantum_plugin.py index d87b17a726b..6889fa37763 100644 --- a/quantum/plugins/openvswitch/ovs_quantum_plugin.py +++ b/quantum/plugins/openvswitch/ovs_quantum_plugin.py @@ -51,7 +51,7 @@ class VlanMap(object): def acquire(self, network_id): for x in xrange(2, 4094): - if self.vlans[x] == None: + if self.vlans[x] is None: self.vlans[x] = network_id # LOG.debug("VlanMap::acquire %s -> %s" % (x, network_id)) return x @@ -73,13 +73,13 @@ class OVSQuantumPlugin(QuantumPluginBase): def __init__(self, configfile=None): config = ConfigParser.ConfigParser() - if configfile == None: + if configfile is None: if os.path.exists(CONF_FILE): configfile = CONF_FILE else: configfile = find_config(os.path.abspath( os.path.dirname(__file__))) - if configfile == None: + if configfile is None: raise Exception("Configuration file \"%s\" doesn't exist" % (configfile)) LOG.debug("Using configuration file: %s" % configfile) diff --git a/quantum/plugins/openvswitch/tests/unit/test_vlan_map.py b/quantum/plugins/openvswitch/tests/unit/test_vlan_map.py index e453dc6d1b7..c4a6d8190c5 100644 --- a/quantum/plugins/openvswitch/tests/unit/test_vlan_map.py +++ b/quantum/plugins/openvswitch/tests/unit/test_vlan_map.py @@ -33,4 +33,4 @@ class VlanMapTest(unittest.TestCase): def testReleaseVlan(self): vlan_id = self.vmap.acquire("foobar") self.vmap.release("foobar") - self.assertTrue(self.vmap.get(vlan_id) == None) + self.assertTrue(self.vmap.get(vlan_id) is None) diff --git a/quantum/tests/unit/test_database.py b/quantum/tests/unit/test_database.py index 44ce0b56142..81ceb1cbd41 100644 --- a/quantum/tests/unit/test_database.py +++ b/quantum/tests/unit/test_database.py @@ -115,4 +115,4 @@ class QuantumDBTest(unittest.TestCase): self.assertTrue(port[0]["attachment"] == "vif1.1") self.dbtest.unplug_interface(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) diff --git a/quantum/wsgi.py b/quantum/wsgi.py index d787fba284e..2efbf56c296 100644 --- a/quantum/wsgi.py +++ b/quantum/wsgi.py @@ -228,7 +228,7 @@ class XMLDictSerializer(DictSerializer): result.setAttribute('xmlns', xmlns) #TODO(bcwaldon): accomplish this without a type-check - if type(data) is list: + if isinstance(data, list): collections = metadata.get('list_collections', {}) if nodename in collections: metadata = collections[nodename] @@ -247,7 +247,7 @@ class XMLDictSerializer(DictSerializer): node = self._to_xml_node(doc, metadata, singular, item) result.appendChild(node) #TODO(bcwaldon): accomplish this without a type-check - elif type(data) is dict: + elif isinstance(data, dict): collections = metadata.get('dict_collections', {}) if nodename in collections: metadata = collections[nodename] @@ -744,7 +744,7 @@ class Resource(Application): LOG.info(_("HTTP exception thrown: %s"), unicode(ex)) 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, accept, action=action) @@ -839,7 +839,7 @@ class Controller(object): arg_dict['request'] = req result = method(**arg_dict) - if type(result) is dict: + if isinstance(result, dict): content_type = req.best_match_content_type() default_xmlns = self.get_default_xmlns(req) body = self._serialize(result, content_type, default_xmlns) @@ -993,7 +993,7 @@ class Serializer(object): xmlns = metadata.get('xmlns', None) if xmlns: result.setAttribute('xmlns', xmlns) - if type(data) is list: + if isinstance(data, list): collections = metadata.get('list_collections', {}) if nodename in collections: metadata = collections[nodename] @@ -1011,7 +1011,7 @@ class Serializer(object): for item in data: node = self._to_xml_node(doc, metadata, singular, item) result.appendChild(node) - elif type(data) is dict: + elif isinstance(data, dict): collections = metadata.get('dict_collections', {}) if nodename in collections: metadata = collections[nodename]