0

I look for Type such that the below type-checks OK:

import typing

def f(a: str, collection: Type):
    return a in collection

that is, Type asserts that collection has __contains__.

Anton Daneyko
  • 6,528
  • 5
  • 31
  • 59
  • [collections.abc.Container](https://docs.python.org/3/library/collections.abc.html#collections.abc.Container). – ekhumoro Feb 03 '21 at 18:26

1 Answers1

4

I keep this page bookmarked, because it's a pain to search for, but is also very helpful.

As you can see at the top of that table, a Container is an object that has a __contains__ method:

from typing import Container

def f(a: str, collection: Container[str]):
    return a in collection

The table references classes in collections, but typing contains generic, typed variants of the same classes.

If collections.Container/typing.Container didn't exist, you could also create your own Protocol to have it hinted properly.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117