Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 675
Chris J Harris Avatar asked Dec 14 '25 11:12

Chris J Harris


1 Answers

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())
like image 152
orlp Avatar answered Dec 17 '25 01:12

orlp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!