On Mon, 19 Dec 2022 at 12:29, Steven D'Aprano <st...@pearwood.info> wrote:
> The problem with this is that the builtins are positively hostile to
> subclassing. The issue is demonstrated with this toy example:
>
> class mystr(str):
>     def method(self):
>         return 1234
>
> s = mystr("hello")
> print(s.method())  # This is fine.
> print(s.upper().method())  # This is not.
>

"Hostile"? I dispute that. Are you saying that every method on a
string has to return something of the same type as self, rather than a
vanilla string? Because that would be far MORE hostile to other types
of string subclass:

>>> import dataclasses
>>> from enum import StrEnum
>>> class Demo(StrEnum):
...     x = "eggs"
...     m = "ham"
...
>>> Demo.x
<Demo.x: 'eggs'>
>>> isinstance(Demo.x, str)
True
>>> Demo.x.upper()
'EGGS'
>>> Demo.m + " and " + Demo.x
'ham and eggs'

Demo.x is a string. Which means that, unless there's good reason to do
otherwise, it should behave as a string. So it should be possible to
use it as if it were the string "eggs", including appending it to
something, appending something to it, uppercasing it, etc, etc, etc.

So what should happen if you do these kinds of manipulations? Should
attempting to use a string in a normal string context raise
ValueError?

>>> Demo("ham and eggs")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.12/enum.py", line 726, in __call__
    return cls.__new__(cls, value)
           ^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/enum.py", line 1121, in __new__
    raise ve_exc
ValueError: 'ham and eggs' is not a valid Demo

I would say that *that* would count as "positively hostile to subclassing".

ChrisA
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/HCXWIKZ47LI7UIESEYAP63TP2CGWHR5O/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to