Skip to content

convert_date: return str for incomplete values instead of raising TypeError - #1287

Open
rahul05ranjan wants to merge 1 commit into
PyMySQL:mainfrom
rahul05ranjan:fix/convert-date-typeerror
Open

rahul05ranjan wants to merge 1 commit into
PyMySQL:mainfrom
rahul05ranjan:fix/convert-date-typeerror

Conversation

@rahul05ranjan

@rahul05ranjan rahul05ranjan commented Oct 29, 2026 •

Copy link
Copy Markdown

Fixes #1286

The bug

The converters' documented contract (docstrings + doctests) is that illegal values are returned unchanged as str. Every malformed input followed it except one class: a value with fewer than three --separated components survived the int() conversion and then blew up datetime.date()'s arity with a raw TypeError:

convert_date('2007-02')     # TypeError: function missing required argument 'day' (pos 3)
convert_datetime('2007-02') # same, via its `except ValueError: return convert_date(obj)` fallback

so a result row containing such a value crashed inside result decoding instead of yielding the string.

Fix

Catch TypeError alongside ValueError in convert_date and pin the behavior with a doctest (>>> convert_date('2007-02') → '2007-02'), matching the module's own doctest-driven test convention.

convert_datetime/convert_timedelta don't need the same catch: their regexes fix the argument count, so arity errors are impossible there; their fallbacks route through convert_date, which now honors the contract.

Verification

  • Pre-fix: convert_date('2007-02') / convert_datetime('2007-02') raise TypeError (reproduced before applying the change via git stash).
  • Post-fix: both return '2007-02'; all previously documented behaviors unchanged ('0000-00-00' → str, '2007-02-31' → str, 'random crap' → str, valid dates/datetimes parse as before).
  • pytest --doctest-modules pymysql/converters.py: 4 passed (including the new doctest line).
  • tests/test_auth.py shows only the same 8 pre-existing host-environment failures (missing CA files / cryptography on this box) before and after the change; CI remains the authority.

Co-authored-by: rahul05ranjan 11793455+rahul05ranjan@users.noreply.github.com

Summary by CodeRabbit

  • Bug Fixes
    • Date conversion now preserves the original input when date construction fails with a type error.

…eError

The documented contract (and existing doctests) for the DATE/TIME
converters is that illegal values are returned unchanged as str, but a
value with fewer than three '-'-separated components reached the
datetime.date() call with too few arguments and raised a raw TypeError
from deep inside result decoding (also reachable through
convert_datetime's fallback). Catch TypeError alongside ValueError and
pin the behavior with a doctest.

Co-authored-by: rahul05ranjan <11793455+rahul05ranjan@users.noreply.github.com>
@coderabbitai

coderabbitai Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 93cbe0f2-5dbe-4c76-9b19-c1a8a430ae7c
Commits

Reviewing files that changed from the base of the PR and between 1aff0a8 and 415bc59.

Files selected for processing: 1
  • pymysql/converters.py

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

Walkthrough

convert_date now returns the original input when date construction raises TypeError, as it already did for ValueError. Its doctest includes an incomplete date as an invalid-value example.

Changes: Date conversion

Layer / File(s) Summary
Invalid date fallback
pymysql/converters.py
convert_date catches TypeError as well as ValueError. The doctest includes 2007-02 as an invalid value.

Priority: Normal

Estimated code review effort: 1 (Trivial) | ~5 minutes

Change: Bug fix · Severity of issue fixed: Medium

Suggested reviewers: methane

Merge Risk: Minimal · up to 415bc

The incomplete-date handling is narrowly scoped and introduces no identified merge-blocking risk.

Pre-merge checks: Passed 5
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely describes the main change: convert_date now returns incomplete values as strings instead of raising TypeError.
Linked Issues check Passed The change satisfies issue #1286. convert_date now catches TypeError from datetime.date arity validation and returns the original value. The new doctest verifies `convert_date('2007-02') == '200…
Out of Scope Changes check Passed The whole-PR diff changes only pymysql/converters.py. It adds the required exception handling and its supporting doctest. No unrelated production or test changes are present.
Docstring Coverage Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentat…
Full details: Linked Issues check

Explanation

The change satisfies issue #1286. convert_date now catches TypeError from datetime.date arity validation and returns the original value. The new doctest verifies convert_date('2007-02') == '2007-02'. convert_datetime routes incomplete values through convert_date, so the reported fallback case is also covered by the implementation.

Full details: Docstring Coverage

Explanation

Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 1 functions across 1 files.

Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@codecov

codecov Bot commented Oct 29, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 85.15%. Comparing base (1e28be8) to head (415bc59).
⚠️ Report is 84 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1287      +/-   ##
==========================================
- Coverage   86.24%   85.15%   -1.10%     
==========================================
  Files          17       17              
  Lines        2436     2492      +56     
  Branches      258      255       -3     
==========================================
+ Hits         2101     2122      +21     
- Misses        249      302      +53     
+ Partials       86       68      -18     

☔ View full report in Codecov by Harness.
📢 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.

This branch has not been deployed

No deployments
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_date raises raw TypeError for incomplete values instead of returning them as str

1 participant