collections.UserString can take away a lot of this boilerplate pain from
user defined str subclasses.

On Sun, Dec 18, 2022 at 7:28 PM Steven D'Aprano <st...@pearwood.info> wrote:

> On Sun, Dec 18, 2022 at 07:38:06PM -0500, David Mertz, Ph.D. wrote:
>
> > However, if you want to allow these types to possibly *do* something with
> > the strings inside (validate them, canonicalize them, do a security
> check,
> > etc), I think I like the other way:
> >
> > #2
> >
> > class html(str): pass
> > class css(str): pass
>
> 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.
>
>
> To be useable, we have to override every string method that returns a
> string. Including dunders. So your class becomes full of tedious boiler
> plate:
>
>     def upper(self):
>         return type(self)(super().upper())
>     def lower(self):
>         return type(self)(super().lower())
>     def casefold(self):
>         return type(self)(super().casefold())
>     # Plus another 29 or so methods
>
> This is not just tedious and error-prone, but it is inefficient: calling
> super returns a regular string, which then has to be copied as a
> subclassed string and the original garbage collected.
>
>
> --
> Steve
> _______________________________________________
> 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/O7PU5FLLGNR7IR2V667LDPBBOEXF5NFU/
> Code of Conduct: http://python.org/psf/codeofconduct/
>
_______________________________________________
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/4RIQ65SHYK3T2KZ2XKOPD45KH2SOFQFI/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to