Quantcast
Channel: Python type hint for classes that support __getitem__ - Stack Overflow
Viewing all articles
Browse latest Browse all 4

Answer by Felk for Python type hint for classes that support __getitem__

$
0
0

It sounds like you essentially want to define your own abstract base class (abc).

Following the documentation above, you can define a custom abc that only dictates the presence of __getitem__, but let's use a predefined one for an example. The Mapping abc consists of __getitem__ and a few other magic methods. You can use abcs in isinstance, but you can also directly use them as a type annotations:

def foo(bar: Mapping):
    pass

Or, using the extended type hinting support of ABCs do even fancies things, which you already saw in other answers:

def foo(bar: Mapping[Any, Any]):
    pass

Viewing all articles
Browse latest Browse all 4

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>