]> review.fuel-infra Code Review - openstack-build/neutron-build.git/commitdiff
PEP8 quantum cleanup
authorlzyeval <lzyeval@gmail.com>
Wed, 4 Jan 2012 09:10:35 +0000 (17:10 +0800)
committerlzyeval <lzyeval@gmail.com>
Wed, 4 Jan 2012 12:12:31 +0000 (20:12 +0800)
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

16 files changed:
quantum/api/api_common.py
quantum/client/__init__.py
quantum/common/flags.py
quantum/common/serializer.py
quantum/common/utils.py
quantum/extensions/_pprofiles.py
quantum/plugins/cisco/l2network_plugin.py
quantum/plugins/cisco/models/l2network_single_blade.py
quantum/plugins/cisco/services/services_logistics.py
quantum/plugins/cisco/tests/unit/test_database.py
quantum/plugins/cisco/tests/unit/test_ucs_plugin.py
quantum/plugins/cisco/ucs/cisco_ucs_inventory.py
quantum/plugins/openvswitch/ovs_quantum_plugin.py
quantum/plugins/openvswitch/tests/unit/test_vlan_map.py
quantum/tests/unit/test_database.py
quantum/wsgi.py

index 96fe70a208040762c1e1562b7677e0ec9798523c..7c9235116f23153b63ddf55f6c763a9d1ae33050 100644 (file)
@@ -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
index d4e032c135c8f24622d2415eae6e5efb9bd6eb49..6f02126385e9b9b7aa340687b4198e4cac12c652 100644 (file)
@@ -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'" \
index 16badd33293390ef68f9bd5567326c0bd1f5d0c7..ef61e7e140faa7c1e1369de345a568631700b651 100644 (file)
@@ -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))
index b596cf89e79763799424c73ccbaa79da609ee3f5..6fc09f602cd5991e428380be65391d52dfcb870b 100644 (file)
@@ -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]
index 1d425a033d6e94ceec94e157ee0b251b2dd906bc..50343b64c4ce04b2a7024cbe206cfa065857b63c 100644 (file)
@@ -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:
index 285cef0b6eb3119bc380479f1a2e6980c9c0075d..5fb088fc991de2642dc4cef6b4231b2c430fc4bf 100644 (file)
@@ -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']))
index b5da80f1167c3784031028a3b2346b081b3b01d1..fb36b8cfb1c1a4a41fe61a566d3d00019ae38943 100644 (file)
@@ -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,
index 256c8098289be1a6290a5d514a485b97c593b90c..93958561584098a9051a5b52ed3c80f417ae327c 100644 (file)
@@ -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,
index 7550ac53e0a6368d16bd682c935870e294c73919..4b630e0b1989be9b0682929cf75e77c68fe42f0c 100644 (file)
@@ -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, \
index f1e2f86f73176b5fca92a3b2a58eeac6005594fb..345348bd028cad1b2535796f4b2a9d48bc1af07f 100644 (file)
@@ -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):
index b8fa34de6e9313d52d7b093a72f1ad233d1b938c..9e1b93c7b7e0ada2073a3889714e0c0d811f76af 100644 (file)
@@ -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])
index 7e78fb26a437195ae704001c5b5052204893eccb..2f530a0e09a241ba912ae315f672ba0a9b3d8183 100644 (file)
@@ -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,
index d87b17a726b885a65e96f8546721f32d41d19502..6889fa377639a77b36763bdf1de5bf301cfaa4be 100644 (file)
@@ -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)
index e453dc6d1b7a9c54eb753a34040220410cbb31dd..c4a6d8190c5256b47e772d55af3cd17444cb1e5b 100644 (file)
@@ -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)
index 44ce0b56142a56fb4e1571a7ae67cd5855adf80f..81ceb1cbd41199c2d64f5bd4f3538c7e9af875b4 100644 (file)
@@ -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)
index d787fba284ef41ff03f51079902a9cb46ddb7472..2efbf56c296bb70ed0d0b41c42cdc1aa725966c1 100644 (file)
@@ -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]