On 19/12/2022 03:23, David Mertz, Ph.D. wrote:
On Sun, Dec 18, 2022 at 8:29 PM Steven D'Aprano <[email protected]>
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:
> 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.
Yes, you have to do some more work with the methods you need to use:
class mystr(str):
def method(self):
return 1234
def upper(self):
return mystr(str(self).upper())
s = mystr("hello")
print(s.method()) # prints 1234
print(s.upper()) # prints HELLO
print(s.upper().method()) # prints 1234
Best wishes
Rob Cliffe_______________________________________________
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/OYOTMOG57PSBIMMYVIFXNLPX7Q5TR3GM/
Code of Conduct: http://python.org/psf/codeofconduct/