Skip to content

Fix/review cleanup#281

Merged
vinitkumar merged 8 commits intomasterfrom
fix/review-cleanup
Apr 8, 2026
Merged

Fix/review cleanup#281
vinitkumar merged 8 commits intomasterfrom
fix/review-cleanup

Conversation

@vinitkumar
Copy link
Copy Markdown
Owner

@vinitkumar vinitkumar commented Apr 8, 2026

Summary by Sourcery

Reuse a module-level secure random generator and correct the handling of optional XML namespace configuration in dicttoxml while cleaning up unused test fixtures.

Bug Fixes:

  • Fix dicttoxml xml_namespaces parameter to avoid using a mutable default and handle a None value safely.

Enhancements:

  • Reuse a single SystemRandom instance at module level for ID generation to avoid repeated instantiation.

Tests:

  • Remove unused setUp and tearDown methods from the json2xml test class.

vinitkumar and others added 5 commits April 8, 2026 12:50
xml_namespaces had a mutable default dict which is a classic Python
footgun where mutations persist across calls. Changed to None with
an 'or {}' guard inside the function body, matching the pattern
already used in dicttoxml_fast.py.

Amp-Thread-ID: https://ampcode.com/threads/T-019d6bf2-ce86-763d-8c62-08118f358cbe
Co-authored-by: Amp <amp@ampcode.com>
These typing imports were dead code since the file already uses
the built-in dict[...] and list[...] syntax everywhere.

Amp-Thread-ID: https://ampcode.com/threads/T-019d6bf2-ce86-763d-8c62-08118f358cbe
Co-authored-by: Amp <amp@ampcode.com>
These were unittest-style no-op methods that serve no purpose in
pytest classes.

Amp-Thread-ID: https://ampcode.com/threads/T-019d6bf2-ce86-763d-8c62-08118f358cbe
Co-authored-by: Amp <amp@ampcode.com>
Avoids creating a new SystemRandom instance on every make_id() call.
The module-level _SAFE_RANDOM is reused across all invocations.

Amp-Thread-ID: https://ampcode.com/threads/T-019d6bf2-ce86-763d-8c62-08118f358cbe
Co-authored-by: Amp <amp@ampcode.com>
@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai bot commented Apr 8, 2026

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Centralizes use of SystemRandom for ID generation and fixes a mutable default argument in dicttoxml’s xml_namespaces parameter, plus minor test cleanup.

Class diagram for updated dicttoxml module structure

classDiagram
    class DicttoxmlModule {
        +SystemRandom _SAFE_RANDOM
        +str make_id(element, start, end)
        +bytes dicttoxml(obj, root, ids, attr_type, item_wrap, item_func, cdata, xml_namespaces, list_headers, xpath_format)
        +str get_unique_id(element)
    }

    class SystemRandom {
        +int randint(start, end)
    }

    DicttoxmlModule --> SystemRandom : uses _SAFE_RANDOM
    DicttoxmlModule ..> SystemRandom : make_id uses randint()
Loading

File-Level Changes

Change Details Files
Reuse a module-level SystemRandom instance for ID generation in dicttoxml.
  • Introduce a private module-level _SAFE_RANDOM = SystemRandom() instance.
  • Update make_id to use the shared _SAFE_RANDOM instead of instantiating SystemRandom on each call.
json2xml/dicttoxml.py
Fix dicttoxml xml_namespaces parameter to avoid mutable default arguments and normalize to a dict at runtime.
  • Change xml_namespaces parameter type from dict[str, Any] = {} to dict[str, Any]
None = None in dicttoxml signature.
  • Initialize xml_namespaces to an empty dict inside dicttoxml when the argument is None.
  • Keep existing namespace processing logic intact while relying on the normalized xml_namespaces value.
  • Remove unused test fixture hooks from TestJson2xml.
    • Delete empty setUp and tearDown methods that had no behavior in TestJson2xml.
    tests/test_json2xml.py

    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. You can also reply to a
      review comment with @sourcery-ai issue to create an issue from it.
    • Generate a pull request title: Write @sourcery-ai anywhere in the pull
      request title to generate a title at any time. You can also comment
      @sourcery-ai title on the pull request to (re-)generate the 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 exactly where you
      want it. You can also comment @sourcery-ai summary on the pull request to
      (re-)generate the summary at any time.
    • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
      request to (re-)generate the reviewer's guide at any time.
    • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
      pull request to resolve all Sourcery comments. Useful if you've already
      addressed all the comments and don't want to see them anymore.
    • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
      request to dismiss all existing Sourcery reviews. Especially useful if you
      want to start fresh with a new review - don't forget to comment
      @sourcery-ai review to trigger a new review!

    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

    @codecov
    Copy link
    Copy Markdown

    codecov bot commented Apr 8, 2026

    Codecov Report

    ✅ All modified and coverable lines are covered by tests.
    ✅ Project coverage is 95.93%. Comparing base (33dc6ba) to head (248c9bf).
    ⚠️ Report is 1 commits behind head on master.

    Additional details and impacted files
    @@            Coverage Diff             @@
    ##           master     #281      +/-   ##
    ==========================================
    + Coverage   95.91%   95.93%   +0.01%     
    ==========================================
      Files           5        5              
      Lines         465      467       +2     
    ==========================================
    + Hits          446      448       +2     
      Misses         19       19              
    Flag Coverage Δ
    unittests 95.93% <100.00%> (+0.01%) ⬆️

    Flags with carried forward coverage won't be shown. Click here to find out more.

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

    Copy link
    Copy Markdown
    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 - I've found 2 issues

    Prompt for AI Agents
    Please address the comments from this code review:
    
    ## Individual Comments
    
    ### Comment 1
    <location path="json2xml/dicttoxml.py" line_range="800" />
    <code_context>
         item_func: Callable[[str], str] = default_item_func,
         cdata: bool = False,
    -    xml_namespaces: dict[str, Any] = {},
    +    xml_namespaces: dict[str, Any] | None = None,
         list_headers: bool = False,
         xpath_format: bool = False,
    </code_context>
    <issue_to_address>
    **suggestion:** Avoid using `or {}` so that only `None` is treated as the "no namespaces" case
    
    `xml_namespaces = xml_namespaces or {}` will replace any falsy-but-valid value (including custom mapping-like objects with `__bool__` returning `False`) with `{}`, which can be surprising. Prefer an explicit `None` check instead:
    
    ```python
    if xml_namespaces is None:
        xml_namespaces = {}
    ```
    
    This preserves existing behavior for `None` while not altering other valid inputs.
    
    ```suggestion
        if xml_namespaces is None:
            xml_namespaces = {}
    ```
    </issue_to_address>
    
    ### Comment 2
    <location path="tests/test_json2xml.py" line_range="21" />
    <code_context>
     class TestJson2xml:
         """Tests for `json2xml` package."""
    
    </code_context>
    <issue_to_address>
    **suggestion (testing):** Add tests covering the updated `xml_namespaces` behavior in `dicttoxml` (None default, no shared mutation, and explicit namespaces).
    
    Since `xml_namespaces` changed from a mutable default (`{}`) to an optional argument (`None` with `xml_namespaces = xml_namespaces or {}`), tests should explicitly cover:
    
    1. Calling `dicttoxml` without `xml_namespaces` and confirming the output matches previous behavior (no unexpected namespace attributes).
    2. Calling `dicttoxml` with an explicit `xml_namespaces` dict (including `xsi` with multiple schema attributes) and asserting the XML has the expected namespace declarations and attributes.
    3. Reusing the same `xml_namespaces` dict across multiple calls and asserting the dict is unchanged and namespaces don’t accumulate.
    
    These will guard against regressions in the new default-handling logic and verify the mutable-default fix is behaviorally transparent.
    </issue_to_address>

    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.

    @@ -21,12 +21,6 @@
    class TestJson2xml:
    Copy link
    Copy Markdown
    Contributor

    Choose a reason for hiding this comment

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

    suggestion (testing): Add tests covering the updated xml_namespaces behavior in dicttoxml (None default, no shared mutation, and explicit namespaces).

    Since xml_namespaces changed from a mutable default ({}) to an optional argument (None with xml_namespaces = xml_namespaces or {}), tests should explicitly cover:

    1. Calling dicttoxml without xml_namespaces and confirming the output matches previous behavior (no unexpected namespace attributes).
    2. Calling dicttoxml with an explicit xml_namespaces dict (including xsi with multiple schema attributes) and asserting the XML has the expected namespace declarations and attributes.
    3. Reusing the same xml_namespaces dict across multiple calls and asserting the dict is unchanged and namespaces don’t accumulate.

    These will guard against regressions in the new default-handling logic and verify the mutable-default fix is behaviorally transparent.

    vinitkumar and others added 3 commits April 8, 2026 15:29
    Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
    @vinitkumar vinitkumar merged commit 15b1de3 into master Apr 8, 2026
    62 checks passed
    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