Skip to content

typing.cast may be code smell #2194

@dimaqq

Description

@dimaqq

James and I examined some of our uses of typing.cast and it seems that many cases can be rewritten to be more explicit.

For example, here self._is_leader is validated above, in a complex series of if statements that pyright doesn't grok. Perhaps changing this change would be clearer:

@@ -3688,8 +3688,8 @@ class _ModelBackend:
             with self._wrap_hookcmd('is-leader'):
                 self._is_leader = hookcmds.is_leader()

-        # We can cast to bool now since if we're here it means we checked.
-        return typing.cast('bool', self._is_leader)
+        assert self._is_leader is not None
+        return self._is_leader

Arguably, cases where the cast is applied to match the function signature return value type fall in this category.

Metadata

Metadata

Assignees

No one assigned

    Labels

    rainy daySmall items done in ~10% of each week's time

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions