简体   繁体   中英

How can I specify a subtype of multiple types (including general types, like Callable) in Python type annotations?

One obvious example of this is multiple inheritance: if I have classes Foo and Bar , I can make a class Baz that inherits from both ( class Baz(Foo, Bar): ... ). However, I could also make another class with a different behavior, which still inherits from both Foo and Bar ... or I could inherit from a third class, which makes a completely different type. Obviously, this is a niche use case, but is this supported in Python type annotations? In the example case, I don't want to write Baz specifically - I only need to know the fact that a type is both Foo and Bar , but it can also be anything else. I was thinking something along the lines of param: Foo | Bar param: Foo | Bar or param: typing.Multiple[Foo, Bar] .

My specific use case: I want to use the Callable syntax to specify parameter and return types (eg Callable[..., bool] ) but I also need to make sure that the argument is a FunctionType , ie not a class or builtin_function_or_method. Of course, I could just specify this in the docstring - but is this supported in type annotations in a way that will work with type checkers?

There is a limited version of this through the Protocol class ( PEP , docs ) - however, it only supports type variables ( Protocol[T] ) and concrete types ( class MyProtocol(FunctionType, Protocol) ), but not general types like Any, Union, Callable, Iterator, etc. So, the example case in the question can be implemented as

class FooAndBar(Foo, Bar, typing.Protocol): ...

but the use case mentioned below seems to be impossible ( might be possible eventually ), so for now I'd either define a Protocol with just the members you need, use a string as the type hint, or specify this in a docstring.

Additional note: if you use an IntelliJ IDE, you can write

assert isinstance(param, (Foo, Bar))

which will, for the purposes of type checking, achieve the same result as a hypothetical param: Intersection[Foo, Bar] in any further code.

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