Should we add a contains_only type guard to the collection mixin?
![](https://secure.gravatar.com/avatar/0f393da4b8265592816178e5ff6c1c62.jpg?s=120&d=mm&r=g)
As type guards become more popular, this one may become extremely common: ``` _T = TypeVar("_T") class Collection: def contains_only(self, type_: Type[_T]) -> TypeGuard[Collection[_T]]: return all(isinstance(x, type_) for x in self) # usage: usernames = settings_dict['usernames'] assert isinstance(usernames, list) assert usernames.contains_only(str) # Ensure it contains only strings. assert_type(usernames, list[str]) # Should pass, but see note. ``` Would it make sense to add it to the `Collection` mixin so that it's available on all collections? Maybe `is_collection_of` would be a better name? The final check may not be easy to get working without an extra ``` assert isinstance(usernames, list) ``` in today's Pyright/MyPy. Or maybe it would be better to have this work on a `GenericAlias` of a collection? Like ```python assert list[str].typeguard(usernames) ``` The benefit of this being that generic class `G[C]` could use `C.typeguard(vaue)` in its code without knowing what `C` is. E.g. ``` class SupportsTypeguard(Protocol): @classmethod # this needs to be available on the generic alias, though def typeguard(cls) -> TypeGuard[Self]: ... C = TypeVar(C, bound=SupportsTypeguard) class G(Generic[C]): def f(self, ...) -> C: # generate a return value of unknown type assert C.typeguard(value) # Works if C is int, or list[str], or whatever else implements this interface. return value
![](https://secure.gravatar.com/avatar/0f393da4b8265592816178e5ff6c1c62.jpg?s=120&d=mm&r=g)
Or instead of SupportsTypeguard.typeguard, maybe call it SupportsTypeguard.__typeguard__ and then isinstance(x, list[str]) can delegate to it?
![](https://secure.gravatar.com/avatar/3247bfd67c8fa4c4a08b8d30e49eab39.jpg?s=120&d=mm&r=g)
I'm somewhat skeptical that this is a sufficiently common pattern that it would justify adding it to the standard library. You can easily write a type guard function yourself in two lines of code if you want this functionality in your code. Also, `TypeGuard` doesn't work on the `self` parameter in an instance method, so it cannot narrow the type of `self`. It narrows the argument passed to the first parameter after `self` (or `cls` in a class method). Refer to PEP 647 for details. -Eric
participants (2)
-
Eric Traut
-
Neil Girdhar