On Tue, Oct 6, 2020 at 6:50 PM Ricky Teachey <ricky@teachey.org> wrote:
On Tue, Oct 6, 2020 at 9:35 PM Steven D'Aprano <steve@pearwood.info> wrote:
On Tue, Oct 06, 2020 at 09:30:06AM -0700, aleksiy123 wrote:
> Currently there are a few Protocols
> https://docs.python.org/3/library/typing.html#protocols defined in the
> typing module. One that I recently felt like was missing was a typing
> annotation for classes with a __str__() method defined. Seems like a fairly
> straightforward implementation.
 
Why do you care specifically about the `__str__` dunder? Calling str()
is one of those protocols that should always succeed, whether the
argument defines `__str__`, `__repr__`, or inherits from object.

Ignoring the possibility of bugs or deliberate raising, I can't think of
any object that doesn't support the str() protocol. Have I missed
anything?
 
I was also finding this desire a little puzzling (and thought it might just be my inexperience).

And since both `type` and `object` have a __str__ method*, it seems like the only way any object could NOT support the str() protocol would be to write a __str__ method and deliberately bust it. Right?  Is there even a way to create a python object that does not have `__str__` in the MRO?

Seeing as that is the case, and seeing as how the protocol system can't look inside your __str__ method to find out whether it is busted at type checking time, isn't `Any` all you'll ever need to type-hint the __str__ protocol?

* and upon checking in fact it is the same __str__ method

There's somewhat a precedent -- though it's a questionable one (Luciano discovered this). It shows how tricky these things are though.

There's a `typing.SupportsFoat` protocol that checks for the presence of a `__float__` method, and a `typing.SupportsComplex` protocol that checks for `__complex__`. Ironically, complex numbers have a `__float__` method that always fails, and floats don't have a `__complex__` method but complex(x) succeeds if x is a float...

--
--Guido van Rossum (python.org/~guido)