On Thu, 22 Dec 2022 at 03:41, Christopher Barker <[email protected]> wrote:
>
> On Wed, Dec 21, 2022 at 1:18 AM Steven D'Aprano <[email protected]> wrote:
>>
>> On Tue, Dec 20, 2022 at 11:55:49PM -0800, Jeremiah Paige wrote:
>> > @property
>> > def data(self):
>> > return f"{self}"
>>
>> By my testing, on Python 3.10, this is slightly faster still:
>>
>> @property
>> def data(self):
>> return "".join((self,))
>
>
> I think both of those will call self.__str__, which creates a recursion --
> that's what I'm trying to avoid.
>
> I'm sure there are ways to optimize this -- but only worth doing if it's
> worth doing at all :-)
>
Second one doesn't seem to.
>>> class Str(str):
... def __str__(self):
... print("str!")
... return "spam"
... def __repr__(self):
... print("repr!")
... return "SPAM"
...
>>> s = Str("ham")
>>> f"{s}"
str!
'spam'
>>> "".join((s,))
'ham'
Interestingly, neither does the f-string, *if* you include a format
code with lots of room. I guess str.__format__ doesn't always call
__str__().
>>> f"{s:s}"
repr!
SPAM
>>> f"{s:1s}"
repr!
SPAM
>>> f"{s:14s}"
'ham '
Curiouser and curiouser. Especially since the returned strings aren't
enclosed in quotes. Let's try something.
>>> format(s, "10s") is s
False
>>> format(s, "s") is s
True
>>> format(s) is s
str!
False
Huh. How about that.
ChrisA
_______________________________________________
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/MJEMRGGUMAFP5W2FSRZJXG7MPWNN44GU/
Code of Conduct: http://python.org/psf/codeofconduct/