Skip to content

Skip the __bytes__ lookup in bytes() for exact bytes and int #160931

Open

Description

@cmaloney

Feature or enhancement

Since 3.11 added bytes.__bytes__ (gh-68422), bytes(b) for an exact bytes looks up __bytes__, creates a bound method and calls it, only to get b back. For an exact int the lookup always misses, because int has no
__bytes__.

Both types are immutable, so bytes_new_impl() can check for them first:

  • return an exact bytes argument directly, as PyObject_Bytes() and PyBytes_FromObject() already do;
  • skip the lookup for an exact int.

Subclasses, including bool, still look up __bytes__, so there's no behaviour change.

That makes bytes(b) about 2.2x faster, a bytes subclass Sub(b) about 1.4x, and bytes(16) about 1.1x. Other bytes() calls and the controls are unchanged (pyperf, PGO+LTO).

Benchmark script
import pyperf

runner = pyperf.Runner()
for stmt in ["bytes(b)", "bytes(16)", "bytes(ba)", "bytes(mv)", "bytes(l)",
             "bytes(s, 'ascii')", "bytes(hb)", "Sub(b)", "bytes()",
             "len(l)", "l[0]", "x + 1", "str(x)"]:
    runner.timeit(stmt, stmt,
                  "b = b'abcdefghijklmnop'; ba = bytearray(b); mv = memoryview(b); "
                  "l = list(range(16)); s = 'abcdefghijklmnop'; x = 12345\n"
                  "class Sub(bytes): pass\n"
                  "class HB:\n    def __bytes__(self): return b\n"
                  "hb = HB()")

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
    type-featureA feature request or enhancement
    performancePerformance or resource usage
    interpreter-core(Objects, Python, Grammar, and Parser dirs)
    on Oct 29, 2026
  2. self-assigned this
    on Oct 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

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