On Sun, Dec 18, 2022 at 8:29 PM Steven D'Aprano <st...@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. > I'd agree to "limited", but not "hostile." Look at the suggestions I mentioned: validate, canoncialize, security check. All of those are perfectly fine in `.__new__()`. E.g.: In [1]: class html(str): ...: def __new__(cls, s): ...: if not "<" in s: ...: raise ValueError("That doesn't look like HTML") ...: return str.__new__(cls, s) In [2]: html("<h1>Hello</h1>") In [3]: html("Hello") --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-3-71d16160c9ad> in <module> ----> 1 html("Hello") <ipython-input-1-e9d5da1202f3> in __new__(cls, s) 2 def __new__(cls, s): 3 if not "<" in s: ----> 4 raise ValueError("That doesn't look like HTML") 5 ValueError: That doesn't look like HTML I readily acknowledge that's not a very thorough validator :-). But this much (say with a better validator) gets you static type checking, syntax highlighting, and inherent documentation of intent. I know that lots of things one can do with a str subclass wind up producing a str instead. But if the thing you do is just "make sure it is created as the right kind of thing for static checking and editor assistance, I don't care about any of that falling back. -- Keeping medicines from the bloodstreams of the sick; food from the bellies of the hungry; books from the hands of the uneducated; technology from the underdeveloped; and putting advocates of freedom in prisons. Intellectual property is to the 21st century what the slave trade was to the 16th.
_______________________________________________ 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/AEQCVTJ2ABFQSQHWM62JOJQJI6UU675Y/ Code of Conduct: http://python.org/psf/codeofconduct/