Re: Idea: Tagged strings in python

On 19/12/2022 03:23, David Mertz, Ph.D. wrote:
On Sun, Dec 18, 2022 at 8:29 PM Steven D'Aprano <steve@pearwood.info> 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
participants (1)
-
Rob Cliffe