I have a bit of Python code which depends on type checking. I'll try and phrase my problem in the language of math so it's clear. I have a few classes which correspond to subsets of each other and form an inheritance chain.
class Real(object):
pass
class Integer(Real):
pass
class Natural(Integer):
pass
And I have a tuples containing types. Each of these corresponds to the domain of some function.
t1 = ( Real, Real )
t2 = ( Real , Integer )
I would like to do some form of type checking such that given a another tuple ( Natural , Natural )
if every coordinate in the tuple is a subclass of the specified domains. For example for some function getcompatibles
I'd like to have:
getcompatibles( ( Real, Real ) ) = [ t1 ]
getcompatibles( ( Real, Integer ) ) = [ t1, t2 ]
getcompatibles( ( Natural, Natural ) ) = [ t1, t2 ]
getcompatibles( ( Natural, Real ) ) = [ t1 ]
The only solution I could come up with would be to run through every for domain (t1, t2) run through each of the types in __subclasses__
and check to see whether it isinstance
is True for the given input.
Thats extremely inefficient though, is there perhaps a more Pythonic way of doing this?