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 -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/O7PU5FLLGNR7IR2V667LDPBBOEXF5NFU/
Code of Conduct: http://python.org/psf/codeofconduct/