简体   繁体   中英

How to annotate a type that is a combination of multiple duck-types?

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 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM