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

Introduce Typed Data Classes for iRail Station Endpoint #22

Merged
merged 13 commits into from
Jan 6, 2025

Conversation

silamon
Copy link
Contributor

@silamon silamon commented Jan 4, 2025

This is a more strict typing example. The goal is to have no dicts for objects that can be defined.
Not all endpoints are done right now, just one to see to gather feedback.

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced station data retrieval with structured response
    • Improved type handling for API responses
  • Dependencies

    • Added mashumaro library for advanced data serialization
  • Improvements

    • Refined data models for railway station information
    • Updated API response parsing to provide more precise data structures

Copy link
Contributor

coderabbitai bot commented Jan 4, 2025

Warning

Rate limit exceeded

@tjorim has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 34 minutes and 36 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 500991b and 43793d2.

📒 Files selected for processing (2)
  • pyrail/models.py (1 hunks)
  • tests/test_irail.py (4 hunks)
📝 Walkthrough

Walkthrough

This pull request introduces a new data modeling approach for the pyrail library by adding the mashumaro serialization library. The changes involve updating the pyproject.toml to include the new dependency, creating a models.py module with structured data classes for API responses and stations, and modifying the irail.py to return typed station objects instead of raw dictionaries. The test suite has been correspondingly updated to validate the new response structure.

Changes

File Change Summary
pyproject.toml Added mashumaro dependency with orjson extras
pyrail/irail.py Updated get_stations method to return List[Station] instead of Dict[str, Any]
pyrail/models.py Created new data classes: ApiResponse, Station, and StationsApiResponse using mashumaro
tests/test_irail.py Modified tests to validate new Station object response structure

Sequence Diagram

sequenceDiagram
    participant Client
    participant iRail
    participant iRailAPI
    participant Models
    
    Client->>iRail: get_stations()
    iRail->>iRailAPI: Request stations
    iRailAPI-->>iRail: Raw station data
    iRail->>Models: Convert to StationsApiResponse
    Models-->>iRail: Structured station objects
    iRail-->>Client: List[Station]
Loading

Possibly related PRs

Poem

🚂 Stations dancing, data refined,
With Mashumaro's magic, models intertwined!
From dict to class, a railway delight,
Serialization leaping with rabbit's might! 🐰
Code transforms, elegance takes flight!


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: 0

🧹 Nitpick comments (8)
test.py (3)

1-2: Add module-level docstring
A module docstring would enhance code readability, align with docstring conventions, and help other developers understand this module’s purpose.

🧰 Tools
🪛 Ruff (0.8.2)

1-1: Missing docstring in public module

(D100)


5-10: Add docstring for main()
The function main() is asynchronous and part of your public interface, so adding a docstring will make it clearer how to use it and what it returns.

🧰 Tools
🪛 Ruff (0.8.2)

5-5: Missing docstring in public function

(D103)


12-13: Consider test structure or rename
Running your script from asyncio.run(main()) is perfectly valid. However, if test.py is intended to be used for actual tests, consider renaming it to clarify its test nature or bringing it into a dedicated testing framework (e.g., pytest).

pyrail/models.py (4)

1-2: Add module-level docstring
Providing a brief docstring at the top-level of the module clarifies its purpose, which is particularly useful for a public module.

🧰 Tools
🪛 Ruff (0.8.2)

1-1: Missing docstring in public module

(D100)


8-15: Add docstring to Station
Although the class is self-explanatory, adding a short docstring ensures clarity and docs generation compliance.

🧰 Tools
🪛 Ruff (0.8.2)

9-9: Missing docstring in public class

(D101)


17-21: Add docstring to APIResponse
A short docstring on this base class will help new contributors understand its intended usage.

🧰 Tools
🪛 Ruff (0.8.2)

18-18: Missing docstring in public class

(D101)


23-25: Add docstring to StationAPIResponse
While the class name is intuitive, clarifying its use in a docstring will improve maintainability and consistency with standard docstring conventions.

🧰 Tools
🪛 Ruff (0.8.2)

24-24: Missing docstring in public class

(D101)

pyrail/irail.py (1)

Line range hint 342-362: Ensure docstring alignment with new return type
Your get_stations() docstring mentions returning a List[Station], but the code uses Python 3.10+ syntax list[Station] | None. Although these are functionally the same for type checking, consider explicitly matching the docstring to the new syntax or clarifying that a None return is possible.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 950a62b and 17311f8.

⛔ Files ignored due to path filters (1)
  • poetry.lock is excluded by !**/*.lock
📒 Files selected for processing (4)
  • pyproject.toml (1 hunks)
  • pyrail/irail.py (3 hunks)
  • pyrail/models.py (1 hunks)
  • test.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
test.py

1-1: Missing docstring in public module

(D100)


5-5: Missing docstring in public function

(D103)

pyrail/models.py

1-1: Missing docstring in public module

(D100)


9-9: Missing docstring in public class

(D101)


18-18: Missing docstring in public class

(D101)


24-24: Missing docstring in public class

(D101)

🔇 Additional comments (2)
pyproject.toml (1)

22-22: Check dependency version compatibility
While mashumaro with orjson extras is a good choice, verify potential version conflicts or pinned requirements in your environment.

pyrail/irail.py (1)

13-13: Validate imports
You’re importing Station and StationAPIResponse for structured data. This is good, but ensure that merging or removing classes in the future doesn’t break downstream references.

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

🔭 Outside diff range comments (1)
pyrail/irail.py (1)

Add error handling for JSON deserialization

The current implementation should handle potential exceptions during JSON deserialization to prevent crashes from malformed API responses. Consider wrapping the from_dict call in a try-except block:

try:
    stations_response: StationAPIResponse = StationAPIResponse.from_dict(stations_dict)
    return stations_response.station
except Exception as e:
    logger.error(f"Failed to parse station response: {e}")
    return None
🔗 Analysis chain

Line range hint 360-380: Consider additional error-handling for station objects.

The updated method neatly converts the dictionary into a StationAPIResponse and returns stations_response.station. However, if the response is missing or malformed, from_dict might raise an exception. Consider adding a try-except or verifying that the station list is present before returning it.

As a follow-up, you could run a script to search for usage of get_stations and confirm whether the calling code already expects empty or partial station lists:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify calls to get_stations for potential error handling
rg -A 5 'await client\.get_stations'

Length of output: 864


Script:

#!/bin/bash
# Find StationAPIResponse class implementation
ast-grep --pattern 'class StationAPIResponse'

Length of output: 47


Script:

#!/bin/bash
# Find StationAPIResponse definition and related code
rg -A 5 "StationAPIResponse" 
rg -A 5 "@dataclass.*StationAPIResponse"

Length of output: 814


Script:

#!/bin/bash
# Find APIResponse base class implementation
rg -A 10 "class APIResponse"

Length of output: 322


Script:

#!/bin/bash
# Find DataClassORJSONMixin implementation
rg -A 10 "class DataClassORJSONMixin"

Length of output: 39

🧹 Nitpick comments (2)
tests/test_typed.py (2)

1-1: Consider adding a module-level docstring.

According to Ruff (D100), a public module should have a docstring explaining its purpose. Adding a short docstring at the top can help newcomers easily understand what this test script does.

🧰 Tools
🪛 Ruff (0.8.2)

1-1: Missing docstring in public module

(D100)


5-9: Add a docstring and basic assertions.

  1. As flagged by Ruff (D103), this public function lacks a docstring describing its purpose, parameters, and usage.
  2. Consider including at least one simple assertion or verification (e.g., verifying that stations is not empty) to strengthen the test example.
🧰 Tools
🪛 Ruff (0.8.2)

5-5: Missing docstring in public function

(D103)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 17311f8 and 604b031.

⛔ Files ignored due to path filters (1)
  • poetry.lock is excluded by !**/*.lock
📒 Files selected for processing (3)
  • pyproject.toml (1 hunks)
  • pyrail/irail.py (3 hunks)
  • tests/test_typed.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • pyproject.toml
🧰 Additional context used
🪛 Ruff (0.8.2)
tests/test_typed.py

