Skip to content

Slicing a bytes object returning <int> with single index #132062

@maxpat78

Description

@maxpat78

Bug report

Bug description:

Consider the first 'if' in the following piece of code.
It used to run nice in Python 2.x (where it was developed):

	if n_offset == 1: # ...BYTE
		offset = struct.unpack_from("<b", offset[0])[0] # offset[0]
	elif n_offset == 2: # ...WORD
		offset = struct.unpack_from("<h", offset[:2])[0]
	elif n_offset in (3,4):  # ...DWORD
		offset = struct.unpack_from("<i", offset[:4])[0]
	else: # ...QWORD
		offset = struct.unpack_from("<q", offset)[0]

Actually, it raises the exception TypeError: a bytes-like object is required, not 'int' and needs an awkward reconversion:

offset = struct.unpack_from("<b", offset[0].to_bytes())[0] # offset[0] -> int ! Must convert back!

Isn't it a contradiction (and a bug) that slicing returns bytes except in the case of a single slicing index???

CPython versions tested on:

3.13

Operating systems tested on:

Windows

Metadata

Metadata

Assignees

No one assigned

    Labels

    invalidtype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions