Skip to content

Commit 46a5b71

Browse files
authored
Fix issues reported by ruff RET rule in Python bindings (project-chip#42154)
1 parent 318d81e commit 46a5b71

File tree

16 files changed

+95
-124
lines changed

16 files changed

+95
-124
lines changed

src/controller/python/matter/ChipBluezMgr.py

Lines changed: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -187,8 +187,7 @@ def adapter_bg_scan(self, enable):
187187
@property
188188
def Address(self):
189189
try:
190-
result = self.adapter_properties.Get(ADAPTER_INTERFACE, "Address")
191-
return result
190+
return self.adapter_properties.Get(ADAPTER_INTERFACE, "Address")
192191
except dbus.exceptions.DBusException as ex:
193192
LOGGER.debug(str(ex))
194193
return None
@@ -455,8 +454,7 @@ def Address(self):
455454
@property
456455
def Name(self):
457456
try:
458-
name = self.device_properties.Get(DEVICE_INTERFACE, "Name")
459-
return name
457+
return self.device_properties.Get(DEVICE_INTERFACE, "Name")
460458
except dbus.exceptions.DBusException as ex:
461459
LOGGER.debug(str(ex))
462460
return None
@@ -490,8 +488,7 @@ def TxPower(self):
490488
@property
491489
def RSSI(self):
492490
try:
493-
result = self.device_properties.Get(DEVICE_INTERFACE, "RSSI")
494-
return result
491+
return self.device_properties.Get(DEVICE_INTERFACE, "RSSI")
495492
except dbus.exceptions.DBusException as ex:
496493
LOGGER.debug(str(ex))
497494
return None
@@ -559,10 +556,9 @@ def destroy(self):
559556
@property
560557
def uuid(self):
561558
try:
562-
result = uuid.UUID(
559+
return uuid.UUID(
563560
str(self.service_properties.Get(SERVICE_INTERFACE, "UUID"))
564561
)
565-
return result
566562
except dbus.exceptions.DBusException as ex:
567563
LOGGER.debug(str(ex))
568564
return None
@@ -573,9 +569,8 @@ def uuid(self):
573569
@property
574570
def Primary(self):
575571
try:
576-
result = bool(self.service_properties.Get(
572+
return bool(self.service_properties.Get(
577573
SERVICE_INTERFACE, "Primary"))
578-
return result
579574
except dbus.exceptions.DBusException as ex:
580575
LOGGER.debug(str(ex))
581576
return False
@@ -586,8 +581,7 @@ def Primary(self):
586581
@property
587582
def Device(self):
588583
try:
589-
result = self.service_properties.Get(SERVICE_INTERFACE, "Device")
590-
return result
584+
return self.service_properties.Get(SERVICE_INTERFACE, "Device")
591585
except dbus.exceptions.DBusException as ex:
592586
LOGGER.debug(str(ex))
593587
return None
@@ -707,13 +701,12 @@ def WriteValue(self, value, options, reply_handler, error_handler, timeout):
707701
@property
708702
def uuid(self):
709703
try:
710-
result = uuid.UUID(
704+
return uuid.UUID(
711705
str(
712706
self.characteristic_properties.Get(
713707
CHARACTERISTIC_INTERFACE, "UUID")
714708
)
715709
)
716-
return result
717710
except dbus.exceptions.DBusException as ex:
718711
LOGGER.debug(str(ex))
719712
return None

src/controller/python/matter/ChipCoreBluetoothMgr.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,7 @@ def shouldLoop(self, cond: LoopCondition):
213213

214214
if cond.op == "ready":
215215
return not self.ready_condition
216-
elif cond.op == "scan":
216+
if cond.op == "scan":
217217
for peripheral in self.peripheral_adv_list:
218218
if cond.arg and str(peripheral.peripheral._.name) == cond.arg:
219219
return False
@@ -444,13 +444,13 @@ def GetBleEvent(self):
444444
if isinstance(ev, BleRxEvent):
445445
eventStruct = BleRxEventStruct.fromBleRxEvent(ev)
446446
return cast(pointer(eventStruct), c_void_p).value
447-
elif isinstance(ev, BleTxEvent):
447+
if isinstance(ev, BleTxEvent):
448448
eventStruct = BleTxEventStruct.fromBleTxEvent(ev)
449449
return cast(pointer(eventStruct), c_void_p).value
450-
elif isinstance(ev, BleSubscribeEvent):
450+
if isinstance(ev, BleSubscribeEvent):
451451
eventStruct = BleSubscribeEventStruct.fromBleSubscribeEvent(ev)
452452
return cast(pointer(eventStruct), c_void_p).value
453-
elif isinstance(ev, BleDisconnectEvent):
453+
if isinstance(ev, BleDisconnectEvent):
454454
eventStruct = BleDisconnectEventStruct.fromBleDisconnectEvent(
455455
ev)
456456
return cast(pointer(eventStruct), c_void_p).value

src/controller/python/matter/ChipDeviceCtrl.py

Lines changed: 43 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -1519,9 +1519,8 @@ def ComputeRoundTripTimeout(self, nodeId: int, upperLayerProcessingTimeoutMs: in
15191519
int: The computed timeout value in milliseconds, representing the round-trip time.
15201520
'''
15211521
device = self.GetConnectedDeviceSync(nodeId)
1522-
res = self._ChipStack.Call(lambda: self._dmLib.pychip_DeviceProxy_ComputeRoundTripTimeout(
1522+
return self._ChipStack.Call(lambda: self._dmLib.pychip_DeviceProxy_ComputeRoundTripTimeout(
15231523
device.deviceProxy, upperLayerProcessingTimeoutMs))
1524-
return res
15251524

15261525
def GetRemoteSessionParameters(self, nodeId: int) -> typing.Optional[SessionParameters]:
15271526
'''
@@ -1774,7 +1773,7 @@ def SendGroupCommand(self, groupid: int, payload: ClusterObjects.ClusterCommand,
17741773
groupid, self.devCtrl, payload, busyWaitMs=busyWaitMs).raise_on_error()
17751774

17761775
# None is the expected return for sending group commands.
1777-
return None
1776+
return
17781777

17791778
async def WriteAttribute(self, nodeId: int,
17801779
attributes: typing.List[typing.Union[
@@ -1968,29 +1967,26 @@ def _parseAttributePathTuple(self, pathTuple: typing.Union[
19681967
if pathTuple == ('*') or pathTuple == ():
19691968
# Wildcard
19701969
return ClusterAttribute.AttributePath()
1971-
elif not isinstance(pathTuple, tuple):
1970+
if not isinstance(pathTuple, tuple):
19721971
if isinstance(pathTuple, int):
19731972
return ClusterAttribute.AttributePath(EndpointId=pathTuple)
1974-
elif issubclass(pathTuple, ClusterObjects.Cluster): # type: ignore[misc, arg-type]
1973+
if issubclass(pathTuple, ClusterObjects.Cluster): # type: ignore[misc, arg-type]
19751974
return ClusterAttribute.AttributePath.from_cluster(EndpointId=None, Cluster=pathTuple) # type: ignore[arg-type]
1976-
elif issubclass(pathTuple, ClusterObjects.ClusterAttributeDescriptor): # type: ignore[arg-type]
1975+
if issubclass(pathTuple, ClusterObjects.ClusterAttributeDescriptor): # type: ignore[arg-type]
19771976
return ClusterAttribute.AttributePath.from_attribute(EndpointId=None, Attribute=pathTuple) # type: ignore[arg-type]
1978-
else:
1979-
raise ValueError("Unsupported Attribute Path")
1980-
else:
1981-
# endpoint + (cluster) attribute / endpoint + cluster
1982-
if issubclass(pathTuple[1], ClusterObjects.Cluster): # type: ignore[misc]
1983-
return ClusterAttribute.AttributePath.from_cluster(
1984-
EndpointId=pathTuple[0], # type: ignore[arg-type]
1985-
Cluster=pathTuple[1] # type: ignore[arg-type, misc]
1986-
)
1987-
elif issubclass(pathTuple[1], ClusterAttribute.ClusterAttributeDescriptor): # type: ignore[arg-type, misc]
1988-
return ClusterAttribute.AttributePath.from_attribute(
1989-
EndpointId=pathTuple[0], # type: ignore[arg-type]
1990-
Attribute=pathTuple[1] # type: ignore[arg-type, misc]
1991-
)
1992-
else:
1993-
raise ValueError("Unsupported Attribute Path")
1977+
raise ValueError("Unsupported Attribute Path")
1978+
# endpoint + (cluster) attribute / endpoint + cluster
1979+
if issubclass(pathTuple[1], ClusterObjects.Cluster): # type: ignore[misc]
1980+
return ClusterAttribute.AttributePath.from_cluster(
1981+
EndpointId=pathTuple[0], # type: ignore[arg-type]
1982+
Cluster=pathTuple[1] # type: ignore[arg-type, misc]
1983+
)
1984+
if issubclass(pathTuple[1], ClusterAttribute.ClusterAttributeDescriptor): # type: ignore[arg-type, misc]
1985+
return ClusterAttribute.AttributePath.from_attribute(
1986+
EndpointId=pathTuple[0], # type: ignore[arg-type]
1987+
Attribute=pathTuple[1] # type: ignore[arg-type, misc]
1988+
)
1989+
raise ValueError("Unsupported Attribute Path")
19941990

19951991
def _parseDataVersionFilterTuple(self, pathTuple: typing.List[typing.Tuple[int, typing.Type[ClusterObjects.Cluster], int]]):
19961992
endpoint = None
@@ -2027,40 +2023,36 @@ def _parseEventPathTuple(self, pathTuple: typing.Union[
20272023
if pathTuple in [('*'), ()]:
20282024
# Wildcard
20292025
return ClusterAttribute.EventPath()
2030-
elif not isinstance(pathTuple, tuple):
2026+
if not isinstance(pathTuple, tuple):
20312027
# mypy refactor (PR https://github.com/project-chip/connectedhomeip/pull/39827):
20322028
# instantiate class types before passing to from_cluster/from_event
20332029
# because these expect instances, not classes.
20342030
if isinstance(pathTuple, int):
20352031
return ClusterAttribute.EventPath(EndpointId=pathTuple)
2036-
elif isinstance(pathTuple, type) and issubclass(pathTuple, ClusterObjects.Cluster):
2032+
if isinstance(pathTuple, type) and issubclass(pathTuple, ClusterObjects.Cluster):
20372033
return ClusterAttribute.EventPath.from_cluster(EndpointId=None, Cluster=pathTuple)
2038-
elif isinstance(pathTuple, type) and issubclass(pathTuple, ClusterObjects.ClusterEvent):
2034+
if isinstance(pathTuple, type) and issubclass(pathTuple, ClusterObjects.ClusterEvent):
20392035
return ClusterAttribute.EventPath.from_event(EndpointId=None, Event=pathTuple)
2040-
else:
2041-
raise ValueError("Unsupported Event Path")
2042-
else:
2043-
if pathTuple[0] == '*':
2044-
return ClusterAttribute.EventPath(Urgent=pathTuple[-1])
2045-
else:
2046-
urgent = bool(pathTuple[-1]) if len(pathTuple) > 2 else False
2047-
# endpoint + (cluster) event / endpoint + cluster
2048-
# mypy errors ignored due to valid use of dynamic types (e.g., int, str, or class types).
2049-
# Fixing these typing errors is a high risk to affect existing functionality.
2050-
# These mismatches are intentional and safe within the current logic.
2051-
if issubclass(pathTuple[1], ClusterObjects.Cluster): # type: ignore[arg-type]
2052-
return ClusterAttribute.EventPath.from_cluster(
2053-
EndpointId=pathTuple[0], # type: ignore[arg-type]
2054-
Cluster=pathTuple[1], Urgent=urgent # type: ignore[arg-type]
2055-
)
2056-
elif issubclass(pathTuple[1], ClusterAttribute.ClusterEvent): # type: ignore[arg-type]
2057-
return ClusterAttribute.EventPath.from_event(
2058-
EndpointId=pathTuple[0], # type: ignore[arg-type]
2059-
Event=pathTuple[1], # type: ignore[arg-type]
2060-
Urgent=urgent
2061-
)
2062-
else:
2063-
raise ValueError("Unsupported Attribute Path")
2036+
raise ValueError("Unsupported Event Path")
2037+
if pathTuple[0] == '*':
2038+
return ClusterAttribute.EventPath(Urgent=pathTuple[-1])
2039+
urgent = bool(pathTuple[-1]) if len(pathTuple) > 2 else False
2040+
# endpoint + (cluster) event / endpoint + cluster
2041+
# mypy errors ignored due to valid use of dynamic types (e.g., int, str, or class types).
2042+
# Fixing these typing errors is a high risk to affect existing functionality.
2043+
# These mismatches are intentional and safe within the current logic.
2044+
if issubclass(pathTuple[1], ClusterObjects.Cluster): # type: ignore[arg-type]
2045+
return ClusterAttribute.EventPath.from_cluster(
2046+
EndpointId=pathTuple[0], # type: ignore[arg-type]
2047+
Cluster=pathTuple[1], Urgent=urgent # type: ignore[arg-type]
2048+
)
2049+
if issubclass(pathTuple[1], ClusterAttribute.ClusterEvent): # type: ignore[arg-type]
2050+
return ClusterAttribute.EventPath.from_event(
2051+
EndpointId=pathTuple[0], # type: ignore[arg-type]
2052+
Event=pathTuple[1], # type: ignore[arg-type]
2053+
Urgent=urgent
2054+
)
2055+
raise ValueError("Unsupported Attribute Path")
20642056

20652057
async def Read(
20662058
self,
@@ -2275,8 +2267,7 @@ async def ReadAttribute(
22752267
payloadCapability=payloadCapability)
22762268
if isinstance(res, ClusterAttribute.SubscriptionTransaction):
22772269
return res
2278-
else:
2279-
return res.attributes
2270+
return res.attributes
22802271

22812272
async def ReadEvent(
22822273
self,
@@ -2349,8 +2340,7 @@ async def ReadEvent(
23492340
autoResubscribe=autoResubscribe, payloadCapability=payloadCapability)
23502341
if isinstance(res, ClusterAttribute.SubscriptionTransaction):
23512342
return res
2352-
else:
2353-
return res.events
2343+
return res.events
23542344

23552345
def SetIpk(self, ipk: bytes):
23562346
'''

src/controller/python/matter/clusters/Attribute.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -464,8 +464,7 @@ def GetAttribute(self, path: TypedAttributePath) -> Any:
464464

465465
if (self._readTransaction._cache.returnClusterObject):
466466
return eval(f'data[path.Path.EndpointId][path.ClusterType].{path.AttributeName}')
467-
else:
468-
return data[path.Path.EndpointId][path.ClusterType][path.AttributeType]
467+
return data[path.Path.EndpointId][path.ClusterType][path.AttributeType]
469468

470469
def GetEvents(self):
471470
return self._readTransaction.GetAllEventValues()

src/controller/python/matter/commissioning/commissioning_flow_blocks.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -209,7 +209,7 @@ async def network_commissioning(self, parameter: commissioning.Parameters, node_
209209
if Clusters.NetworkCommissioning.id not in clusters[commissioning.ROOT_ENDPOINT_ID][Clusters.Descriptor].serverList:
210210
self._logger.info(
211211
f"Network commissioning cluster {commissioning.ROOT_ENDPOINT_ID} is not enabled on this device.")
212-
return
212+
return None
213213

214214
network_commissioning_cluster_state = (await self._devCtrl.ReadAttribute(
215215
nodeId=node_id,
@@ -220,16 +220,17 @@ async def network_commissioning(self, parameter: commissioning.Parameters, node_
220220
if networks.connected:
221221
self._logger.info(
222222
f"Device already connected to {networks.networkID.hex()} skip network commissioning")
223-
return
223+
return None
224224

225225
if parameter.commissionee_info.is_wifi_device:
226226
if network_commissioning_cluster_state.featureMap != commissioning.NetworkCommissioningFeatureMap.WIFI_NETWORK_FEATURE_MAP:
227227
raise AssertionError("Device is expected to be a WiFi device")
228228
return await self.network_commissioning_wifi(parameter=parameter, node_id=node_id)
229-
elif parameter.commissionee_info.is_thread_device:
229+
if parameter.commissionee_info.is_thread_device:
230230
if network_commissioning_cluster_state.featureMap != commissioning.NetworkCommissioningFeatureMap.THREAD_NETWORK_FEATURE_MAP:
231231
raise AssertionError("Device is expected to be a Thread device")
232232
return await self.network_commissioning_thread(parameter=parameter, node_id=node_id)
233+
return None
233234

234235
async def send_regulatory_config(self, parameter: commissioning.Parameters, node_id: int):
235236
self._logger.info("Sending Regulatory Config")

src/controller/python/matter/interaction_model/__init__.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,8 +100,7 @@ def __init__(self, status: Status, clusterStatus: int = kUndefinedClusterStatus)
100100
def __str__(self):
101101
if self.hasClusterStatus:
102102
return f"InteractionModelError: {self._status.name} (0x{self._status.value:x}, clusterStatus: {self._clusterStatus})"
103-
else:
104-
return f"InteractionModelError: {self._status.name} (0x{self._status.value:x})"
103+
return f"InteractionModelError: {self._status.name} (0x{self._status.value:x})"
105104

106105
@property
107106
def hasClusterStatus(self) -> bool:

src/controller/python/matter/tlv/__init__.py

Lines changed: 12 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -403,25 +403,21 @@ def _encodeControlAndTag(self, type, tag, lenOfLenOrVal=0):
403403
if tagNum <= UINT16_MAX:
404404
controlByte |= TLV_TAG_CONTROL_IMPLICIT_PROFILE_2Bytes
405405
return struct.pack("<BH", controlByte, tagNum)
406-
else:
407-
controlByte |= TLV_TAG_CONTROL_IMPLICIT_PROFILE_4Bytes
408-
return struct.pack("<BL", controlByte, tagNum)
409-
elif profile == 0:
406+
controlByte |= TLV_TAG_CONTROL_IMPLICIT_PROFILE_4Bytes
407+
return struct.pack("<BL", controlByte, tagNum)
408+
if profile == 0:
410409
if tagNum <= UINT16_MAX:
411410
controlByte |= TLV_TAG_CONTROL_COMMON_PROFILE_2Bytes
412411
return struct.pack("<BH", controlByte, tagNum)
413-
else:
414-
controlByte |= TLV_TAG_CONTROL_COMMON_PROFILE_4Bytes
415-
return struct.pack("<BL", controlByte, tagNum)
416-
else:
417-
vendorId = (profile >> 16) & 0xFFFF
418-
profileNum = (profile >> 0) & 0xFFFF
419-
if tagNum <= UINT16_MAX:
420-
controlByte |= TLV_TAG_CONTROL_FULLY_QUALIFIED_6Bytes
421-
return struct.pack("<BHHH", controlByte, vendorId, profileNum, tagNum)
422-
else:
423-
controlByte |= TLV_TAG_CONTROL_FULLY_QUALIFIED_8Bytes
424-
return struct.pack("<BHHL", controlByte, vendorId, profileNum, profile, tagNum)
412+
controlByte |= TLV_TAG_CONTROL_COMMON_PROFILE_4Bytes
413+
return struct.pack("<BL", controlByte, tagNum)
414+
vendorId = (profile >> 16) & 0xFFFF
415+
profileNum = (profile >> 0) & 0xFFFF
416+
if tagNum <= UINT16_MAX:
417+
controlByte |= TLV_TAG_CONTROL_FULLY_QUALIFIED_6Bytes
418+
return struct.pack("<BHHH", controlByte, vendorId, profileNum, tagNum)
419+
controlByte |= TLV_TAG_CONTROL_FULLY_QUALIFIED_8Bytes
420+
return struct.pack("<BHHL", controlByte, vendorId, profileNum, profile, tagNum)
425421
raise ValueError("Invalid object given for TLV tag")
426422

427423
@staticmethod

src/controller/python/matter/tlv/tlvlist.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -87,14 +87,12 @@ def as_tuple(self):
8787
def as_rich_repr_tuple(self):
8888
if self.tag is None:
8989
return "Anonymous", repr(self.value)
90-
else:
91-
return str(self.tag), repr(self.value)
90+
return str(self.tag), repr(self.value)
9291

9392
def __repr__(self):
9493
if self.tag is None:
9594
return "Anonymous: " + repr(self.value)
96-
else:
97-
return str(self.tag) + ": " + repr(self.value)
95+
return str(self.tag) + ": " + repr(self.value)
9896

9997
def __rich_repr__(self):
10098
yield self.as_rich_repr_tuple()
@@ -146,10 +144,10 @@ def __getitem__(self, access) -> Any:
146144
tag, index = access.start, access.stop
147145
if tag == TLVList.IndexMethod.Tag:
148146
return self._get_item_by_tag(index)
149-
elif tag == TLVList.IndexMethod.Index:
147+
if tag == TLVList.IndexMethod.Index:
150148
return self._data[index].as_tuple()
151149
raise ValueError("Method should be TLVList.IndexMethod.Tag or TLVList.IndexMethod.Index")
152-
elif isinstance(access, int):
150+
if isinstance(access, int):
153151
return self._get_item_by_tag(access)
154152
raise ValueError("Invalid access method")
155153

src/controller/python/matter/webrtc/browser_peer_connection.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -255,7 +255,7 @@ async def check_for_session_establishment(self) -> bool:
255255
PeerConnectionState.INVALID,
256256
]:
257257
return False
258-
elif self._peer_state == PeerConnectionState.CONNECTED:
258+
if self._peer_state == PeerConnectionState.CONNECTED:
259259
return True
260260
self._peer_state = await event_queue.get(timeout=30)
261261

src/controller/python/matter/webrtc/browser_webrtc_client.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,8 +72,7 @@ async def get_local_description(self):
7272

7373
async def get_peer_connection_state(self):
7474
event = "GET_PEER_CONNECTION_STATE"
75-
state = await self.send_message(event)
76-
return state
75+
return await self.send_message(event)
7776

7877
def on_gathering_complete(self, callback):
7978
self.event_callbacks["GATHERING_STATE_COMPLETE"] = callback

0 commit comments

Comments
 (0)