-
I don't know the proper terminology to use to describe the issue so I'm having a hard time searching for posts. I have the following code (simplification of actual code to demonstrate issue). from typing import TypeVar
T = TypeVar('T')
def filter_unprintable(dfx: T) -> T:
if isinstance(dfx, str):
return dfx.translate({10: None})
return dfx This gives
Basically, what can I do to type this without errors? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
The problem here is that Your options include:
return type(dfx)(dfx.translate({10: None}))
@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
def filter_unprintable(dfx: T) -> T:
if isinstance(dfx, str):
return cast(T, dfx.translate({10: None}))
return dfx |
Beta Was this translation helpful? Give feedback.
The problem here is that
str.translate
always returns astr
. That means ifT
is some subclass ofstr
, callingtranslate
will change it into astr
rather than retaining its original type.Your options include:
translate
, manually construct a new value that is guaranteed to have the same type asdfx
:cast
to tell the type checker to ignore the error. This is perhaps the …