]> granicus.if.org Git - python/commitdiff
bpo-36972: Add SupportsIndex (GH-13448)
authorPaul Dagnelie <paulcd2000@gmail.com>
Wed, 22 May 2019 14:23:01 +0000 (07:23 -0700)
committerIvan Levkivskyi <levkivskyi@gmail.com>
Wed, 22 May 2019 14:23:01 +0000 (15:23 +0100)
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.

Doc/library/typing.rst
Lib/test/test_typing.py
Lib/typing.py
Misc/ACKS
Misc/NEWS.d/next/Library/2019-05-20-17-08-26.bpo-36972.3l3SGc.rst [new file with mode: 0644]

index c2523ed52960030c41c3076d04e35018b68ef75b..86a3db8467ec742481d5c46a555a44594e8cf4a5 100644 (file)
@@ -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
index a547fe274c878073f537c4bf9c145d64b527d657..c9bfd0c7ed720deba8fef2d761ce58f7c263f8f6 100644 (file)
@@ -568,6 +568,10 @@ class ProtocolTests(BaseTestCase):
         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)
index 530d4633fe4c22a3b6b59c699e1acf699ab39b82..7aab1628a3192b959c7954a84b0a89a57984f333 100644 (file)
@@ -74,6 +74,7 @@ __all__ = [
     'SupportsBytes',
     'SupportsComplex',
     'SupportsFloat',
+    'SupportsIndex',
     'SupportsInt',
     'SupportsRound',
 
@@ -1304,6 +1305,14 @@ class SupportsBytes(_Protocol):
         pass
 
 
+class SupportsIndex(_Protocol):
+    __slots__ = ()
+
+    @abstractmethod
+    def __index__(self) -> int:
+        pass
+
+
 class SupportsAbs(_Protocol[T_co]):
     __slots__ = ()
 
index 6b1fdbc37fa934ebcfca0f3929207458c514aa24..8f0ecb7f1c3758f8f27e622348bd067477d3aacb 100644 (file)
--- a/Misc/ACKS
+++ b/Misc/ACKS
@@ -355,6 +355,7 @@ Tom Culliton
 Raúl Cumplido
 Antonio Cuni
 Brian Curtin
+Paul Dagnelie
 Lisandro Dalcin
 Darren Dale
 Andrew Dalke
diff --git a/Misc/NEWS.d/next/Library/2019-05-20-17-08-26.bpo-36972.3l3SGc.rst b/Misc/NEWS.d/next/Library/2019-05-20-17-08-26.bpo-36972.3l3SGc.rst
new file mode 100644 (file)
index 0000000..da650e8
--- /dev/null
@@ -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()`.