Skip to content

Remove call-stack inspection from DateTime.__add__ - #1032

Merged
Secrus merged 1 commit into
python-pendulum:masterfrom
ariebovenberg:remove-stack-walk
Oct 6, 2026
Merged

Secrus merged 1 commit into
python-pendulum:masterfrom
ariebovenberg:remove-stack-walk

Conversation

@ariebovenberg

@ariebovenberg ariebovenberg commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

While investigating #818, I found a big contribution to the slowdown to be a stack walk in DateTime.__add__:

caller = traceback.extract_stack(limit=2)[0].name
if caller == "astimezone":
    return super().__add__(other)

It turns out this exists because ZoneInfo.from_utc() expects arithmetic with standard library semantics when called as part of astimezone. Using the stack walk, DateTime detects this situation and reverts to stdlib semantics. This approach has a high cost (it's slow, and has side effects like #820 ), but there is a relatively cheap alternative: convert DateTime to a datetime before calling astimezone(). The same solution is proposed in #1006 (it doesn't remove the stack walk though).

With this approach, + becomes ±5x faster. in_tz/astimezone become ±10x faster.

There's a theoretical behaviour change: calling + from a function that happens to be called astimezone() will get a different result.

Pull Request Check List

  • Added tests for changed code.
  • Updated documentation for changed code. n/a

AI disclosure: I used Claude Code to code this up. I have reviewed the code thoroughly.

edit: clarity relationto #1006

@codspeed

codspeed Bot commented Oct 5, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 1 untouched benchmark


Comparing ariebovenberg:remove-stack-walk (e7e8ea4) with master (b8ebebe)

Open in CodSpeed

@Secrus
Secrus force-pushed the remove-stack-walk branch from 5f9d55c to e7e8ea4 Compare October 6, 2026 00:02

@Secrus Secrus left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thank you for that improvement!

@Secrus
Secrus merged commit f8ca0f3 into python-pendulum:master Oct 6, 2026
27 checks passed
@ariebovenberg
ariebovenberg deleted the remove-stack-walk branch October 7, 2026 05:30
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.

2 participants