Skip to content

Remove unnecessary casts in SimDevice#2965

Merged
janiversen merged 1 commit into
pymodbus-dev:devfrom
km-64:improve-type-narrowing
Jul 16, 2026
Merged

Remove unnecessary casts in SimDevice#2965
janiversen merged 1 commit into
pymodbus-dev:devfrom
km-64:improve-type-narrowing

Conversation

@km-64

@km-64 km-64 commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

Type checkers are able to narrow down the type to tuple and retain more information such as the element types. This gives the type more information than just casting to a tuple.

For example, line sim_list will be of type Any with the cast, but without it the actual type is inferred by the zuban.

sim_list = cast(tuple, self.simdata)[i]

# With tuple cast
sim_list = cast(tuple, self.simdata)[i]
reveal_type(sim_list) # pymodbus/simulator/simdevice.py:153: note: Revealed type is "Any"

# Without tuple cast
sim_list = self.simdata[i]
reveal_type(sim_list) # pymodbus/simulator/simdevice.py:153: note: Revealed type is "builtins.list[pymodbus.simulator.simdata.SimData]"

In this case removing the cast provides more information for later usages of sim_list such as in __check_simple_blocks,

 for inx, entry in enumerate(sim_list):
    reveal_type(entry) # pymodbus/simulator/simdevice.py:156: note: Revealed type is "pymodbus.simulator.simdata.SimData"

    if not isinstance(entry, SimData):
        raise TypeError(
            f"simdata[{inx}]=tuple[{TUPLE_NAMES[i]}] -> list[{inx}] is not a SimData entry"
        )
    if i < 2 and entry.datatype != DataType.BITS:
        raise TypeError(
            f"simdata[{inx}]=tuple[{TUPLE_NAMES[i]}] -> list[{inx}] not DataType.BITS, not allowed"
        )

…to type-narrowing

The type checker is able to narrow down the type and retains more type information
that way. This can be inspected using `typing.reveal_type`.
@km-64
km-64 marked this pull request as ready for review July 16, 2026 14:40

@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 f051adf into pymodbus-dev:dev Jul 16, 2026
37 of 38 checks passed
@km-64
km-64 deleted the improve-type-narrowing branch July 16, 2026 14:52
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