Reputation: 9465
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
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__()
forcomplex
and__bytes__()
forbytes
are implemented to support thetyping.SupportsComplex
andtyping.SupportsBytes
protocols. (Contributed by Mark Dickinson and Donghee Na in bpo-24234.)
Upvotes: 1
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