On Tue, Dec 20, 2022 at 5:38 PM Christopher Barker <python...@gmail.com> wrote:
> But collections.UserString does exist -- so if you want to subclass, and > performance isn't critical, then use that. Steven A pointed out that > UserStrings are not instances of str though. I think THAT is a bug. And > it's probably that way because with the magic of duck typing, no one cared > -- but with all the static type hinting going on now, that is a bigger > liability than it used to be. Also basue when it was written, you couldn't > subclass str. > > Though I will note that run-time type checking of string is relatively > common compared to other types, due to the whole a-str-is-a-sequence-of-str > issue making the distinction between a sequence of strings and a string > itself is sometimes needed. And str is rarely duck typed. > Note that UserString does break some built-in functionality, like you can't apply regular expressions to a UserString: >>> class FooString(UserString): ... pass ... >>> re.compile(r"asdf").match(FooString("asdf")) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: expected string or bytes-like object, got 'FooString' There is more discussion in this thread ( https://stackoverflow.com/questions/59756050/python3-when-userstring-does-not-behave-as-a-string), including a link to a very old bug (https://bugs.python.org/issue232493). There is a related issue with json.dump etc, though it can be worked around since there is a python-only json implementation. I have run into this in practice at a previous job, with a runtime "taint" tracker for logging access to certain database fields in a Django application. Many views would select all fields from a table, then not actually use the fields I needed to log access to, which generated false positives. (Obviously the "correct" design is to only select data that is relevant for the given code, but I was instrumenting a legacy codebase with updated compliance requirements.) So I think there is some legitimate use for this, though object proxies can be made to work around most of the issues. - Lucas
_______________________________________________ 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/DZQNWKTSUTKRMA4WFXVERW46AMPYDEAX/ Code of Conduct: http://python.org/psf/codeofconduct/