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):
hasitems[locator]
I don't want to restrict hasitems to be a specific type like list or dict. As long as it supports __getitem__, it's an appropriate argument to my_function. How can I annotate its type without being unnecessarily restrictive?
Edit: apparently PyCharm can deduce the appropriate hint in a number of common cases, but not in my actual use case. I can't post the code since it's for work, and I haven't been able to find a nonproprietary minimal example where PyCharm fails. In any case, the original question doesn't reference PyCharm and it is still a valid use case for type hints.
abcwith that single abstract method. - juanpa.arrivillagamy_function(5, 10): > Type 'int' doesn't have expected attribute 'getitem' less... (Ctrl+F1) Inspection info: This inspection detects type errors in function call expressions. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Types of function parameters can be specified in docstrings or in Python 3 function annotations. - Liran Funaro