From ea27c8a162f49219f359bb7f6bf14346edc39437 Mon Sep 17 00:00:00 2001 From: Angus Lees Date: Thu, 31 Jul 2014 13:30:52 +1000 Subject: [PATCH] Purge use of "PRED and A or B" poor-mans-ternary 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 --- neutron/agent/linux/dhcp.py | 2 +- neutron/agent/linux/utils.py | 8 +++--- .../rpc/agentnotifiers/l3_rpc_agent_api.py | 2 +- .../agentnotifiers/metering_rpc_agent_api.py | 2 +- neutron/db/portbindings_db.py | 6 ++--- neutron/debug/commands.py | 2 +- neutron/plugins/brocade/vlanbm.py | 2 +- .../l3/rpc/l3_router_rpc_joint_agent_api.py | 2 +- neutron/plugins/ml2/drivers/arista/db.py | 2 +- neutron/plugins/vmware/dbexts/lsn_db.py | 7 +++--- neutron/plugins/vmware/dbexts/networkgw_db.py | 4 +-- .../plugins/vmware/dhcp_meta/lsnmanager.py | 25 +++++++++++-------- neutron/plugins/vmware/nsxlib/__init__.py | 4 ++- neutron/plugins/vmware/vshield/vcns.py | 4 ++- neutron/policy.py | 4 +-- .../firewall/drivers/linux/iptables_fwaas.py | 2 +- .../services/vpn/service_drivers/__init__.py | 2 +- .../vpn/service_drivers/cisco_ipsec.py | 2 +- .../cisco/apic/test_cisco_apic_common.py | 4 +-- neutron/tests/unit/vmware/test_nsx_plugin.py | 2 +- 20 files changed, 47 insertions(+), 41 deletions(-) diff --git a/neutron/agent/linux/dhcp.py b/neutron/agent/linux/dhcp.py index 67e498d2d..ce71fea22 100644 --- a/neutron/agent/linux/dhcp.py +++ b/neutron/agent/linux/dhcp.py @@ -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: diff --git a/neutron/agent/linux/utils.py b/neutron/agent/linux/utils.py index 824346891..4c91dfc55 100644 --- a/neutron/agent/linux/utils.py +++ b/neutron/agent/linux/utils.py @@ -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: diff --git a/neutron/api/rpc/agentnotifiers/l3_rpc_agent_api.py b/neutron/api/rpc/agentnotifiers/l3_rpc_agent_api.py index 0b8f7e5ef..e22c5292f 100644 --- a/neutron/api/rpc/agentnotifiers/l3_rpc_agent_api.py +++ b/neutron/api/rpc/agentnotifiers/l3_rpc_agent_api.py @@ -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: diff --git a/neutron/api/rpc/agentnotifiers/metering_rpc_agent_api.py b/neutron/api/rpc/agentnotifiers/metering_rpc_agent_api.py index 915d999fc..0a37fd7a3 100644 --- a/neutron/api/rpc/agentnotifiers/metering_rpc_agent_api.py +++ b/neutron/api/rpc/agentnotifiers/metering_rpc_agent_api.py @@ -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) diff --git a/neutron/db/portbindings_db.py b/neutron/db/portbindings_db.py index 8b777aba7..c8ab65c59 100644 --- a/neutron/db/portbindings_db.py +++ b/neutron/db/portbindings_db.py @@ -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) diff --git a/neutron/debug/commands.py b/neutron/debug/commands.py index 464966d25..2b321b282 100644 --- a/neutron/debug/commands.py +++ b/neutron/debug/commands.py @@ -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), ) diff --git a/neutron/plugins/brocade/vlanbm.py b/neutron/plugins/brocade/vlanbm.py index 91bb24b79..16c9d4bf3 100644 --- a/neutron/plugins/brocade/vlanbm.py +++ b/neutron/plugins/brocade/vlanbm.py @@ -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: diff --git a/neutron/plugins/cisco/l3/rpc/l3_router_rpc_joint_agent_api.py b/neutron/plugins/cisco/l3/rpc/l3_router_rpc_joint_agent_api.py index 96bc6f46a..72bbaa41d 100644 --- a/neutron/plugins/cisco/l3/rpc/l3_router_rpc_joint_agent_api.py +++ b/neutron/plugins/cisco/l3/rpc/l3_router_rpc_joint_agent_api.py @@ -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 diff --git a/neutron/plugins/ml2/drivers/arista/db.py b/neutron/plugins/ml2/drivers/arista/db.py index f47bcd140..be295c90b 100644 --- a/neutron/plugins/ml2/drivers/arista/db.py +++ b/neutron/plugins/ml2/drivers/arista/db.py @@ -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, diff --git a/neutron/plugins/vmware/dbexts/lsn_db.py b/neutron/plugins/vmware/dbexts/lsn_db.py index f24e0488b..a4865bdfc 100644 --- a/neutron/plugins/vmware/dbexts/lsn_db.py +++ b/neutron/plugins/vmware/dbexts/lsn_db.py @@ -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): diff --git a/neutron/plugins/vmware/dbexts/networkgw_db.py b/neutron/plugins/vmware/dbexts/networkgw_db.py index 40113d129..7463d0b1a 100644 --- a/neutron/plugins/vmware/dbexts/networkgw_db.py +++ b/neutron/plugins/vmware/dbexts/networkgw_db.py @@ -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): diff --git a/neutron/plugins/vmware/dhcp_meta/lsnmanager.py b/neutron/plugins/vmware/dhcp_meta/lsnmanager.py index 9bc80e6c7..4c61a93a8 100644 --- a/neutron/plugins/vmware/dhcp_meta/lsnmanager.py +++ b/neutron/plugins/vmware/dhcp_meta/lsnmanager.py @@ -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) diff --git a/neutron/plugins/vmware/nsxlib/__init__.py b/neutron/plugins/vmware/nsxlib/__init__.py index 8305334c2..c267ecc47 100644 --- a/neutron/plugins/vmware/nsxlib/__init__.py +++ b/neutron/plugins/vmware/nsxlib/__init__.py @@ -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], diff --git a/neutron/plugins/vmware/vshield/vcns.py b/neutron/plugins/vmware/vshield/vcns.py index 6c2835ea2..6b4f24845 100644 --- a/neutron/plugins/vmware/vshield/vcns.py +++ b/neutron/plugins/vmware/vshield/vcns.py @@ -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 diff --git a/neutron/policy.py b/neutron/policy.py index 5ce695f30..5b8344b07 100644 --- a/neutron/policy.py +++ b/neutron/policy.py @@ -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) diff --git a/neutron/services/firewall/drivers/linux/iptables_fwaas.py b/neutron/services/firewall/drivers/linux/iptables_fwaas.py index 7f4a2c12a..71b3b345c 100644 --- a/neutron/services/firewall/drivers/linux/iptables_fwaas.py +++ b/neutron/services/firewall/drivers/linux/iptables_fwaas.py @@ -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'), diff --git a/neutron/services/vpn/service_drivers/__init__.py b/neutron/services/vpn/service_drivers/__init__.py index 8703ebf35..d66e37850 100644 --- a/neutron/services/vpn/service_drivers/__init__.py +++ b/neutron/services/vpn/service_drivers/__init__.py @@ -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( diff --git a/neutron/services/vpn/service_drivers/cisco_ipsec.py b/neutron/services/vpn/service_drivers/cisco_ipsec.py index 28e3d589f..c61d4796e 100644 --- a/neutron/services/vpn/service_drivers/cisco_ipsec.py +++ b/neutron/services/vpn/service_drivers/cisco_ipsec.py @@ -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) diff --git a/neutron/tests/unit/ml2/drivers/cisco/apic/test_cisco_apic_common.py b/neutron/tests/unit/ml2/drivers/cisco/apic/test_cisco_apic_common.py index d2da4ed24..bbb342c4d 100644 --- a/neutron/tests/unit/ml2/drivers/cisco/apic/test_cisco_apic_common.py +++ b/neutron/tests/unit/ml2/drivers/cisco/apic/test_cisco_apic_common.py @@ -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) diff --git a/neutron/tests/unit/vmware/test_nsx_plugin.py b/neutron/tests/unit/vmware/test_nsx_plugin.py index 192ea5784..bd668d671 100644 --- a/neutron/tests/unit/vmware/test_nsx_plugin.py +++ b/neutron/tests/unit/vmware/test_nsx_plugin.py @@ -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), -- 2.45.2