El lun., 1 jun. 2020 a las 13:46, Luciano Ramalho (<luciano@ramalho.org>) escribió:
I am working on a PR for typeshed that will use a protocol
(_SupportsLessThan) to make sure that the parameterized type of
arguments to `sorted` can be sorted—which requires they implement
`__lt__`.

In Python 3, there are two cases relevant to this discussion:

- if no `key` argument is given, then the first arg of `sorted` must
be `Iterable[SupportsLessThan]`.
- if a `key` argument is given, then the first argument can be
`Iterable[Any]`, but the `key` argument must be a callable that
returns a value that `SupportsLessThan`

The same PR is supposed to enhance the type hints for the `list.sort`
method, but in this case, I don't know how to deal with the case where
no `key` is given. Can I just annotate `self`?

I believe that should be OK. See mypy's documentation at https://mypy.readthedocs.io/en/stable/more_types.html#advanced-uses-of-self-types. I don't know whether other typecheckers fully support this pattern (pyanalyze certainly doesn't), but it should be acceptable in tyeshed.
 
class list:
    ...
    def sort(self: List[SupportsLessThan]... etc....

The whole thing is more complicated than I just described, @overload
is required to make the `sorted` annotations. My question is about
constraining `self`, because it turns out that not all list instances
are sortable...

Cheers,

Luciano

--
Luciano Ramalho
|  Author of Fluent Python (O'Reilly, 2015)
|     http://shop.oreilly.com/product/0636920032519.do
|  Technical Principal at ThoughtWorks
|  Twitter: @ramalhoorg
_______________________________________________
Typing-sig mailing list -- typing-sig@python.org
To unsubscribe send an email to typing-sig-leave@python.org
https://mail.python.org/mailman3/lists/typing-sig.python.org/
Member address: jelle.zijlstra@gmail.com