Skip to content

Function with multiple generic parameters of same type #1201

Answered by erictraut
sh0ck-wave asked this question in Q&A
Discussion options

You must be logged in to vote

No, you can't accomplish this with bound TypeVars. The constraint solver will find always find a valid solution using either a union (Sandwich | Rice) or a join (Food). Both solutions are valid.

As you pointed out, you can use a constrained TypeVar to accomplish this, but that requires each subtype to be listed in the TypeVar definition.

Here's another variant that does work with a bound TypeVar, but it requires another class.

class FoodMixer(Generic[K]):
    def __init__(self, f1: K):
        self._f1 = f1

    def mix(self, f2: K) -> K:
        return self._f1.mix(f2)

FoodMixer(Rice(10)).mix(Sandwich(5)) # Type error

And here's another variant, but it requires you to explicitly special…

Replies: 3 comments 5 replies

Comment options

You must be logged in to vote
1 reply
@sh0ck-wave
Comment options

Answer selected by sh0ck-wave
Comment options

You must be logged in to vote
4 replies
@erictraut
Comment options

@hauntsaninja
Comment options

@hmc-cs-mdrissi
Comment options

@sh0ck-wave
Comment options

Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
5 participants