Python type hint for classes that support __getitem__

前端 未结 3 519
半阙折子戏
半阙折子戏 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:26

    This will work for dict and list, but not for any generic type:

    from typing import Any, Mapping, Sequence, Union
    
    def my_function(hasitems: Union[Mapping, Sequence], locator: Any) -> Any:
        return hasitems[locator]
    

提交回复
热议问题