]> review.fuel-infra Code Review - openstack-build/neutron-build.git/commitdiff
Purge use of "PRED and A or B" poor-mans-ternary
authorAngus Lees <gus@inodes.org>
Thu, 31 Jul 2014 03:30:52 +0000 (13:30 +1000)
committerAngus Lees <gus@inodes.org>
Fri, 7 Nov 2014 13:17:12 +0000 (00:17 +1100)
Since python2.6, python has a proper ternary construct "A if PRED else
B".  The older idiom "PRED and A or B" has a hidden trap - when A is
itself false, the result is (unexpectedly) B.

This change removes all cases of the older construct found using a
trivial git grep " and .* or " - except one case in oslo common
code (fixed in oslo upstream).

Change-Id: I24461f4328e188c8983ad574495e11e033ec5ba4

20 files changed:
neutron/agent/linux/dhcp.py
neutron/agent/linux/utils.py
neutron/api/rpc/agentnotifiers/l3_rpc_agent_api.py
neutron/api/rpc/agentnotifiers/metering_rpc_agent_api.py
neutron/db/portbindings_db.py
neutron/debug/commands.py
neutron/plugins/brocade/vlanbm.py
neutron/plugins/cisco/l3/rpc/l3_router_rpc_joint_agent_api.py
neutron/plugins/ml2/drivers/arista/db.py
neutron/plugins/vmware/dbexts/lsn_db.py
neutron/plugins/vmware/dbexts/networkgw_db.py
neutron/plugins/vmware/dhcp_meta/lsnmanager.py
neutron/plugins/vmware/nsxlib/__init__.py
neutron/plugins/vmware/vshield/vcns.py
neutron/policy.py
neutron/services/firewall/drivers/linux/iptables_fwaas.py
neutron/services/vpn/service_drivers/__init__.py
neutron/services/vpn/service_drivers/cisco_ipsec.py
neutron/tests/unit/ml2/drivers/cisco/apic/test_cisco_apic_common.py
neutron/tests/unit/vmware/test_nsx_plugin.py

index 67e498d2dd2cadd26bb213a4b170b9096c58edbc..ce71fea227e6a8fc3d9bc356904d937512a49471 100644 (file)
@@ -260,7 +260,7 @@ class DhcpLocalProcess(DhcpBase):
         try:
             with open(file_name, 'r') as f:
                 try:
-                    return converter and converter(f.read()) or f.read()
+                    return converter(f.read()) if converter else f.read()
                 except ValueError:
                     msg = _('Unable to convert value in %s')
         except IOError:
