Created
October 21, 2020 17:56
-
-
Save jph00/b005513fe9d1e3892efa81f1ce6e50fe to your computer and use it in GitHub Desktop.
A start on how to work around the annoying python behavior that isinstance doesn't work with generics in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from fastcore.all import * | |
from typing import _SpecialForm,_GenericAlias,Optional,Union | |
@patch | |
def __instancecheck__(self:_SpecialForm, typs): return isinstance(self, typs) | |
@patch(cls_method=True) | |
def __subclasscheck__(self:_SpecialForm, cls): return type.__subclasscheck__(self, cls) | |
@patch | |
def __subclasscheck__(self:_GenericAlias, cls): | |
return issubclass(cls.__origin__ if isinstance(cls, _GenericAlias) else cls, self.__origin__) | |
# test: | |
a = Optional[int] | |
isinstance(a,Optional),isinstance(a,int) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment