Skip to content

Unable to assign type to generic (probably working as intended?) #9929

Answered by erictraut
Sxderp asked this question in Q&A
Discussion options

You must be logged in to vote

The problem here is that str.translate always returns a str. That means if T is some subclass of str, calling translate will change it into a str rather than retaining its original type.

Your options include:

  1. After calling translate, manually construct a new value that is guaranteed to have the same type as dfx:
return type(dfx)(dfx.translate({10: None}))
  1. Use an overload:
@overload
def filter_unprintable(dfx: str) -> str: ...
@overload
def filter_unprintable(dfx: T) -> T: ...
def filter_unprintable(dfx: T | str) -> T | str:
    if isinstance(dfx, str):
        return dfx.translate({10: None})
    return dfx
  1. Use a cast to tell the type checker to ignore the error. This is perhaps the …

Replies: 1 comment

Comment options

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