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

Fix type hints #340

Merged
merged 2 commits into from
Sep 28, 2024
Merged

Fix type hints #340

merged 2 commits into from
Sep 28, 2024

Conversation

jan-janssen
Copy link
Member

@jan-janssen jan-janssen commented Sep 28, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced return types for several functions, allowing for more flexible outputs (e.g., submit_job and convert_queue_status can now return None).
    • Added documentation to clarify the purpose of the CoreQueueAdapter class.
  • Bug Fixes

    • Updated function signatures to accept a wider range of input types, improving usability.
  • Documentation

    • Removed outdated attribute documentation from the BasisQueueAdapter class to streamline information.

Copy link

coderabbitai bot commented Sep 28, 2024

Walkthrough

The changes involve modifications to function signatures and documentation across several files in the pysqa module. Key updates include altering return types to allow for more flexible outputs, such as introducing None as a possible return value. Additionally, some class documentation has been refined, with specific attributes removed from the docstrings, while new docstrings have been added to clarify class purposes.

Changes

Files Change Summary
pysqa/ext/modular.py Updated submit_job function signature to return Union[int, None]. Added import for Union from typing.
pysqa/utils/basic.py Removed attribute documentation for config, queue_list, queue_view, and queues in BasisQueueAdapter class.
pysqa/utils/core.py Added docstring to CoreQueueAdapter class describing its purpose and parameters.
pysqa/utils/validate.py Changed _memory_spec_string_to_value parameter value from str to Union[str, int, float].
pysqa/wrapper/gent.py Modified convert_queue_status method signature to return Union[pandas.DataFrame, None]. Added import for Union from typing.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant QueueSystem
    User->>QueueSystem: Submit Job
    QueueSystem->>User: Return Job ID or None
Loading

🐰 Hopping through the code, oh what a sight,
With changes so clever, making things right.
Functions now flexible, docs shining bright,
In the land of pysqa, all feels just right!
Let's celebrate with a joyful cheer,
For every little change, brings us near! 🌟


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

@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

🧹 Outside diff range and nitpick comments (6)
pysqa/wrapper/gent.py (1)

Line range hint 41-50: Update docstring to reflect new return type.

The change in the return type hint from pandas.DataFrame to Union[pandas.DataFrame, None] is appropriate and aligns with the method's implementation. This change improves type accuracy and flexibility.

However, the method's docstring should be updated to reflect this change in the return type.

Please update the docstring to include information about the possibility of returning None. Here's a suggested change:

 def convert_queue_status(queue_status_output: str) -> Union[pandas.DataFrame, None]:
     """
     Converts the queue status output into a pandas DataFrame.

     Args:
         queue_status_output (str): The output of the queue status command.

     Returns:
-        pandas.DataFrame: The converted queue status.
+        Union[pandas.DataFrame, None]: The converted queue status, or None if there are no jobs in the queue.

     """
pysqa/utils/validate.py (1)

80-82: Consider renaming the function

The function name _memory_spec_string_to_value now seems inconsistent with its new capability to handle non-string inputs.

Consider renaming the function to better reflect its new capabilities. For example:

def _memory_spec_to_value(
    value: Union[str, int, float],
    default_magnitude: str = "m",
    target_magnitude: str = "b",
) -> Union[int, float]:

This name more accurately describes the function's ability to handle various input types.

pysqa/ext/modular.py (1)

58-58: Update the docstring to reflect the new return type.

The change in the return type annotation to Union[int, None] is correct and more accurately represents the method's behavior. However, the docstring for this method needs to be updated to reflect this change.

Please update the Returns section in the docstring to:

Returns:
    Union[int, None]: The cluster queue ID if successful, None otherwise.
pysqa/utils/core.py (3)

75-82: Enhance the docstring with type information and accuracy.

The added docstring is a good start, but it can be improved for clarity and accuracy:

  1. Add type information to the parameters.
  2. Correct the description of execute_command to indicate it's a callable rather than a function.
  3. Consider adding a return section to describe what the class returns or creates.

Here's a suggested improvement:

"""
The goal of the QueueAdapter class is to make submitting to a queue system as easy as starting another sub process
locally.

Args:
    queue_type (str): Type of the queuing system in capital letters.
    execute_command (callable): Callable to execute commands.

Returns:
    CoreQueueAdapter: An instance of the CoreQueueAdapter class.
"""

Line range hint 1-465: Consider further type hint improvements throughout the file.

While the PR objective is to "Fix type hints", there are opportunities to enhance the existing type hints:

  1. Replace Union[type, None] with Optional[type] for better readability. For example:

    def submit_job(
        self,
        queue: Optional[str] = None,
        job_name: Optional[str] = None,
        # ... other parameters ...
    ) -> Optional[int]:
  2. Use more specific callable types where applicable. For example, in the __init__ method:

    from typing import Callable
    
    def __init__(
        self,
        queue_type: str,
        execute_command: Callable[[Union[str, List[str]], Optional[str], bool, bool, str], str] = execute_command,
    ):
  3. Consider using TypedDict for dictionary return types where appropriate, especially if the structure of the returned dictionary is known and consistent.

  4. Import and use TypeAlias for complex types that are used multiple times:

    from typing import TypeAlias
    
    CommandList: TypeAlias = Union[str, List[str]]

These improvements will enhance code readability and provide more precise type information.


Line range hint 1-465: Summary of review and alignment with PR objective

The PR objective was to "Fix type hints", but the actual change was limited to adding a docstring to the CoreQueueAdapter class. While this addition is valuable, it doesn't directly address the stated objective.

To better align with the PR's intent, consider:

  1. Implementing the suggested improvements to the added docstring, including type information for parameters.
  2. Applying the proposed type hint enhancements throughout the file, such as using Optional instead of Union[type, None] and more specific callable types.

These changes would more fully address the PR's objective of fixing and improving type hints in the code.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 2ad0c18 and 23b42c8.

📒 Files selected for processing (5)
  • pysqa/ext/modular.py (2 hunks)
  • pysqa/utils/basic.py (0 hunks)
  • pysqa/utils/core.py (1 hunks)
  • pysqa/utils/validate.py (1 hunks)
  • pysqa/wrapper/gent.py (2 hunks)
💤 Files not reviewed due to no reviewable changes (1)
  • pysqa/utils/basic.py
🔇 Additional comments (5)
pysqa/wrapper/gent.py (2)

1-1: LGTM: Import statement added for Union type.

The addition of from typing import Union is appropriate and necessary for the updated return type hint in the convert_queue_status method. This change aligns with the PR objective of fixing type hints.


Line range hint 1-41: Overall assessment: Changes improve type accuracy.

The modifications in this file, including the addition of the Union import and the update to the return type hint of convert_queue_status, successfully improve type accuracy and flexibility. These changes align well with the PR objective of fixing type hints.

A minor suggestion was made to update the docstring of convert_queue_status to reflect the new return type. Once this is addressed, the changes in this file will be complete and satisfactory.

pysqa/utils/validate.py (1)

80-82: Verify impact on value_in_range function

The value_in_range function uses _memory_spec_string_to_value. Please ensure that this change doesn't negatively impact its behavior.

Let's verify the usage of _memory_spec_string_to_value in the value_in_range function:

This will help us understand if any adjustments are needed in value_in_range to accommodate the new input types of _memory_spec_string_to_value.

pysqa/ext/modular.py (2)

1-1: LGTM: Import statement updated correctly.

The addition of Union to the import statement is appropriate for the new return type annotation in the submit_job method.


58-58: Verify callers of submit_job method.

The new return type Union[int, None] accurately reflects the method's behavior. To ensure this change doesn't introduce issues elsewhere in the codebase, please verify that all code calling this method is prepared to handle both int and None return values.

✅ Verification successful

submit_job method return type verified.

All callers of submit_job have been reviewed and appropriately handle both int and None return values.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all calls to submit_job method in the codebase

# Test: Search for calls to submit_job. Expect: List of all method calls with context.
rg --type python -A 5 $'submit_job\('

Length of output: 69


Script:

#!/bin/bash
# Description: Find all calls to submit_job method in the codebase

# Test: Search for calls to submit_job. Expect: List of all method calls with context.
rg --glob '*.py' -A 5 'submit_job\('

Length of output: 5104

Comment on lines +80 to +82
value: Union[str, int, float],
default_magnitude: str = "m",
target_magnitude: str = "b",
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Approve type hint change, but function body needs updates

The change to accept Union[str, int, float] as input is good for flexibility, but the function body needs to be updated to handle these new input types. Also, please update the docstring to reflect this change.

Please update the function body to handle int and float inputs. Here's a suggestion for the beginning of the function:

def _memory_spec_string_to_value(
    value: Union[str, int, float],
    default_magnitude: str = "m",
    target_magnitude: str = "b",
) -> Union[int, float]:
    """
    Converts a valid memory string, integer, or float into a value of desired magnitude.

    Args:
        value (Union[str, int, float]): The value to convert. If string, it should be a valid memory string.
        default_magnitude (str): The magnitude for interpreting plain integer/float values [b, B, k, K, m, M, g, G, t, T]. Defaults to "m".
        target_magnitude (str): The magnitude to which the output value should be converted [b, B, k, K, m, M, g, G, t, T]. Defaults to "b".

    Returns:
        Union[int, float]: The value in `target_magnitude` units.
    """
    if isinstance(value, (int, float)):
        # Treat int/float as if they were strings with default_magnitude
        return (value * 1024 ** magnitude_mapping[default_magnitude.lower()]) / (
            1024 ** magnitude_mapping[target_magnitude.lower()]
        )
    
    # Existing code for string handling...

This change ensures that int and float inputs are handled correctly, interpreting them with the default_magnitude.

@jan-janssen jan-janssen merged commit a0470e1 into main Sep 28, 2024
18 checks passed
@jan-janssen jan-janssen deleted the typehints branch September 28, 2024 14:42
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.

1 participant