Roel Schroeven <
roel@roelschroeven.net> wrote or quoted:
As a follow-up, it looks like this behavior is because bytes and int are
immutable.
Alright, so you've stumbled onto some pretty gnarly behavior with
Python's immutable types. Let's unpack this burrito:
1) Here's the skinny on how it goes down with immutable types
like "bytes" and "int":
These bad boys do their thing in "__new__", not
"__init__". It's like trying to change a burrito after
it's been wrapped - ain't going to happen.
When you hit "MyBytes( b'abcdefghijlkmn' )", it's like this:
a) Python calls up "MyBytes.__new__".
b) That passes the buck to "bytes.__new__", which
whips up the new "bytes" object.
c) Then "MyBytes.__init__" gets a shot, but the horse
has already left the barn.
2) Wanna customize those args?
For immutable types, you got to override `__new__`.
It's like swapping out the ingredients before the
burrito's wrapped:
class MyBytes( bytes ):
def __new__( cls, data ):
return super().__new__( cls, data * 2 )
print( MyBytes( b'abc' )) # Spits out: b'abcabc'
3) Why "bytes" (and "int", ...) are different beasts:
You nailed it in your follow-up. It's all about being immutable.
These types are coded in C for speed, but the real kicker
is they can't change after creation.
On your other questions:
- Yeah, immutable types like "bytes" and "int" pretty much
ghost "__init__". All the magic happens in "__new__".
- There's definitely a connection between being immutable
and ditching "__init__". It's like setting your GPS
before you start driving - once you're moving, you can't
change the route.
- That "__init__" doc you quoted? It's legit for mutable
types, but for immutable ones, it's like trying to add
avocado to a sealed burrito - not going to work.
To wrap it up:
- Mutable types: Override "__init__" to set things up.
- Immutable types: "__new__" is where the party's at.
This setup lets Python keep its promises about immutability while
still letting you customize through subclassing. It's like having
your artisanal, gluten-free burrito and eating it too.