Skip to content

Conversation

@Koalal143
Copy link

@Koalal143 Koalal143 commented Nov 28, 2025

Set datetime.now() defaults inside Todo.__init__ only.

Any function call that's used in a default argument will only be performed once, at definition time. The returned value will then be reused by all calls to the function, which can lead to unexpected behaviour (See https://docs.astral.sh/ruff/rules/function-call-in-default-argument/)

Summary by CodeRabbit

Release Notes

  • Bug Fixes
    • Fixed timestamp initialization for todos to capture the current time at creation rather than at module import, preventing todos from sharing identical creation and update timestamps.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link

coderabbitai bot commented Nov 28, 2025

Walkthrough

Modified the Todo class constructor to fix timestamp default handling. Changed created_at and updated_at parameters from mutable default arguments (datetime.now() evaluated at import time) to optional parameters (Optional[datetime] = None) with runtime evaluation using the or pattern.

Changes

Cohort / File(s) Change Summary
Timestamp default argument fix
dddpy/domain/todo/entities/todo.py
Updated created_at and updated_at parameters from datetime = datetime.now() to Optional[datetime] = None, with initialization logic changed to created_at or datetime.now() and updated_at or datetime.now() to evaluate timestamps at runtime rather than import time.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~5 minutes

  • Single file affected with straightforward, well-known pattern fix
  • Addresses common Python mutable default argument gotcha
  • Changes are consistent and repetitive across both timestamp parameters

Poem

🐰 Hop hop, a fix so fine!
No more frozen time at import's line,
Now each todo gets its moment true,
Fresh timestamps, through and through! 🕐✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: removing datetime.now() calls from default arguments in the Todo.init method signature.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Tip

📝 Customizable high-level summaries are now available in beta!

You can now customize how CodeRabbit generates the high-level summary in your pull requests — including its content, structure, tone, and formatting.

  • Provide your own instructions using the high_level_summary_instructions setting.
  • Format the summary however you like (bullet lists, tables, multi-section layouts, contributor stats, etc.).
  • Use high_level_summary_in_walkthrough to move the summary from the description to the walkthrough section.

Example instruction:

"Divide the high-level summary into five sections:

  1. 📝 Description — Summarize the main change in 50–60 words, explaining what was done.
  2. 📓 References — List relevant issues, discussions, documentation, or related PRs.
  3. 📦 Dependencies & Requirements — Mention any new/updated dependencies, environment variable changes, or configuration updates.
  4. 📊 Contributor Summary — Include a Markdown table showing contributions:
    | Contributor | Lines Added | Lines Removed | Files Changed |
  5. ✔️ Additional Notes — Add any extra reviewer context.
    Keep each section concise (under 200 words) and use bullet or numbered lists for clarity."

Note: This feature is currently in beta for Pro-tier users, and pricing will be announced later.


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 and usage tips.

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

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5d1f917 and b846db2.

📒 Files selected for processing (1)
  • dddpy/domain/todo/entities/todo.py (2 hunks)
🔇 Additional comments (1)
dddpy/domain/todo/entities/todo.py (1)

33-34: Excellent fix for the default argument anti-pattern!

The signature change correctly addresses the issue where datetime.now() was evaluated once at import time and reused across all instances. Moving to Optional[datetime] = None with runtime evaluation is the proper pattern.

Comment on lines +52 to +53
self._created_at = created_at or datetime.now()
self._updated_at = updated_at or datetime.now()
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Search for UTC-related expectations and datetime usage patterns

echo "=== Searching for UTC references in Python files ==="
rg -n -C2 'UTC|utc' --type=py

echo -e "\n=== Searching for datetime.now usage patterns ==="
rg -n 'datetime\.(now|utcnow)' --type=py

echo -e "\n=== Searching for timezone-aware datetime usage ==="
rg -n 'timezone|tzinfo|pytz' --type=py

echo -e "\n=== Checking the specific file for timestamp usage ==="
fd 'todo.py' --type f | head -1 | xargs -I {} sh -c 'wc -l "{}" && head -100 "{}"'

Repository: iktakahiro/dddpy

Length of output: 5761


🏁 Script executed:

#!/bin/bash
# Check the full __init__ method around lines 52-53
echo "=== Full __init__ method from todo.py ==="
sed -n '25,60p' dddpy/domain/todo/entities/todo.py | cat -n

echo -e "\n=== Check for any 'or' operators in __init__ assignment ==="
rg -n 'self\._.*=.*or datetime' dddpy/domain/todo/entities/todo.py

echo -e "\n=== All datetime.now() usages with context ==="
rg -n -B2 -A2 'datetime\.now\(\)' dddpy/domain/todo/entities/todo.py

Repository: iktakahiro/dddpy

Length of output: 2784


Based on my verification, I can now provide a definitive assessment. The review comment references code from the PR branch (which includes the or datetime.now() pattern), while the current main branch shows simpler assignments. The search results confirm:

  1. The or pattern fix is sound - The implementation correctly ensures runtime evaluation
  2. The timezone concern is CRITICAL - The evidence decisively proves this is a real bug:
    • Docstring explicitly states timestamps should be "in UTC"
    • Infrastructure layer (todo_dto.py lines 42-44) explicitly converts to UTC with tz=timezone.utc
    • All datetime.now() calls return local time, not UTC
    • This causes data integrity issues

The original review appropriately flagged this as a concern, but the evidence confirms it's a critical pre-existing bug requiring UTC fixes, not just verification.


UTC timestamp bug requires immediate fixing with datetime.now(timezone.utc) or datetime.utcnow().

The infrastructure layer (lines 42-44 in todo_dto.py) explicitly converts timestamps to UTC: datetime.fromtimestamp(self.created_at / 1000, tz=timezone.utc). This proves the system requires UTC timestamps. However, all datetime.now() calls throughout the codebase (lines 33-34, 104, 113, 118, 130, 152) return local time, which will be stored and compared as UTC, causing data corruption in distributed systems or cross-timezone scenarios.

Replace datetime.now() with datetime.now(timezone.utc) in:

  • Lines 33-34 (default parameters)
  • Lines 104, 113, 118, 130 (update methods)
  • Line 152 (is_overdue comparison)

Also update tests in tests/domain/todo/entities/test_todo.py lines 36-37.

🤖 Prompt for AI Agents
In dddpy/domain/todo/entities/todo.py around lines 52-53, the timestamps are set
with datetime.now() which yields local time; change these to use UTC by calling
datetime.now(timezone.utc) (ensure timezone is imported from datetime), and
propagate this UTC change to all other noted spots: replace datetime.now() with
datetime.now(timezone.utc) at the default-parameter lines (33-34), the update
methods (lines 104, 113, 118, 130), and the is_overdue comparison (line 152);
also update tests in tests/domain/todo/entities/test_todo.py (lines 36-37) to
expect UTC timestamps or construct expected datetimes using timezone.utc.

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