Let’s say I want to annotate the parameter to a function, and it should satisfy both typing.Sized
and typing.Hashable
(any other 2+ types could apply, I just picked these two for the sake of example). How would I annotate this?
Given that one can combine types as an “or” using Sized | Hashable
, I would expect something like: Sized & Hashable
or Sized + Hashable
to work, but unfortunately it doesn’t (at the time of writing on Python 3.10).
Is this supported at all, and if so with what syntax?
Advertisement
Answer
Sized & Hashable
is a reasonable guess, but unfortunately intersection types are not supported.
You’ll have to define your own subclass that inherits from both:
class SizedHashable(Sized, Hashable): pass
There seems to be some effort being made to support intersection types, but I can’t find any updates beyond this brief mention.