Skip to content

🔨 enhance type hints and improve code clarity across multiple modules#17

Merged
techouse merged 2 commits intomainfrom
chore/strict-typing
Mar 26, 2025
Merged

🔨 enhance type hints and improve code clarity across multiple modules#17
techouse merged 2 commits intomainfrom
chore/strict-typing

Conversation

@techouse
Copy link
Owner

@techouse techouse commented Mar 26, 2025

This pull request includes several changes to improve type annotations and code clarity across various modules in the qs_codec package. The most significant changes involve adding type hints to function signatures and refining existing type annotations.

Type Annotation Improvements:

Code Clarity Enhancements:

Other Changes:


Fixes #16

Summary by CodeRabbit

  • Refactor

    • Enhanced internal clarity with improved type annotations and explicit public interface definitions.
  • Chores

    • Updated internal method signatures and type hints to boost maintainability and static type checking without altering external functionality.

@techouse techouse added the enhancement New feature or request label Mar 26, 2025
@techouse techouse self-assigned this Mar 26, 2025
@coderabbitai
Copy link

coderabbitai bot commented Mar 26, 2025

Walkthrough

The pull request refines type annotations and method signatures across the module. An explicit __all__ list has been added to declare the public interface in the main package file. Various functions and methods in decoding, encoding, models, and utilities now feature more precise type hints, including updates to list, tuple, and mapping declarations. Unnecessary type ignore directives have been removed and return types explicitly annotated, thereby improving clarity and supporting static type checking without altering core functionality.

Changes

Files Change Summary
src/qs_codec/__init__.py Added an explicit __all__ list defining the module's public interface.
src/qs_codec/decode.py, src/qs_codec/encode.py Enhanced type annotations in helper functions by updating variable types and removing redundant type ignore directives.
src/qs_codec/models/decode_options.py, src/qs_codec/models/encode_options.py, src/qs_codec/models/undefined.py, src/qs_codec/models/weak_wrapper.py Updated method signatures to include explicit return types and refined parameter type annotations, with minor comment removals for clarity.
src/qs_codec/utils/decode_utils.py, src/qs_codec/utils/utils.py Refined type annotations in utility functions by removing unnecessary casts and enhancing type specificity in parameters and return types.

Assessment against linked issues

Objective Addressed Explanation
Use explicit export in src/qs_codec/__init__.py (#16)

Possibly related PRs

  • ⚡ decode returns dict[str, Any] instead of dict #4: The changes in the main PR are related to the modifications in the decode function's type annotations in the retrieved PR, as both involve updates to type hints and public interface declarations within the qs_codec module.
  • ✨ decode: add raise_on_limit_exceeded option #11: The changes in the main PR are related to the modifications in the DecodeOptions class and the _parse_query_string_values function in the retrieved PR, as both involve updates to type annotations and the handling of public entities within the same module.

Poem

I'm a rabbit, hopping through fresh code lines,
Where types now sparkle and intentions shine.
Each function and method feels so clear,
A tidy garden where bugs disappear.
With eager hops and whiskered delight,
I celebrate these changes both bold and bright!
🐇 Happy coding, under starry night!


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b95cd81 and b082e2b.

📒 Files selected for processing (1)
  • src/qs_codec/utils/utils.py (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/qs_codec/utils/utils.py
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Codacy Static Code Analysis

🪧 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

@codacy-production
Copy link

codacy-production bot commented Mar 26, 2025

Coverage summary from Codacy

See diff coverage on Codacy

Coverage variation Diff coverage
+0.02% (target: -1.00%) 100.00%
Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (383f839) 762 737 96.72%
Head commit (b082e2b) 766 (+4) 741 (+4) 96.74% (+0.02%)

Coverage variation is the difference between the coverage for the head and common ancestor commits of the pull request branch: <coverage of head commit> - <coverage of common ancestor commit>

Diff coverage details
Coverable lines Covered lines Diff coverage
Pull request (#17) 21 21 100.00%

Diff coverage is the percentage of lines that are covered by tests out of the coverable lines that the pull request added or modified: <covered lines added or modified>/<coverable lines added or modified> * 100%

See your quality gate settings    Change summary preferences

Codacy stopped sending the deprecated coverage status on June 5th, 2024. Learn more

@codecov
Copy link

codecov bot commented Mar 26, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 96.73%. Comparing base (383f839) to head (b082e2b).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main      #17      +/-   ##
==========================================
+ Coverage   96.71%   96.73%   +0.01%     
==========================================
  Files          16       16              
  Lines         762      766       +4     
==========================================
+ Hits          737      741       +4     
  Misses         25       25              

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

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

🧹 Nitpick comments (1)
src/qs_codec/utils/utils.py (1)

20-20: Consider refactoring the default parameter to avoid function call.

The static analyzer has flagged a potential issue with using a function call in the default parameter. Function calls in default parameters are evaluated only once when the function is defined, not on each call.

-    options: DecodeOptions = DecodeOptions(),
+    options: t.Optional[DecodeOptions] = None,

Then within the function:

if options is None:
    options = DecodeOptions()
🧰 Tools
🪛 Ruff (0.8.2)

20-20: Do not perform function call DecodeOptions in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable

(B008)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 383f839 and b95cd81.

📒 Files selected for processing (9)
  • src/qs_codec/__init__.py (1 hunks)
  • src/qs_codec/decode.py (2 hunks)
  • src/qs_codec/encode.py (2 hunks)
  • src/qs_codec/models/decode_options.py (1 hunks)
  • src/qs_codec/models/encode_options.py (2 hunks)
  • src/qs_codec/models/undefined.py (1 hunks)
  • src/qs_codec/models/weak_wrapper.py (1 hunks)
  • src/qs_codec/utils/decode_utils.py (1 hunks)
  • src/qs_codec/utils/utils.py (6 hunks)
🧰 Additional context used
🧬 Code Definitions (2)
src/qs_codec/models/encode_options.py (2)
src/qs_codec/utils/encode_utils.py (2)
  • EncodeUtils (14-189)
  • encode (75-98)
src/qs_codec/encode.py (1)
  • encode (19-104)
src/qs_codec/utils/utils.py (1)
src/qs_codec/models/decode_options.py (1)
  • DecodeOptions (12-97)
🪛 Ruff (0.8.2)
src/qs_codec/utils/utils.py

20-20: Do not perform function call DecodeOptions in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable

(B008)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Codacy Static Code Analysis
🔇 Additional comments (19)
src/qs_codec/models/decode_options.py (1)

92-92: Great addition of return type annotation.

Adding the explicit -> None return type annotation to the __post_init__ method improves type checking and code clarity, making it clear that this method doesn't return any value.

src/qs_codec/__init__.py (1)

17-28: Excellent addition of explicit __all__ list.

Adding an __all__ list is a best practice in Python modules as it clearly defines the public API, controls what gets imported with wildcard imports, and helps documentation tools identify the public interface. This change improves module organization and makes the API more explicit.

src/qs_codec/utils/decode_utils.py (1)

36-36: Good removal of redundant type cast.

Removing the redundant cast to str simplifies the code while maintaining functionality, as match.group(0) already returns a string.

src/qs_codec/models/undefined.py (1)

3-4: Excellent type annotations and code simplification.

The changes in this file demonstrate multiple best practices:

  1. Adding proper type annotations to the __new__ method
  2. Using forward references with "Undefined" for self-referencing types
  3. Simplifying the super() call to use the more concise Python 3 syntax

These improvements enhance type checking capabilities and align with modern Python practices.

Also applies to: 11-11, 14-14

src/qs_codec/encode.py (3)

186-186: Improved type annotation clarity.

The type annotation for values has been appropriately updated from t.List to t.List[t.Any], providing more specific type information about the list elements. This enhances static type checking and improves code clarity.


191-191: Type annotation correctly enhanced.

The type annotation for obj_keys has been properly updated from t.List to t.List[t.Any], explicitly indicating that the list can contain elements of any type. This is consistent with other type annotation improvements in the file.


205-205: Type hint refinement is beneficial.

The type annotation for keys has been appropriately updated from t.List to t.List[t.Any], which provides clearer type information and improves static type checking capabilities. This change aligns with Python typing best practices.

src/qs_codec/models/encode_options.py (2)

84-84: Successfully removed unnecessary type ignore directive.

The type ignore directive has been removed from the encoder setter, suggesting that the type checking issue it was suppressing has been resolved. This is a good practice as it reduces the number of suppressed type checks.


97-97: Added explicit return type annotation.

The __post_init__ method now correctly includes a return type annotation -> None, which improves type clarity and helps with static type checking. This is a good practice for method signatures in typed Python code.

src/qs_codec/decode.py (2)

119-119: Enhanced type annotation for improved clarity.

The type annotation for val has been refined from t.Union[t.List, t.Tuple, str, t.Any] to t.Union[t.List[t.Any], t.Tuple[t.Any], str, t.Any], which provides more specific type information about the elements in lists and tuples. This change improves static type checking and code readability.


137-137: Successfully removed unnecessary type ignore directive.

The type ignore directive has been removed from the function call to _interpret_numeric_entities, indicating that the type checking issue it was suppressing has been resolved. This improves code quality by reducing the reliance on type suppressions.

src/qs_codec/models/weak_wrapper.py (1)

18-23: Improved method signature with proper type annotations.

The _hash_recursive method signature has been enhanced with:

  1. An explicit self parameter
  2. Specific type annotations for seen and stack, changing from set to t.Set[t.Any]
  3. Proper type annotation for the value parameter

These changes provide clearer type information and follow Python's typing best practices, improving maintainability and static type checking capabilities.

src/qs_codec/utils/utils.py (7)

18-21: Improved type annotations for merge method parameters and return type.

The more specific type annotations for target, source, and return type provide better static type checking. The changes correctly specify that tuples can contain elements of any type (Tuple[t.Any]), which is more precise than the generic Tuple.

🧰 Tools
🪛 Ruff (0.8.2)

20-20: Do not perform function call DecodeOptions in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable

(B008)


110-116: Enhanced type specificity in compact method.

The type annotations for refs, item, obj, and keys are now more specific by declaring the element types. This improves type checking without changing runtime behavior.


134-134: Better type specification for _remove_undefined_from_list parameter.

Changing from generic t.List to t.List[t.Any] improves type safety by explicitly stating that the list can contain elements of any type.


150-151: Improved type annotations for _remove_undefined_from_map.

The parameter type has been refined from generic t.Dict to t.Dict[t.Any, t.Any] and keys is now explicitly typed as t.List[t.Any]. These changes enhance type checking capabilities.


165-169: Enhanced type specificity for _dicts_are_equal parameters.

The parameters d1, d2, and path now have more specific type annotations, which provides better information for static type checkers and improves code clarity.


192-195: Improved type annotations for combine method parameters and return type.

The changes from generic list, tuple to t.List[t.Any], t.Tuple[t.Any] make the type annotations more specific and the return type t.List[t.Any] provides clearer information about what the method returns.


200-203: Enhanced type specificity for apply method parameters and return type.

The refined type annotations for val and the return type provide better static type checking capabilities while maintaining backward compatibility.

@techouse techouse merged commit b9a386f into main Mar 26, 2025
16 checks passed
@techouse techouse deleted the chore/strict-typing branch March 26, 2025 06:13
techouse added a commit that referenced this pull request Mar 26, 2025
## 1.1.1

* [CHORE] enhance type hints and improve code clarity ([#17](#17))
@coderabbitai coderabbitai bot mentioned this pull request Aug 16, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Use explicit export in src/qs_codec/__init__.py

1 participant