Skip to content

fix: has_lines returns empty str instead of bool #3260

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Conversation

Strengthless
Copy link
Contributor

Minimal reproducible example:

def has_lines(string: str, count: int) -> bool:
    """Return True if `string` has at least `count` lines."""
    # Benchmarks show this is significantly faster than using str.count("\n") or a for loop & break.
    split = string.split("\n", count - 1)

    # Make sure the last part isn't empty, which would happen if there was a final newline.
    return split[-1] and len(split) == count

print(has_lines("test\n", 1)) # returns True correctly
print(has_lines("test\n", 3)) # returns "" instead of False

Of course, "" in an if-statement will still evaluate to False, but it's not a good practice and probably unsafe.

This PR fixes that by adding an explicit != "" check, so that booleans are returned at all times.

Unit tests for the whole file bot/utils/helpers.py have also been included, and the test coverage for that file is now at 100%.

Copy link
Member

@vivekashok1221 vivekashok1221 left a comment

Choose a reason for hiding this comment

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

Nice catch, I'm curious how you found this.

@Strengthless
Copy link
Contributor Author

I'm curious how you found this

To be honest, I was just writing a bunch of new tests in hope to improve the coverage, but then came across a weird AssertionError that I totally did not expect 😅

@ChrisLovering ChrisLovering merged commit f00ad30 into python-discord:main Feb 16, 2025
5 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.

3 participants