index 8243468919a84edbebcb60a6dff865b8a517fa03..4c91dfc559c2d3f3b9019799c5971df25ba8969b 100644 (file)
@@ -63,9 +63,7 @@ def execute(cmd, root_helper=None, process_input=None, addl_env=None,
     try:
         obj, cmd = create_process(cmd, root_helper=root_helper,
                                   addl_env=addl_env)
-        _stdout, _stderr = (process_input and
-                            obj.communicate(process_input) or
-                            obj.communicate())
+        _stdout, _stderr = obj.communicate(process_input)
         obj.stdin.close()
         m = _("\nCommand: %(cmd)s\nExit code: %(code)s\nStdout: %(stdout)r\n"
               "Stderr: %(stderr)r") % {'cmd': cmd, 'code': obj.returncode,
@@ -88,7 +86,7 @@ def execute(cmd, root_helper=None, process_input=None, addl_env=None,
         #               it two execute calls in a row hangs the second one
         greenthread.sleep(0)
 
-    return return_stderr and (_stdout, _stderr) or _stdout
+    return (_stdout, _stderr) if return_stderr else _stdout
 
 
 def get_interface_mac(interface):
@@ -157,7 +155,7 @@ def get_value_from_conf_file(cfg_root, uuid, cfg_file, converter=None):
     try:
         with open(file_name, 'r') as f:
             try:
-                return converter and converter(f.read()) or f.read()
+                return converter(f.read()) if converter else f.read()
             except ValueError:
                 msg = _('Unable to convert value in %s')
     except IOError:
index 0b8f7e5efafe7cd8c79dd0aee8ff297620d7a46c..e22c5292f44538feb3c88904c242e11265e2c061 100644 (file)
@@ -48,7 +48,7 @@ class L3AgentNotifyAPI(n_rpc.RpcProxy):
     def _agent_notification(self, context, method, router_ids, operation,
                             shuffle_agents):
         """Notify changed routers to hosting l3 agents."""
-        adminContext = context.is_admin and context or context.elevated()
+        adminContext = context if context.is_admin else context.elevated()
         plugin = manager.NeutronManager.get_service_plugins().get(
             service_constants.L3_ROUTER_NAT)
         for router_id in router_ids:
index 915d999fc9e12fb7ab748b10a3b5cdb01e52704a..0a37fd7a3ebbec969cbb2d3c64b57a5eac970e18 100644 (file)
@@ -33,7 +33,7 @@ class MeteringAgentNotifyAPI(n_rpc.RpcProxy):
 
     def _agent_notification(self, context, method, routers):
         """Notify l3 metering agents hosted by l3 agent hosts."""
-        adminContext = context.is_admin and context or context.elevated()
+        adminContext = context if context.is_admin else context.elevated()
         plugin = manager.NeutronManager.get_service_plugins().get(
             service_constants.L3_ROUTER_NAT)
 
index 8b777aba7a6d680275c50358ffa5542276c133e8..c8ab65c59da5c2d20c8d29cdc6e291973a7920a6 100644 (file)
@@ -90,14 +90,14 @@ class PortBindingMixin(portbindings_base.PortBindingBaseMixin):
                 else:
                     bind_port.host = host
             else:
-                host = (bind_port and bind_port.host or None)
+                host = bind_port.host if bind_port else None
         self._extend_port_dict_binding_host(port, host)
 
     def get_port_host(self, context, port_id):
         with context.session.begin(subtransactions=True):
             bind_port = context.session.query(
                 PortBindingPort).filter_by(port_id=port_id).first()
-            return bind_port and bind_port.host or None
+            return bind_port.host if bind_port else None
 
     def _extend_port_dict_binding_host(self, port_res, host):
         super(PortBindingMixin, self).extend_port_dict_binding(
@@ -105,7 +105,7 @@ class PortBindingMixin(portbindings_base.PortBindingBaseMixin):
         port_res[portbindings.HOST_ID] = host
 
     def extend_port_dict_binding(self, port_res, port_db):
-        host = (port_db.portbinding and port_db.portbinding.host or None)
+        host = port_db.portbinding.host if port_db.portbinding else None
         self._extend_port_dict_binding_host(port_res, host)
 
 
index 464966d253a6e7f11c38a1376fd4f3805cd6205f..2b321b2823f0ac113b6923987f5ecbf4cf9ef584 100644 (file)
@@ -89,7 +89,7 @@ class ListProbe(client.NeutronCommand, lister.Lister):
 
         debug_agent = self.get_debug_agent()
         info = debug_agent.list_probes()
-        columns = len(info) > 0 and sorted(info[0].keys()) or []
+        columns = sorted(info[0].keys()) if info else []
         return (columns, (utils.get_item_properties(
             s, columns, formatters=self._formatters, )
             for s in info), )
index 91bb24b7958f2fc6eaf8a0722557a441780bddef..16c9d4bf3611d969c99130e0e44e7d408ecf4af5 100644 (file)
@@ -41,7 +41,7 @@ class VlanBitmap(object):
     def get_next_vlan(self, vlan_id=None):
         """Try to get a specific vlan if requested or get the next vlan."""
         min_vlan_search = vlan_id or MIN_VLAN
-        max_vlan_search = (vlan_id and vlan_id + 1) or MAX_VLAN
+        max_vlan_search = (vlan_id + 1) if vlan_id else MAX_VLAN
 
         for vlan in moves.xrange(min_vlan_search, max_vlan_search):
             if vlan not in self.vlans:
index 96bc6f46a5f5e01009c832bbd07190642d6d20c4..72bbaa41d330cd26f934ba298b72836544487767 100644 (file)
@@ -41,7 +41,7 @@ class L3RouterJointAgentNotifyAPI(n_rpc.RpcProxy):
 
     def _agent_notification(self, context, method, routers, operation, data):
         """Notify individual Cisco cfg agents."""
-        admin_context = context.is_admin and context or context.elevated()
+        admin_context = context if context.is_admin else context.elevated()
         for router in routers:
             if router['hosting_device'] is None:
                 continue
index f47bcd1409388f40412bcab3c2b9de7f899d3e16..be295c90b26aa95a892ebbe531f04e5d6fd6f9ce 100644 (file)
@@ -199,7 +199,7 @@ def get_segmentation_id(tenant_id, network_id):
         net = (session.query(AristaProvisionedNets).
                filter_by(tenant_id=tenant_id,
                          network_id=network_id).first())
-        return net and net.segmentation_id or None
+        return net.segmentation_id if net else None
 
 
 def is_vm_provisioned(vm_id, host_id, port_id,
index f24e0488bf7f1f91ab047444023e44b34e66ebf5..a4865bdfc19dd5c1d95b7a2f95fb58cb0b39a1de 100644 (file)
@@ -83,12 +83,13 @@ def lsn_get_for_network(context, network_id, raise_on_err=True):
     try:
         return query.filter_by(net_id=network_id).one()
     except (orm.exc.NoResultFound, d_exc.DBError):
-        logger = raise_on_err and LOG.error or LOG.warn
-        logger(_('Unable to find Logical Service Node for '
-                 'network %s'), network_id)
+        msg = _('Unable to find Logical Service Node for network %s')
         if raise_on_err:
+            LOG.error(msg, network_id)
             raise p_exc.LsnNotFound(entity='network',
                                     entity_id=network_id)
+        else:
+            LOG.warn(msg, network_id)
 
 
 def lsn_port_add_for_lsn(context, lsn_port_id, subnet_id, mac, lsn_id):
index 40113d129fe748145ce1b5c2ca3f1edb6694aa11..7463d0b1ac161e1a8edc74f43964bfc5c79a1103 100644 (file)
@@ -173,7 +173,7 @@ class NetworkGatewayMixin(networkgw.NetworkGatewayPluginBase):
                'devices': device_list,
                'tenant_id': network_gateway['tenant_id']}
         # Query gateway connections only if needed
-        if (fields and 'ports' in fields) or not fields:
+        if not fields or 'ports' in fields:
             res['ports'] = [self._make_gw_connection_dict(conn)
                             for conn in network_gateway.network_connections]
         return self._fields(res, fields)
@@ -221,7 +221,7 @@ class NetworkGatewayMixin(networkgw.NetworkGatewayPluginBase):
         query = self._get_collection_query(context,
                                            NetworkConnection,
                                            filters)
-        return only_one and query.one() or query.all()
+        return query.one() if only_one else query.all()
 
     def _unset_default_network_gateways(self, context):
         with context.session.begin(subtransactions=True):
index 9bc80e6c71ddf53e8f240c7c0823ccbcae628699..4c61a93a8c386790053ea77fab5235e8fbce702f 100644 (file)
@@ -67,12 +67,13 @@ class LsnManager(object):
         try:
             return lsn_api.lsn_for_network_get(self.cluster, network_id)
         except (n_exc.NotFound, api_exc.NsxApiException):
-            logger = raise_on_err and LOG.error or LOG.warn
-            logger(_('Unable to find Logical Service Node for '
-                     'network %s'), network_id)
+            msg = _('Unable to find Logical Service Node for network %s')
             if raise_on_err:
+                LOG.error(msg, network_id)
                 raise p_exc.LsnNotFound(entity='network',
                                         entity_id=network_id)
+            else:
+                LOG.warn(msg, network_id)
 
     def lsn_create(self, context, network_id):
         """Create a LSN associated to the network."""
@@ -103,14 +104,15 @@ class LsnManager(object):
                 lsn_port_id = lsn_api.lsn_port_by_subnet_get(
                     self.cluster, lsn_id, subnet_id)
             except (n_exc.NotFound, api_exc.NsxApiException):
-                logger = raise_on_err and LOG.error or LOG.warn
-                logger(_('Unable to find Logical Service Node Port for '
-                         'LSN %(lsn_id)s and subnet %(subnet_id)s')
-                       % {'lsn_id': lsn_id, 'subnet_id': subnet_id})
+                msg = _('Unable to find Logical Service Node Port for '
+                        'LSN %(lsn_id)s and subnet %(subnet_id)s')
                 if raise_on_err:
+                    LOG.error(msg, {'lsn_id': lsn_id, 'subnet_id': subnet_id})
                     raise p_exc.LsnPortNotFound(lsn_id=lsn_id,
                                                 entity='subnet',
                                                 entity_id=subnet_id)
+                else:
+                    LOG.warn(msg, {'lsn_id': lsn_id, 'subnet_id': subnet_id})
                 return (lsn_id, None)
             else:
                 return (lsn_id, lsn_port_id)
@@ -125,14 +127,15 @@ class LsnManager(object):
                 lsn_port_id = lsn_api.lsn_port_by_mac_get(
                     self.cluster, lsn_id, mac)
             except (n_exc.NotFound, api_exc.NsxApiException):
-                logger = raise_on_err and LOG.error or LOG.warn
-                logger(_('Unable to find Logical Service Node Port for '
-                         'LSN %(lsn_id)s and mac address %(mac)s')
-                       % {'lsn_id': lsn_id, 'mac': mac})
+                msg = _('Unable to find Logical Service Node Port for '
+                        'LSN %(lsn_id)s and mac address %(mac)s')
                 if raise_on_err:
+                    LOG.error(msg, {'lsn_id': lsn_id, 'mac': mac})
                     raise p_exc.LsnPortNotFound(lsn_id=lsn_id,
                                                 entity='MAC',
                                                 entity_id=mac)
+                else:
+                    LOG.warn(msg, {'lsn_id': lsn_id, 'mac': mac})
                 return (lsn_id, None)
             else:
                 return (lsn_id, lsn_port_id)
index 8305334c2b251197d4508bc988326167db00d410..c267ecc47eabd6dc0801d049dcba74094b02453c 100644 (file)
@@ -41,7 +41,9 @@ def _build_uri_path(resource,
                     is_attachment=False,
                     extra_action=None):
     resources = resource.split('/')
-    res_path = resources[0] + (resource_id and "/%s" % resource_id or '')
+    res_path = resources[0]
+    if resource_id:
+        res_path += "/%s" % resource_id
     if len(resources) > 1:
         # There is also a parent resource to account for in the uri
         res_path = "%s/%s/%s" % (resources[1],
index 6c2835ea231a9928153224988202e39b16808c78..6b4f2484587bf520ba28cd05d403d89183ccb863 100644 (file)
@@ -293,7 +293,9 @@ class Vcns(object):
                         is_attachment=False):
         uri_prefix = "%s/%s/%s" % (URI_PREFIX, edge_id, service)
         if resource:
-            res_path = resource + (resource_id and "/%s" % resource_id or '')
+            res_path = resource
+            if resource_id:
+                res_path += "/%s" % resource_id
             uri_path = "%s/%s" % (uri_prefix, res_path)
         else:
             uri_path = uri_prefix
index 5ce695f303f44cec78390b90c456e2cbbcb61888..5b8344b075f8b3e2eaf1f7c8867f117b532be521 100644 (file)
@@ -412,8 +412,8 @@ def check_is_admin(context):
     target = credentials
     # Backward compatibility: if ADMIN_CTX_POLICY is not
     # found, default to validating role:admin
-    admin_policy = (ADMIN_CTX_POLICY in policy._rules
-                    and ADMIN_CTX_POLICY or 'role:admin')
+    admin_policy = (ADMIN_CTX_POLICY if ADMIN_CTX_POLICY in policy._rules
+                    else 'role:admin')
     return policy.check(admin_policy, target, credentials)
 
 
index 7f4a2c12a48ef3e43756a3177eee57d715f4aa5b..71b3b345ca22266f21b2c5d48af992a0ca361bfd 100644 (file)
@@ -268,7 +268,7 @@ class IptablesFwaasDriver(fwaas_base.FwaasDriverBase):
         self._add_rules_to_chain(ipt_mgr, IPV6, 'FORWARD', jump_rule)
 
     def _convert_fwaas_to_iptables_rule(self, rule):
-        action = rule.get('action') == 'allow' and 'ACCEPT' or 'DROP'
+        action = 'ACCEPT' if rule.get('action') == 'allow' else 'DROP'
         args = [self._protocol_arg(rule.get('protocol')),
                 self._port_arg('dport',
                                rule.get('protocol'),
index 8703ebf35ee4359a52363f6b67b55ad4634cebc4..d66e37850992e1d19ab52fb3c019bc436da39865 100644 (file)
@@ -86,7 +86,7 @@ class BaseIPsecVpnAgentApi(n_rpc.RpcProxy):
         This method will find where is the router, and
         dispatch notification for the agent.
         """
-        admin_context = context.is_admin and context or context.elevated()
+        admin_context = context if context.is_admin else context.elevated()
         if not version:
             version = self.RPC_API_VERSION
         l3_agents = self.driver.l3_plugin.get_l3_agents_hosting_routers(
index 28e3d589fe1267e7effd280ec7bb8b9290d26b18..c61d4796ecf6d82cd8738d13fe8e73cb02b7762f 100644 (file)
@@ -93,7 +93,7 @@ class CiscoCsrIPsecVpnAgentApi(service_drivers.BaseIPsecVpnAgentApi,
         Find the host for the router being notified and then
         dispatches a notification for the VPN device driver.
         """
-        admin_context = context.is_admin and context or context.elevated()
+        admin_context = context if context.is_admin else context.elevated()
         if not version:
             version = self.RPC_API_VERSION
         host = via_cfg_file.get_host_for_router(admin_context, router_id)
index d2da4ed24b81718ff7ef03035e1e57326ede938b..bbb342c4dde59e0c79d34fae6907bab72eb88606 100644 (file)
@@ -107,7 +107,7 @@ class ControllerMixin(object):
 
     def reset_reponses(self, req=None):
         # Clear all staged responses.
-        reqs = req and [req] or ['post', 'get']  # Both if none specified.
+        reqs = [req] if req else ['post', 'get']  # Both if none specified.
         for req in reqs:
             del self.response[req][:]
             self.restart_responses(req)
@@ -126,7 +126,7 @@ class ControllerMixin(object):
     def _stage_mocked_response(self, req, mock_status, mo, **attrs):
         response = mock.MagicMock()
         response.status_code = mock_status
-        mo_attrs = attrs and [{mo: {'attributes': attrs}}] or []
+        mo_attrs = [{mo: {'attributes': attrs}}] if attrs else []
         response.json.return_value = {'imdata': mo_attrs}
         self.response[req].append(response)
 
index 192ea5784a3b97ea138076342c5e205c1a60a78b..bd668d6719db35efcc10bb79b10baa80cc2d05d6 100644 (file)
@@ -241,7 +241,7 @@ class TestPortsV2(NsxPluginV2TestCase,
 class TestNetworksV2(test_plugin.TestNetworksV2, NsxPluginV2TestCase):
 
     def _test_create_bridge_network(self, vlan_id=0):
-        net_type = vlan_id and 'vlan' or 'flat'
+        net_type = 'vlan' if vlan_id else 'flat'
         name = 'bridge_net'
         expected = [('subnets', []), ('name', name), ('admin_state_up', True),
                     ('status', 'ACTIVE'), ('shared', False),