Skip to content

Improve performance of exceptions #161242

Open

Description

@eendebakpt

Feature or enhancement

Raising exceptions in python is rather expensive:

d = {'a': 'b', 'c': 1}

def f():
    try: return d['x']
    except: pass
def g():
    if 'x' in d:
        return d['x']
%timeit f()
%timeit g()

211 ns ± 1.08 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)
31.5 ns ± 0.265 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)

We can improve this by using freelists (for tracebacks and exceptions), using managed dicts for exceptions and improving the performance of attribute setters.

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

Linked PRs

Activity

  1. added
    performancePerformance or resource usage
    interpreter-core(Objects, Python, Grammar, and Parser dirs)
    on Nov 3, 2026
  2. cmaloney commented on Nov 3, 2026

    @cmaloney
    Contributor

    👍 to adding a freelist.

    I'm planning to use AC Vectorcall on the core exception hierarchy including AttributeError and KeyError which should help a number of cases although have to be careful in application. Some exceptions store the args tuple and going tuple -> Vectorcall -> tuple is slower than not doing vectorcall unless take special care.

    OSError currently spends most its time re-encoding the output of strerror_r as a str which I plan to fix (just keep all the ones we've encountered as a dict of immortal strings).

    Can I use this issue for that work or would you rather a separate one?

  3. added 2 commits that reference this issue on Nov 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-core(Objects, Python, Grammar, and Parser dirs)performancePerformance or resource usagetype-featureA feature request or enhancement

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions