Skip to content
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

feat: trim flanking whitespace when reading a metric #217

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

nh13
Copy link
Member

@nh13 nh13 commented Jan 28, 2025

Fixes #216

Also, strips any flanking whitespace when formatting a float into a string.

@nh13 nh13 requested review from tfenne and clintval as code owners January 28, 2025 17:09
Copy link
Contributor

coderabbitai bot commented Jan 28, 2025

Warning

Rate limit exceeded

@nh13 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 23 minutes and 13 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between de3b0c7 and 77c35a0.

📒 Files selected for processing (1)
  • tests/fgpyo/util/test_metric.py (2 hunks)

Walkthrough

The pull request modifies the Metric class in the fgpyo/util/metric.py file, specifically updating the read and format_value methods. A new parameter, strip_whitespace, has been added to the read method, enabling the removal of leading and trailing whitespace from values read from the metric file. The format_value method's return statements have been revised to apply strip() to string representations of float and general values. Additionally, two new test functions have been introduced in tests/fgpyo/util/test_metric.py to verify the handling of whitespace in the Person class and during TSV file reading. No existing functionality was deleted or modified.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
fgpyo/util/metric.py (1)

356-356: Add docstring to document whitespace stripping behavior.

The new whitespace stripping behavior should be documented in the method's docstring.

Add this to the docstring:

        Args:
            value: the value to format.
+           
+        Note:
+            Leading and trailing whitespace is stripped from all string representations.

Also applies to: 360-360

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f1f89e9 and 6315fbd.

📒 Files selected for processing (2)
  • fgpyo/util/metric.py (1 hunks)
  • tests/fgpyo/util/test_metric.py (1 hunks)
🧰 Additional context used
🪛 GitHub Actions: Python package
tests/fgpyo/util/test_metric.py

[error] 408-408: Test failure in test_metric_whitespace_padded_strip: String comparison mismatch. Expected 'John Doe' but got ' John Doe \t ' with extra whitespace and tab characters.

Comment on lines 406 to 436
@pytest.mark.parametrize("data_and_classes", (attr_data_and_classes, dataclasses_data_and_classes))
def test_metric_whitespace_padded_strip(data_and_classes: DataBuilder) -> None:
assert list(data_and_classes.Person(name=" John Doe \t ", age=42).values()) == ["John Doe", 42]

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix test failure: values not being stripped.

Test expects whitespace stripping but fails. The values() method returns raw values, while formatted_values() returns formatted (stripped) values.

Fix the test by using formatted_values():

-    assert list(data_and_classes.Person(name=" John Doe  \t ", age=42).values()) == ["John Doe", 42]
+    assert data_and_classes.Person(name=" John Doe  \t ", age=42).formatted_values() == ["John Doe", "42"]
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@pytest.mark.parametrize("data_and_classes", (attr_data_and_classes, dataclasses_data_and_classes))
def test_metric_whitespace_padded_strip(data_and_classes: DataBuilder) -> None:
assert list(data_and_classes.Person(name=" John Doe \t ", age=42).values()) == ["John Doe", 42]
@pytest.mark.parametrize("data_and_classes", (attr_data_and_classes, dataclasses_data_and_classes))
def test_metric_whitespace_padded_strip(data_and_classes: DataBuilder) -> None:
assert data_and_classes.Person(name=" John Doe \t ", age=42).formatted_values() == ["John Doe", "42"]
🧰 Tools
🪛 GitHub Actions: Python package

[error] 408-408: Test failure in test_metric_whitespace_padded_strip: String comparison mismatch. Expected 'John Doe' but got ' John Doe \t ' with extra whitespace and tab characters.

Copy link

codecov bot commented Jan 28, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 91.08%. Comparing base (f1f89e9) to head (d1d08de).

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #217      +/-   ##
==========================================
+ Coverage   91.00%   91.08%   +0.08%     
==========================================
  Files          18       18              
  Lines        2300     2300              
  Branches      341      341              
==========================================
+ Hits         2093     2095       +2     
+ Misses        136      135       -1     
+ Partials       71       70       -1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
fgpyo/util/metric.py (1)

213-213: Fix line length.

Line exceeds maximum length of 100 characters.

-    def read(cls, path: Path, ignore_extra_fields: bool = True, strip_whitespace: bool = True) -> Iterator[Any]:
+    def read(
+        cls,
+        path: Path,
+        ignore_extra_fields: bool = True,
+        strip_whitespace: bool = True,
+    ) -> Iterator[Any]:
🧰 Tools
🪛 Ruff (0.8.2)

213-213: Line too long (112 > 100)

(E501)

🪛 GitHub Actions: Python package

[warning] File needs formatting. Run 'ruff format' to fix formatting issues.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d1d08de and 3d73db1.

📒 Files selected for processing (2)
  • fgpyo/util/metric.py (4 hunks)
  • tests/fgpyo/util/test_metric.py (2 hunks)
🧰 Additional context used
🪛 GitHub Actions: Python package
tests/fgpyo/util/test_metric.py

[warning] File needs formatting. Run 'ruff format' to fix formatting issues.

fgpyo/util/metric.py

[warning] File needs formatting. Run 'ruff format' to fix formatting issues.

🪛 Ruff (0.8.2)
fgpyo/util/metric.py

213-213: Line too long (112 > 100)

(E501)

🔇 Additional comments (5)
fgpyo/util/metric.py (2)

267-268: LGTM!

Clean implementation of whitespace stripping with proper conditional check.

🧰 Tools
🪛 GitHub Actions: Python package

[warning] File needs formatting. Run 'ruff format' to fix formatting issues.


359-363: LGTM!

