Python type hint for classes that support __getitem__

前端 未结 3 484
半阙折子戏
半阙折子戏 2020-12-06 16:42

I want to add type hints to a function that will accept any object with a __getitem__ method. For instance, in

def my_function(hasitems, locator         


        
3条回答
  •  失恋的感觉
    2020-12-06 17:28

    If you're willing to install a not-quite-offical extension to typing, typing-extensions, you can use a Protocol, which should be an implementation of PEP-0544:

    from typing_extensions import Protocol
    from typing import Any
    
    class GetItem(Protocol):
        def __getitem__(self: 'Getitem', key: Any) -> Any: pass
    
    class BadGetItem:
        def __getitem__(self, a: int, b: int) -> Any: pass
    
    def do_thing(arg: GetItem):
        pass
    
    do_thing(dict())  # OK
    do_thing(BadGetItem())  # Fails with explanation of correct signature
    do_thing(1)  # Fails
    

提交回复
热议问题