Skip to content

Union should work for constrained type variable #1911

Answered by Daverball
hannes-ucsc asked this question in Q&A
Discussion options

You must be logged in to vote

Right, I hadn't considered the fact that str and bytes don't return Self for most methods but rather the base class. This includes slicing, so:

class MyStr(str):
    pass

reveal_type(MyStr("")[:])  #  str, not MyStr

So the value constrained version is actually more correct for str and bytes, since it can't specialize the generic to a subclass:

class MyStr(str):
    pass

def truncate_bounded[S: str | bytes](s: S) -> S:
    return s[:10]

def truncate_constrained[S: (str, bytes)](s: S) -> S:
    return s[:10]
    
    
reveal_type(truncate_bounded(MyStr("")))  # should be `str`, but actually is `MyStr`
reveal_type(truncate_constrained(MyStr("")))  # is `str`, as it should be, in order to …

Replies: 2 comments 4 replies

Comment options

You must be logged in to vote
0 replies
Comment options

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

@hannes-ucsc
Comment options

@Daverball
Comment options

Answer selected by hannes-ucsc
@hauntsaninja
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants