wvxvw
wvxvw

Reputation: 9465

bytes doesn't have __bytes__ method

So... I have code more or less along these lines:

class Foo(bytes):
    def __bytes__(self):
        return b'prefix' + super().__bytes__()

But unique taste for consistency of Python core developers gets in my way, and this attempt fails miserably.

Looking at methods defined on bytes class, I see no way to reproduce its default printing behavior in subclasses.

Or maybe there is a way?

Upvotes: 5

Views: 807

Answers (2)

wim
wim

Reputation: 362836

Since Python 3.11, the code shown in the question works as-is.

>>> class Foo(bytes):
...     def __bytes__(self):
...         return b'prefix' + super().__bytes__()
... 
>>> bytes(Foo(b' hello'))
b'prefix hello'

You can find this mentioned in the CPython changelog:

The special methods __complex__() for complex and __bytes__() for bytes are implemented to support the typing.SupportsComplex and typing.SupportsBytes protocols. (Contributed by Mark Dickinson and Donghee Na in bpo-24234.)

Upvotes: 1

FHTMitchell
FHTMitchell

Reputation: 12157

Just to sum up the comments, the answer is as below (I'm surprised you tried the harder method first):

class Foo(bytes):
    def __bytes__(self):
        return b'prefix' + self

I think bytes not implementing __bytes__() is a bit weird though, and I would raise that as an issue with the python dev team.

Upvotes: 3

Related Questions