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: Convert values of resolved options #125

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

dashmug
Copy link
Owner

@dashmug dashmug commented Nov 21, 2024

Resolves #64.

Summary by Sourcery

Implement automatic conversion of field values to their annotated types in the BaseOptions dataclass and replace warnings with errors for unsupported field types.

New Features:

  • Introduce automatic conversion of field values to their annotated types in the BaseOptions dataclass.

Enhancements:

  • Replace warnings with errors for unsupported field types in the BaseOptions dataclass.

Copy link
Contributor

sourcery-ai bot commented Nov 21, 2024

Reviewer's Guide by Sourcery

This PR enhances the BaseOptions class by adding type conversion functionality and improving type validation. It replaces the previous warning-based approach with strict type checking and implements automatic conversion of field values to their annotated types during initialization.

Updated class diagram for BaseOptions

classDiagram
    class BaseOptions {
        +__init_subclass__() void
        +from_options(options: dict[str, Any] | None) BaseOptions
        +__post_init__() void
        +_convert_and_set_field_value(field: Field[Any], value: Any, target_type: type) void
    }
    class UnsupportedTypeError {
    }
    BaseOptions <|-- UnsupportedTypeError
    note for BaseOptions "Enhanced with type conversion and validation"
    note for UnsupportedTypeError "New error class for unsupported types"
Loading

File-Level Changes

Change Details Files
Replace warning-based type checking with strict validation
  • Add new UnsupportedTypeError exception class
  • Replace warning with exception raising in init_subclass
  • Add SUPPORTED_TYPES class attribute check
src/glue_utils/options.py
Implement automatic type conversion for field values
  • Add post_init method to handle type conversion
  • Add _convert_and_set_field_value helper method
  • Implement special handling for boolean string conversion
  • Add value conversion error handling with descriptive messages
src/glue_utils/options.py

Assessment against linked issues

Issue Objective Addressed Explanation
#64 Convert resolved option values to match their field types defined in BaseOptions

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time. You can also use
    this command to specify where the summary should be inserted.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey @dashmug - I've reviewed your changes - here's some feedback:

Overall Comments:

  • The code references SUPPORTED_TYPES but this constant is not defined. Please define it with the supported types (str, int, float, bool).
Here's what I looked at during the review
  • 🟢 General issues: all looks good
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟡 Complexity: 1 issue found
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@@ -51,3 +51,36 @@ def from_options(cls, options: dict[str, Any] | None = None) -> Self:
return cls(
**{key: value for key, value in options.items() if key in field_names},
)

def __post_init__(self) -> None:
Copy link
Contributor

Choose a reason for hiding this comment

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

issue (complexity): Consider consolidating the type conversion logic into a single method with simplified boolean handling.

The type conversion logic can be simplified while maintaining functionality:

  1. Merge the conversion logic into __post_init__
  2. Simplify boolean conversion to standard true/false strings
  3. Move type validation to __init_subclass__
def __post_init__(self) -> None:
    """Convert field values to their annotated types."""
    type_hints = get_type_hints(self)

    for field in fields(self):
        value = getattr(self, field.name)
        target_type = type_hints.get(field.name, Any)

        if not isinstance(value, target_type):
            try:
                if target_type is bool:
                    converted = str(value).lower() == "true"
                else:
                    converted = target_type(value)
                setattr(self, field.name, converted)
            except (ValueError, TypeError) as e:
                msg = f"Could not convert field {field.name} value '{value}' to {target_type.__name__}"
                raise ValueError(msg) from e

This maintains all functionality while:

  • Removing unnecessary method abstraction
  • Simplifying boolean conversion
  • Reducing nesting levels
  • Keeping error handling intact

try:
if target_type is bool:
# Special handling for boolean strings
converted = str(value).lower() in ("true", "t", "yes", "y", "1")
Copy link
Contributor

Choose a reason for hiding this comment

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

suggestion (code-quality): Use set when checking membership of a collection of literals (collection-into-set)

Suggested change
converted = str(value).lower() in ("true", "t", "yes", "y", "1")
converted = str(value).lower() in {"true", "t", "yes", "y", "1"}

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.

Convert the values of the resolved options into the field types of BaseOptions.
1 participant