Clean implementation of whitespace handling in value formatting.

🧰 Tools
🪛 GitHub Actions: Python package

[warning] File needs formatting. Run 'ruff format' to fix formatting issues.

tests/fgpyo/util/test_metric.py (3)

157-161: LGTM!

Clean implementation of float age support.

🧰 Tools
🪛 GitHub Actions: Python package

[warning] File needs formatting. Run 'ruff format' to fix formatting issues.


411-419: LGTM!

Test properly verifies float rounding behavior.

🧰 Tools
🪛 GitHub Actions: Python package

[warning] File needs formatting. Run 'ruff format' to fix formatting issues.


421-438: LGTM!

Comprehensive test coverage for whitespace stripping functionality.

🧰 Tools
🪛 GitHub Actions: Python package

[warning] File needs formatting. Run 'ruff format' to fix formatting issues.

Fixes #216

Also, strips any flanking whitespace when formatting a float into
a string.
@nh13 nh13 force-pushed the feat/strip-metric-values branch from 3d73db1 to de3b0c7 Compare January 28, 2025 19:00
@nh13 nh13 changed the title feat: metric to trim flanking whitespace at: trim flanking whitespace when reading a metric Jan 28, 2025
@nh13 nh13 requested a review from msto January 28, 2025 19:00
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
tests/fgpyo/util/test_metric.py (1)

411-417: Add edge cases to float rounding test.

Consider adding test cases for:

  • Very small numbers (e.g., 0.0000001)
  • Very large numbers (e.g., 1e10)
  • Negative numbers
 @pytest.mark.parametrize("data_and_classes", (attr_data_and_classes, dataclasses_data_and_classes))
 def test_metric_round_floats(data_and_classes: DataBuilder) -> None:
-    assert list(data_and_classes.Person(name="John Doe", age=42.123456).formatted_values()) == [
-        "John Doe",
-        "42.12346",
-    ]
+    test_cases = [
+        (42.123456, "42.12346"),
+        (0.0000001, "0.0"),
+        (1e10, "10000000000.0"),
+        (-42.123456, "-42.12346"),
+    ]
+    for value, expected in test_cases:
+        assert list(data_and_classes.Person(name="John Doe", age=value).formatted_values()) == [
+            "John Doe",
+            expected,
+        ]
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3d73db1 and de3b0c7.

📒 Files selected for processing (2)
  • fgpyo/util/metric.py (4 hunks)
  • tests/fgpyo/util/test_metric.py (2 hunks)
🔇 Additional comments (5)
fgpyo/util/metric.py (3)

213-215: LGTM! Well-documented parameter addition.

The new strip_whitespace parameter is properly documented and maintains backward compatibility.

Also applies to: 226-226


269-270: LGTM! Clean implementation of whitespace stripping.

The implementation correctly handles the strip_whitespace parameter.


361-361: LGTM! Consistent whitespace handling.

The changes ensure uniform whitespace handling for both float and general values.

Also applies to: 365-365

tests/fgpyo/util/test_metric.py (2)

157-161: LGTM! Well-structured test class.

The PersonAgeFloat class is properly implemented for testing float values.


419-436: LGTM! Comprehensive whitespace handling test.

Test covers all important whitespace scenarios: leading, trailing, and both.

@nh13 nh13 changed the title at: trim flanking whitespace when reading a metric feat: trim flanking whitespace when reading a metric Jan 28, 2025
Copy link
Contributor

@msto msto left a comment

Choose a reason for hiding this comment

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

Thank you!

@@ -353,11 +358,11 @@ def format_value(cls, value: Any) -> str: # noqa: C901
+ "}"
)
elif isinstance(value, float):
return str(round(value, 5))
return f"{round(value, 5)}".strip()
Copy link
Contributor

Choose a reason for hiding this comment

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

I think the .strip() is unnecessary here because the f-string interpolation won't add any trailing whitespace

Suggested change
return f"{round(value, 5)}".strip()
return f"{round(value, 5)}"

@@ -221,6 +223,7 @@ def read(cls, path: Path, ignore_extra_fields: bool = True) -> Iterator[Any]:
Args:
path: the path to the metrics file.
ignore_extra_fields: True to ignore any extra columns, False to raise an exception.
strip_whitespace: True to strip leading and trailing whitespace, False to keep as-is.
Copy link
Contributor

Choose a reason for hiding this comment

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

Just a small suggestion! It might be helpful to clarify that the whitespace stripping applies to each field individually, not to the row as a whole

Suggested change
strip_whitespace: True to strip leading and trailing whitespace, False to keep as-is.
strip_whitespace: True to strip leading and trailing whitespace from each field, False to keep as-is.

@@ -210,7 +210,9 @@ def _parsers(cls) -> Dict[type, Callable[[str], Any]]:
return {}

@classmethod
def read(cls, path: Path, ignore_extra_fields: bool = True) -> Iterator[Any]:
def read(
cls, path: Path, ignore_extra_fields: bool = True, strip_whitespace: bool = True
Copy link
Contributor

Choose a reason for hiding this comment

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

Should this default be False? Otherwise it will be a breaking change

Suggested change
cls, path: Path, ignore_extra_fields: bool = True, strip_whitespace: bool = True
cls, path: Path, ignore_extra_fields: bool = True, strip_whitespace: bool = False

assert persons[2].name == "Someone Else"
assert persons[2].age == 47

persons = list(data_and_classes.Person.read(test_tsv, strip_whitespace=False))
Copy link
Contributor

@msto msto Jan 28, 2025

Choose a reason for hiding this comment

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

🙌 good catch to cover both cases!

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.

Metric could optionally trim flanking whitespace from string fields
2 participants