Conversation
| '0' | ||
| """ | ||
| return self.key_string[round(num)] | ||
| return self.key_string[(num)] |
There was a problem hiding this comment.
@dhruvmanila I do not understand this change requested by ruff. Type hints are suggestions, not mandatory in Python. Just because the type hint says num: int, that does not guarantee that the caller will not pass in 17.23. This call to round() prevents breakage.
There was a problem hiding this comment.
I think this is correct and is https://docs.astral.sh/ruff/rules/unnecessary-round/. The num is an int so it doesn't require a round call. If you expect num to be a float as well then the type hint should be updated to int | float which is basically float.
There was a problem hiding this comment.
This misses the point. The type hint is a suggestion in Python, not an obligation. The caller may choose to send a float even though I have suggested they send an int. Without the round() call, the function will crash. With the round() call, the function will succeed. This rule is asking me not to drive defensively.
The workaround for ruff rule RUF057 is to use int(num) instead of round(num):
There was a problem hiding this comment.
I don't think that's correct. From a static analysis perspective, type hints are part of the function contract that says that the num parameter here should be an int and if the caller passes a float then that's an error. So, if the function is expecting to receive a float or an int, then the contract should be updated instead.
There was a problem hiding this comment.
The num parameter here should be an int. Python will not prevent the caller from breaking that rule.
Using int(num) instead of round(num) ensures the function remains well-behaved in the face of garbage input.
There was a problem hiding this comment.
I see. I think that depends on whether this specific function is part of the public API for this module or not. If it is, then one way to perform error handling would be to use something like:
if not isinstance(num, int):
raise TypeError("expected an integer, but got ...")And, if it's not part of the public API, then we shouldn't do this and instead use a type checker.
Describe your change:
Make changes required to pass current ruff tests.
Checklist: