I’m regularly defining this function, which helps make my code shorter and easier to read. I think it may be a good idea to add something like this to the typing module:
def safe_cast[T](t: type[T], x: object) -> T:
if not isinstance(x, t):
raise TypeError(f'Expecting {x!r} to be of type {t!r}')
return x
It is very useful when I want my code to type-check, and I want a quick failure if my assumptions aren’t satisfied. This comes a lot when parsing objects coming from json, and also in other cases where a function can return one of several types and I expect a specific one.
My current use case: I’m using pygit2, and this allows me to write:
commits.append(safe_cast(Commit, repo[commit_id]))
instead of:
tmp = repo[commit_id]
assert isinstance(tmp, Commit)
commits.append(tmp)
With the extra benefit of a better error message in case the assertion fails.
The easiest solution right now is to just use typing.cast, and I guess that that’s what most people do. But this contradicts “Errors should never pass silently”, from the Zen of Python. Or, in other words, I prefer to catch the error sooner rather than later.
Note: I deliberately suggest a simple function, that doesn’t handle generics. This is just meant as a shorthand for assert isinstance, not as a way to solve complex typing problems.
WDYT?
Edit: changed the name from assert_cast to safe_cast, I like it better. Thanks @tmk!