1-1: Missing docstring in public module

(D100)


5-5: Missing docstring in public function

(D103)

🔇 Additional comments (2)
tests/test_typed.py (1)

13-13: Looks good.

The invocation of asyncio.run(main()) is straightforward and valid for running the asynchronous code in this test script.

pyrail/irail.py (1)

13-13: New imports for typed models.

Importing Station and StationAPIResponse is consistent with the new typed approach. Smooth integration 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 (6)
tests/test_irail.py (3)

57-58: **Docstring mismatch with updated data structure **

The function docstring above mentions that the response is a dictionary containing 'station', but the new assertion checks for a list. Consider updating the docstring to reflect that the method now returns a list of Station objects.


60-63: **Clarify assertion error message **

The error message "Expected 'station' to be a list" may be confusing, as you are actually expecting an element from the stations list to be a Station object. Consider revising it for clarity.

-            stations[0], Station), "Expected 'station' to be a list"
+            stations[0], Station), "Expected the first item in the stations list to be a Station instance"

91-94: **Clarify assertion error message for connections **

Similar to the stations check, improve the assertion message for consistency:

-            connection_list, list), "Expected 'connection' to be a list"
+            connection_list, list), "Expected response['connection'] to be a list"
pyrail/models.py (3)

10-10: **Add class-level docstring to explain its purpose **

The linter flags a missing docstring. Consider adding a brief summary of ApiResponse:

+ """Base class for API responses, including schema version and timestamp."""
🧰 Tools
🪛 Ruff (0.8.2)

10-10: Missing docstring in public class

(D101)


16-16: **Add class-level docstring to explain its purpose **

Consider adding a docstring summarizing Station, for clarity and to address linter warnings:

+ """Represents a single railway station with location and naming attributes."""
🧰 Tools
🪛 Ruff (0.8.2)

16-16: Missing docstring in public class

(D101)


30-30: **Add class-level docstring to explain its purpose **

Similarly, add a docstring for StationsApiResponse. For example:

+ """Holds a list of station objects returned by the 'stations' endpoint."""
🧰 Tools
🪛 Ruff (0.8.2)

30-30: Missing docstring in public class

(D101)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 604b031 and 500991b.

⛔ Files ignored due to path filters (1)
  • poetry.lock is excluded by !**/*.lock
📒 Files selected for processing (3)
  • pyrail/irail.py (3 hunks)
  • pyrail/models.py (1 hunks)
  • tests/test_irail.py (4 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
pyrail/models.py

10-10: Missing docstring in public class

(D101)


16-16: Missing docstring in public class

(D101)


30-30: Missing docstring in public class

(D101)

🔇 Additional comments (4)
tests/test_irail.py (3)

8-8: **Import of Station is appropriate **

Good job importing the newly introduced Station class and using it in the tests. This aligns with the typed approach described in the pull request summary.


26-27: **No concerns with additional header usage **

The added headers referencing the pyRail GitHub repo are correct and consistent with the existing pattern.


83-84: **No issues found **

Asserting that connections is a dictionary aligns with the endpoint's expected return type.

pyrail/irail.py (1)

Line range hint 360-381: **Concise and clear station fetch method **

Switching from raw dictionaries to typed objects increases clarity and maintainability. Good work updating the docstring to match the new return type.

@tjorim
Copy link
Owner

tjorim commented Jan 6, 2025

@coderabbitai Suggest a title for this PR.

Copy link
Contributor

coderabbitai bot commented Jan 6, 2025

Tip

For best results, initiate chat on the files or code changes.

@tjorim Here's a concise, descriptive title you could use:

Introduce Typed Data Classes for iRail Station Endpoint

Feel free to adjust as needed!

@tjorim tjorim changed the title Typing example Introduce Typed Data Classes for iRail Station Endpoint Jan 6, 2025
@tjorim tjorim merged commit 26c45e2 into tjorim:main Jan 6, 2025
4 checks passed
@tjorim
Copy link
Owner

tjorim commented Jan 6, 2025

Thanks for teaching me something new @silamon!

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.

2 participants