Search code examples
pythonpython-typing

How to specify that a python object must be two types at once


I'm using the Python typing module throughout my project, and I was wondering if there was a way to specify that a given object must be of two different types, at once. This most obviously arises when you have specified two protocols, and expect a single object to fulfil both:

class ReturnsNumbers(Protocol):
    def get_number(self) -> Int:
        pass

class ReturnsLetters(Protocol):
    def get_letter(self) -> str:
        pass

def get_number_and_letter(x: <what should this be?>) -> None:
    print(x.get_number(), x.get_letter())

Thanks in advance!


Solution

  • Create a new type that inherits from all types you wish to combine, as well as Protocol.

    class ReturnsNumbersAndLetters(ReturnsNumbers, ReturnsLetters, Protocol):
        pass
    
    def get_number_and_letter(x: ReturnsNumbersAndLetters) -> None:
        print(x.get_number(), x.get_letter())