Skip to content

Commit

Permalink
bpo-36972: Add SupportsIndex (GH-13448)
Browse files Browse the repository at this point in the history
In order to support typing checks calling hex(), oct() and bin() on user-defined classes, a SupportIndex protocol is required. The ability to check these at runtime would be good to add for completeness sake. This is pretty much just a copy of SupportsInt with the names tweaked.
  • Loading branch information
pcd1193182 authored and ilevkivskyi committed May 22, 2019
1 parent 33e71e0 commit 4c7a46e
Show file tree
Hide file tree
Showing 5 changed files with 21 additions and 0 deletions.
6 changes: 6 additions & 0 deletions Doc/library/typing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -529,6 +529,12 @@ The module defines the following classes, functions and decorators:

An ABC with one abstract method ``__bytes__``.

.. class:: SupportsIndex

An ABC with one abstract method ``__index__``.

.. versionadded:: 3.8

.. class:: SupportsAbs

An ABC with one abstract method ``__abs__`` that is covariant
Expand Down
4 changes: 4 additions & 0 deletions Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -568,6 +568,10 @@ def test_reversible(self):
self.assertIsSubclass(list, typing.Reversible)
self.assertNotIsSubclass(int, typing.Reversible)

def test_supports_index(self):
self.assertIsSubclass(int, typing.SupportsIndex)
self.assertNotIsSubclass(str, typing.SupportsIndex)

def test_protocol_instance_type_error(self):
with self.assertRaises(TypeError):
isinstance(0, typing.SupportsAbs)
Expand Down
9 changes: 9 additions & 0 deletions Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@
'SupportsBytes',
'SupportsComplex',
'SupportsFloat',
'SupportsIndex',
'SupportsInt',
'SupportsRound',

Expand Down Expand Up @@ -1304,6 +1305,14 @@ def __bytes__(self) -> bytes:
pass


class SupportsIndex(_Protocol):
__slots__ = ()

@abstractmethod
def __index__(self) -> int:
pass


class SupportsAbs(_Protocol[T_co]):
__slots__ = ()

Expand Down
1 change: 1 addition & 0 deletions Misc/ACKS
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,7 @@ Tom Culliton
Raúl Cumplido
Antonio Cuni
Brian Curtin
Paul Dagnelie
Lisandro Dalcin
Darren Dale
Andrew Dalke
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add SupportsIndex protocol to the typing module to allow type checking to detect classes that can be passed to `hex()`, `oct()` and `bin()`.

0 comments on commit 4c7a46e

Please sign in to comment.