Skip to content

Commit

Permalink
chore: cleanup `len' usage (canonical#5956)
Browse files Browse the repository at this point in the history
In most cases there is no need to calculate length of list of string
values to do something else, just ensuring list or string is not empty
is enough. This will also give a slight performance gain.

Signed-off-by: Shreenidhi Shedi <shreenidhi.shedi@broadcom.com>
  • Loading branch information
sshedi authored and holmanb committed Feb 11, 2025
1 parent 019c321 commit 22d3408
Show file tree
Hide file tree
Showing 42 changed files with 88 additions and 87 deletions.
2 changes: 1 addition & 1 deletion cloudinit/config/cc_apt_configure.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ def apply_debconf_selections(cfg):
LOG.debug("pkgs_cfgd: %s", pkgs_cfgd)
need_reconfig = pkgs_cfgd.intersection(pkgs_installed)

if len(need_reconfig) == 0:
if not need_reconfig:
LOG.debug("no need for reconfig")
return

Expand Down
2 changes: 1 addition & 1 deletion cloudinit/config/cc_byobu.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@


def handle(name: str, cfg: Config, cloud: Cloud, args: list) -> None:
if len(args) != 0:
if args:
value = args[0]
else:
value = util.get_cfg_option_str(cfg, "byobu_by_default", "")
Expand Down
4 changes: 2 additions & 2 deletions cloudinit/config/cc_disk_setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,7 @@ def check_partition_mbr_layout(device, layout):
found_layout = []
for line in out.splitlines():
_line = line.split()
if len(_line) == 0:
if not _line:
continue

if device in _line[0]:
Expand Down Expand Up @@ -500,7 +500,7 @@ def get_partition_mbr_layout(size, layout):
# Create a single partition, default to Linux
return ",,83"

if (len(layout) == 0 and isinstance(layout, list)) or not isinstance(
if ((not layout) and isinstance(layout, list)) or not isinstance(
layout, list
):
raise RuntimeError("Partition layout is invalid")
Expand Down
2 changes: 1 addition & 1 deletion cloudinit/config/cc_final_message.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
def handle(name: str, cfg: Config, cloud: Cloud, args: list) -> None:

msg_in = ""
if len(args) != 0:
if args:
msg_in = str(args[0])
else:
msg_in = util.get_cfg_option_str(cfg, "final_message", "")
Expand Down
2 changes: 1 addition & 1 deletion cloudinit/config/cc_locale.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@


def handle(name: str, cfg: Config, cloud: Cloud, args: list) -> None:
if len(args) != 0:
if args:
locale = args[0]
else:
locale = util.get_cfg_option_str(cfg, "locale", cloud.get_locale())
Expand Down
2 changes: 1 addition & 1 deletion cloudinit/config/cc_mounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -548,7 +548,7 @@ def handle(name: str, cfg: Config, cloud: Cloud, args: list) -> None:
if swapfile:
updated_cfg.append([swapfile, "none", "swap", "sw", "0", "0"])

if len(updated_cfg) == 0:
if not updated_cfg:
# This will only be true if there is no mount configuration at all
# Even if fstab has no functional changes, we'll get past this point
# as we remove any 'comment=cloudconfig' lines and then add them back
Expand Down
10 changes: 3 additions & 7 deletions cloudinit/config/cc_ntp.py
Original file line number Diff line number Diff line change
Expand Up @@ -427,18 +427,14 @@ def write_ntp_config_template(
if not peers:
peers = []

if len(servers) == 0 and len(pools) == 0 and distro_name == "cos":
if not servers and not pools and distro_name == "cos":
return
if (
len(servers) == 0
and distro_name == "alpine"
and service_name == "ntpd"
):
if not servers and distro_name == "alpine" and service_name == "ntpd":
# Alpine's Busybox ntpd only understands "servers" configuration
# and not "pool" configuration.
servers = generate_server_names(distro_name)
LOG.debug("Adding distro default ntp servers: %s", ",".join(servers))
elif len(servers) == 0 and len(pools) == 0:
elif not (servers) and not (pools):
pools = generate_server_names(distro_name)
LOG.debug(
"Adding distro default ntp pool servers: %s", ",".join(pools)
Expand Down
2 changes: 1 addition & 1 deletion cloudinit/config/cc_phone_home.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@


def handle(name: str, cfg: Config, cloud: Cloud, args: list) -> None:
if len(args) != 0:
if args:
ph_cfg = util.read_conf(args[0])
else:
if "phone_home" not in cfg:
Expand Down
2 changes: 1 addition & 1 deletion cloudinit/config/cc_resizefs.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ def maybe_get_writable_device_path(devpath, info):


def handle(name: str, cfg: Config, cloud: Cloud, args: list) -> None:
if len(args) != 0:
if args:
resize_root = args[0]
else:
resize_root = util.get_cfg_option_str(cfg, "resize_rootfs", True)
Expand Down
4 changes: 2 additions & 2 deletions cloudinit/config/cc_rh_subscription.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,7 @@ def addPool(self, pools):
"""

# An empty list was passed
if len(pools) == 0:
if not pools:
self.log.debug("No pools to attach")
return True

Expand Down Expand Up @@ -379,7 +379,7 @@ def update_repos(self):
return False

# Bail if both lists are not populated
if (len(erepos) == 0) and (len(drepos) == 0):
if not (erepos) and not (drepos):
self.log.debug("No repo IDs to enable or disable")
return True

Expand Down
2 changes: 1 addition & 1 deletion cloudinit/config/cc_ssh_import_id.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def handle(name: str, cfg: Config, cloud: Cloud, args: list) -> None:
return

# import for "user: XXXXX"
if len(args) != 0:
if args:
user = args[0]
ids = []
if len(args) > 1:
Expand Down
2 changes: 1 addition & 1 deletion cloudinit/config/cc_timezone.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@


def handle(name: str, cfg: Config, cloud: Cloud, args: list) -> None:
if len(args) != 0:
if args:
timezone = args[0]
else:
timezone = util.get_cfg_option_str(cfg, "timezone", False)
Expand Down
2 changes: 1 addition & 1 deletion cloudinit/distros/aosc.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ def update_locale_conf(sys_path, locale_cfg):
if v is None:
continue
v = str(v)
if len(v) == 0:
if not v:
continue
contents[k] = v
updated_am += 1
Expand Down
2 changes: 1 addition & 1 deletion cloudinit/distros/parsers/ifconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ def parse(self, text: str) -> Dict[str, Union[Ifstate, List[Ifstate]]]:
ifs_by_mac = defaultdict(list)
dev = None
for line in text.splitlines():
if len(line) == 0:
if not line:
continue
if line[0] not in ("\t", " "):
# We hit the start of a device block in the ifconfig output
Expand Down
2 changes: 1 addition & 1 deletion cloudinit/distros/parsers/sys_conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ def __str__(self):
def _quote(self, value, multiline=False):
if not isinstance(value, str):
raise ValueError('Value "%s" is not a string' % (value))
if len(value) == 0:
if not value:
return ""
quot_func = None
if value[0] in ['"', "'"] and value[-1] in ['"', "'"]:
Expand Down
2 changes: 1 addition & 1 deletion cloudinit/distros/rhel_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def update_sysconfig_file(fn, adjustments, allow_empty=False):
if v is None:
continue
v = str(v)
if len(v) == 0 and not allow_empty:
if (not v) and (not allow_empty):
continue
contents[k] = v
updated_am += 1
Expand Down
2 changes: 1 addition & 1 deletion cloudinit/net/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -828,7 +828,7 @@ def find_entry(mac, driver, device_id):
"up": Iproute2.link_up,
}

if len(ops) + len(ups) == 0:
if not (ops) and not (ups):
if len(errors):
LOG.warning(
"Unable to rename interfaces: %s due to errors: %s",
Expand Down
2 changes: 1 addition & 1 deletion cloudinit/net/dhcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ def parse_leases(lease_content: str) -> List[Dict[str, Any]]:
"""
lease_regex = re.compile(r"lease {(?P<lease>.*?)}\n", re.DOTALL)
dhcp_leases: List[Dict] = []
if len(lease_content) == 0:
if not lease_content:
return []
for lease in lease_regex.findall(lease_content):
lease_options = []
Expand Down
2 changes: 1 addition & 1 deletion cloudinit/net/sysconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -938,7 +938,7 @@ def _render_networkmanager_conf(network_state, templates=None):
):
content.set_section_keypair("main", "dns", "none")

if len(content) == 0:
if not content:
return None
out = "".join([_make_header(), "\n", "\n".join(content.write()), "\n"])
return out
Expand Down
13 changes: 8 additions & 5 deletions cloudinit/netinfo.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ def _netdev_info_ifconfig_netbsd(ifconfig_data):
# fields that need to be returned in devs for each dev
devs = {}
for line in ifconfig_data.splitlines():
if len(line) == 0:
if not line:
continue
if line[0] not in ("\t", " "):
curdev = line.split()[0]
Expand Down Expand Up @@ -237,7 +237,7 @@ def _netdev_info_ifconfig(ifconfig_data):
# fields that need to be returned in devs for each dev
devs = {}
for line in ifconfig_data.splitlines():
if len(line) == 0:
if not line:
continue
if line[0] not in ("\t", " "):
curdev = line.split()[0]
Expand Down Expand Up @@ -587,7 +587,8 @@ def netdev_pformat():
fields = ["Device", "Up", "Address", "Mask", "Scope", "Hw-Address"]
tbl = SimpleTable(fields)
for dev, data in sorted(netdev.items()):
for addr in data.get("ipv4"):
ipv4_addrs = data.get("ipv4")
for addr in ipv4_addrs:
tbl.add_row(
(
dev,
Expand All @@ -598,7 +599,9 @@ def netdev_pformat():
data["hwaddr"],
)
)
for addr in data.get("ipv6"):

ipv6_addrs = data.get("ipv6")
for addr in ipv6_addrs:
tbl.add_row(
(
dev,
Expand All @@ -609,7 +612,7 @@ def netdev_pformat():
data["hwaddr"],
)
)
if len(data.get("ipv6")) + len(data.get("ipv4")) == 0:
if not (ipv4_addrs) and not (ipv6_addrs):
tbl.add_row(
(dev, data["up"], empty, empty, empty, data["hwaddr"])
)
Expand Down
2 changes: 1 addition & 1 deletion cloudinit/reporting/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,7 @@ def _break_down(self, key, meta_data, description):
result_array.append(self._encode_kvp_item(subkey, value))
i += 1
des_in_json = des_in_json[room_for_desc:]
if len(des_in_json) == 0:
if not des_in_json:
break
return result_array

Expand Down
9 changes: 6 additions & 3 deletions cloudinit/sources/DataSourceAzure.py
Original file line number Diff line number Diff line change
Expand Up @@ -1733,15 +1733,18 @@ def can_dev_be_reformatted(devpath, preserve_ntfs):
# devpath of /dev/sd[a-z] or /dev/disk/cloud/azure_resource
# where partitions are "<devpath>1" or "<devpath>-part1" or "<devpath>p1"
partitions = _partitions_on_device(devpath)
if len(partitions) == 0:
if not partitions:
return False, "device %s was not partitioned" % devpath
elif len(partitions) > 2:

partition_len = len(partitions)
if partition_len > 2:
msg = "device %s had 3 or more partitions: %s" % (
devpath,
" ".join([p[1] for p in partitions]),
)
return False, msg
elif len(partitions) == 2:

if partition_len == 2:
cand_part, cand_path = partitions[1]
else:
cand_part, cand_path = partitions[0]
Expand Down
2 changes: 1 addition & 1 deletion cloudinit/sources/DataSourceEc2.py
Original file line number Diff line number Diff line change
Expand Up @@ -895,7 +895,7 @@ def _build_nic_order(
@return: Dictionary with macs as keys and nic orders as values.
"""
nic_order: Dict[str, int] = {}
if len(macs_to_nics) == 0 or len(macs_metadata) == 0:
if (not macs_to_nics) or (not macs_metadata):
return nic_order

valid_macs_metadata = filter(
Expand Down
4 changes: 2 additions & 2 deletions cloudinit/sources/DataSourceMAAS.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ def get_id_from_ds_cfg(ds_cfg):
def read_maas_seed_dir(seed_d):
if seed_d.startswith("file://"):
seed_d = seed_d[7:]
if not os.path.isdir(seed_d) or len(os.listdir(seed_d)) == 0:
if not os.path.isdir(seed_d) or not os.listdir(seed_d):
raise MAASSeedDirNone("%s: not a directory")

# seed_dir looks in seed_dir, not seed_dir/VERSION
Expand Down Expand Up @@ -283,7 +283,7 @@ def check_seed_contents(content, seed):
else:
ret[dpath] = content[spath]

if len(ret) == 0:
if not ret:
raise MAASSeedDirNone("%s: no data files found" % seed)

if missing:
Expand Down
2 changes: 1 addition & 1 deletion cloudinit/sources/DataSourceNoCloud.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ def _pp2d_callback(mp, data):

# There was no indication on kernel cmdline or data
# in the seeddir suggesting this handler should be used.
if len(found) == 0:
if not found:
return False

# The special argument "seedfrom" indicates we should
Expand Down
4 changes: 2 additions & 2 deletions cloudinit/sources/DataSourceOVF.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def _get_data(self):
found.append(name)

# There was no OVF transports found
if len(found) == 0:
if not found:
return False

if "seedfrom" in md and md["seedfrom"]:
Expand Down Expand Up @@ -372,7 +372,7 @@ def get_properties(contents):
dom.documentElement, lambda n: n.localName == "PropertySection"
)

if len(propSections) == 0:
if not propSections:
raise XmlError("No 'PropertySection's")

props = {}
Expand Down
2 changes: 1 addition & 1 deletion cloudinit/sources/DataSourceSmartOS.py
Original file line number Diff line number Diff line change
Expand Up @@ -438,7 +438,7 @@ def as_ascii():
while True:
try:
byte = self.fp.read(1)
if len(byte) == 0:
if not byte:
raise JoyentMetadataTimeoutException(msg % as_ascii())
if byte == b"\n":
return as_ascii()
Expand Down
2 changes: 1 addition & 1 deletion cloudinit/sources/DataSourceVMware.py
Original file line number Diff line number Diff line change
Expand Up @@ -500,7 +500,7 @@ def get_none_if_empty_val(val):
# simplify the rest of this function's logic.
val = util.decode_binary(val)
val = val.rstrip()
if len(val) == 0 or val == GUESTINFO_EMPTY_YAML_VAL:
if (not val) or (val == GUESTINFO_EMPTY_YAML_VAL):
return None
return val

Expand Down
8 changes: 4 additions & 4 deletions cloudinit/sources/DataSourceWSL.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,14 +237,14 @@ def merge_agent_landscape_data(
cloud-init to merge separate parts.
"""
# Ignore agent_data if None or empty
if agent_data is None or len(agent_data.raw) == 0:
if user_data is None or len(user_data.raw) == 0:
if (agent_data is None) or (not agent_data.raw):
if (user_data is None) or (not user_data.raw):
return None
return user_data.raw

# Ignore user_data if None or empty
if user_data is None or len(user_data.raw) == 0:
if agent_data is None or len(agent_data.raw) == 0:
if (user_data is None) or (not user_data.raw):
if (agent_data is None) or (not agent_data.raw):
return None
return agent_data.raw

Expand Down
7 changes: 4 additions & 3 deletions cloudinit/sources/helpers/azure.py
Original file line number Diff line number Diff line change
Expand Up @@ -1034,7 +1034,7 @@ def _find(
matches = node.findall(
"./%s:%s" % (namespace, name), OvfEnvXml.NAMESPACES
)
if len(matches) == 0:
if not matches:
msg = "missing configuration for %r" % name
LOG.debug(msg)
if required:
Expand All @@ -1058,13 +1058,14 @@ def _parse_property(
default=None,
):
matches = node.findall("./wa:" + name, OvfEnvXml.NAMESPACES)
if len(matches) == 0:
if not matches:
msg = "missing configuration for %r" % name
LOG.debug(msg)
if required:
raise errors.ReportableErrorOvfInvalidMetadata(msg)
return default
elif len(matches) > 1:

if len(matches) > 1:
raise errors.ReportableErrorOvfInvalidMetadata(
"multiple configuration matches for %r (%d)"
% (name, len(matches))
Expand Down
Loading

0 comments on commit 22d3408

Please sign in to comment.