Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

How to create a TypeGuard that mimics isinstance

$
0
0

I have to check an object that may have been created by an API.When I try using isinstance(obj, MyClass) it get a TypeError if obj was created by the API.

I wrote a custom function to handle this.

def is_instance(obj: Any, class_or_tuple: Any) -> bool:    try:        return isinstance(obj, class_or_tuple)    except TypeError:        return False

The issue I am having is using is_instance() instead of the builtin isinstance() does not have any TypeGuard support, so the type checker complains.

def my_process(api_obj: int | str) -> None:    if is_instance(api_obj, int):        process_int(api_obj)    else:        process_str(api_obj)

"Type int | str cannot be assigned to parameter ..."

How could I create a TypeGuard for this function?


Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>