Skip to content

Simplify convert_from/to_registers (remove noqa: C901). - #3098

Merged
janiversen merged 5 commits into
pymodbus-dev:devfrom
daveharsh38:refactor/simplify-register-conversion
Nov 25, 2026
Merged

janiversen merged 5 commits into
pymodbus-dev:devfrom
daveharsh38:refactor/simplify-register-conversion

Conversation

@daveharsh38

Copy link
Copy Markdown
Contributor

convert_from_registers carries the last # noqa: C901 in the library. This PR does for it what #3082 did for execute, without changing behaviour:

  • Extract _registers_to_bytes(). The word-order handling and register -> bytes loop was written twice in convert_from_registers. The method is now under the C901 limit, so the noqa is removed.
  • Move the BITS / STRING / numeric branch bodies of convert_to_registers into _bits_to_bytes(), _string_to_bytes() and _values_to_bytes().
  • Rename data_len/data_type_len to regs_per_value, the number of registers per value (it was not a data length).
  • Name data_type.value[0] as struct_format instead of indexing the tuple inline.

Public API, error messages and results are unchanged. The existing converter tests pass unmodified, and check_ci.sh passes locally with coverage at 100%. This does not overlap with #3068.

data_len held the number of registers per value, not a data length,
and data_type_len held the same quantity under a different name.
Both are now regs_per_value; reg_len -> registers_count and the
loop index x -> start.
data_type.value[0] is an anonymous tuple index; name it struct_format
(the struct format character of the data type). In convert_to_registers
it is also computed once instead of once per value.
The word-order handling and register -> bytes loop was written twice
(once for STRING/BITS, once per numeric value). Extract it into
_registers_to_bytes(). This brings convert_from_registers under the
ruff C901 limit, so the "# noqa: C901" suppression is removed.
Each branch of the BITS / STRING / numeric if-elif-else validated and
packed the value inline. Move each branch body into an intention
revealing helper (_bits_to_bytes, _string_to_bytes, _values_to_bytes)
so convert_to_registers reads as a dispatch on data type.

@janiversen janiversen left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, Thanks.

@janiversen
janiversen merged commit d843b9e into pymodbus-dev:dev Nov 25, 2026
16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants