operator icon indicating copy to clipboard operation
operator copied to clipboard

typing.cast may be code smell

Open dimaqq opened this issue 3 months ago • 0 comments

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.

dimaqq avatar Nov 27 '25 02:11 dimaqq