Fix Optional handling for node IDs and PDO variables#650
Fix Optional handling for node IDs and PDO variables#650bizfsc wants to merge 1 commit intocanopen-python:masterfrom
Conversation
- Annotate BaseNode.id as Optional[int] to match its runtime value - Add assert + re-annotation in RemoteNode/LocalNode to narrow to int - Add asserts for PdoVariable.offset and pdo_parent before use - Fix wait_for_reception return type to Optional[float]
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
|
I think this is going in the wrong direction. The possibility of The intention here (according to the docstring) is that a dummy value can be passed for What do you think? Should we try the opposite way and restrict |
|
Agreed — this is the right direction. Making self.id Optional just pushes the problem downstream to every caller. It's better to enforce a valid ID at construction time. The current pattern node_id or self.object_dictionary.node_id already treats 0 and None identically as "unspecified", which aligns with your suggestion. The fix would be: if the result is still None (or 0), raise a ValueError in BaseNode.init instead of silently leaving the object in a broken state. Happy to rework the PR in that direction. |
|
I'm working on a counter suggestion PR right now. See #657. |
|
Closed in favor of #657 |
|
I think there are some other improvements in here that #657 doesn't cover. Feel free to reopen with reduced scope, or make a new PR. |
Fix
Optionalhandling to prevent operations on potentiallyNonevalues.Problem
mypy reports
[operator]and[union-attr]errors whereOptionalvalues are used without None-checks — e.g.0x600 + self.idwhenself.idcould beNone, ordivmod(self.offset, 8)whenself.offsetisNone.Changes
canopen/node/base.pyself.idasOptional[int]to match its runtime value (node_id or self.object_dictionary.node_id).canopen/node/remote.py/canopen/node/local.pyassert self.id is not Nonein__init__and re-annotateself.id: intto narrow the type for all methods.canopen/pdo/base.pyassertguards forself.offsetandself.pdo_parentat the start ofget_data()andset_data().wait_for_reception()return type:Optional[float](wasfloat, but returnsNoneon timeout).Impact
Eliminates 21
[operator]and[union-attr]errors in node and PDO modules.", "draft">false