Union should work for constrained type variable #1911
Replies: 2 comments 4 replies
-
If you want to be able to pass in an union you should use an upper bound of It's rare that you actually need a constrained type variable. They're not very well specced out currently, so you can expect many bugs and weird corner cases. def truncate[S: str | bytes](s: S) -> S:
return s[:10]
def log(v: str | bytes):
print(truncate(v)) I see that this version leads to a different error in mypy for |
Beta Was this translation helpful? Give feedback.
-
Thank you! If it's a bug in https://mypy-play.net/?mypy=master&python=3.12&gist=89357de9ce83741a67351b0ed4f1e6ff class A:
def f(self) -> A:
return A()
class B:
def f(self) -> B:
return B()
def truncate[S: A | B](s: S) -> S:
return s.f() # error: Incompatible return value type (got "A | B", expected "S") [return-value]
def truncate2[S: (A, B)](s: S) -> S:
return s.f() I am stupefied. Do you still recommend filing a bug against |
Beta Was this translation helpful? Give feedback.
-
https://mypy-play.net/?mypy=master&python=3.12&gist=f0db7bce0a6d929cff485bd50c76a158
How can I avoid the error without narrowing to every possible alternative of the union (note how the
if
andelse
branches are identical) …… or adding overloads to
truncate
? Both seem like inelegant and tedious workarounds.Beta Was this translation helpful? Give feedback.
All reactions