Skip to content

Commit

Permalink
refactor: Make SysUtil.link_info_find() more pythonic
Browse files Browse the repository at this point in the history
- Removed the unnecessary `refresh` argument since it wasn't used.
- Used `None` checks more idiomatically with `if mac` instead of `is not None`.
- Eliminated redundant variables and conditions to improve readability.
- Avoided using `locals()` by explicitly storing fallback results.
- Made `ifname` matching take priority before checking MAC addresses.
- Ensured that the function returns early when a definitive match is found.

Signed-off-by: Wen Liang <[email protected]>
  • Loading branch information
liangwen12year authored and Wen Liang committed Feb 11, 2025
1 parent 46c3cea commit 894645b
Showing 1 changed file with 17 additions and 19 deletions.
36 changes: 17 additions & 19 deletions library/network_connections.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@

DEFAULT_ACTIVATION_TIMEOUT = 90
DEFAULT_TIMEOUT = 10
NULL_MAC = "00:00:00:00:00:00"


class CheckMode:
Expand Down Expand Up @@ -222,31 +223,28 @@ def link_infos(cls, refresh=False):
return linkinfos

@classmethod
def link_info_find(cls, refresh=False, mac=None, ifname=None):
if mac is not None:
def link_info_find(cls, mac=None, ifname=None):
if mac:
mac = Util.mac_norm(mac)
for linkinfo in cls.link_infos(refresh).values():
perm_address = linkinfo.get("perm-address", None)
current_address = linkinfo.get("address", None)

# Match by perm-address (prioritized)
if mac is not None and perm_address not in [None, "00:00:00:00:00:00"]:
if mac == perm_address:
return linkinfo
result = None

# Fallback to match by address
if mac is not None and (perm_address in [None, "00:00:00:00:00:00"]):
if mac == current_address:
matched_by_address = linkinfo # Save for potential fallback
for linkinfo in cls.link_infos().values():
perm_address = linkinfo.get("perm-address", NULL_MAC)
current_address = linkinfo.get("address", NULL_MAC)

if ifname is not None and ifname == linkinfo.get("ifname", None):
return linkinfo
if ifname and ifname == linkinfo["ifname"]:
result = linkinfo
break

# Return fallback match by address if no perm-address match found
if "matched_by_address" in locals():
return matched_by_address
if mac:
if perm_address != NULL_MAC and mac == perm_address:
result = linkinfo
break
elif perm_address == NULL_MAC and mac == current_address:
result = linkinfo

return None
return result


###############################################################################
Expand Down

0 comments on commit 894645b

Please sign in to comment.