Created
July 31, 2024 16:07
-
-
Save CodeByAidan/7f8d4caa6584e23e2f53fb88ef8b2641 to your computer and use it in GitHub Desktop.
Custom implementation of ABCMeta with caching for isinstance checks
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
| import collections.abc | |
| from types import SimpleNamespace | |
| class CustomABCMeta(type): | |
| _abc_cache = set() | |
| _abc_negative_cache = set() | |
| _abc_negative_cache_version = 0 | |
| _abc_invalidation_counter = 0 | |
| def __instancecheck__(cls, instance): | |
| subclass = instance.__class__ | |
| if subclass in cls._abc_cache: | |
| return True | |
| subtype = type(instance) | |
| if subtype is subclass: | |
| if (cls._abc_negative_cache_version == | |
| cls._abc_invalidation_counter and | |
| subclass in cls._abc_negative_cache): | |
| return False | |
| return cls.__subclasscheck__(subclass) | |
| return any(cls.__subclasscheck__(c) for c in {subclass, subtype}) | |
| ABCMeta = SimpleNamespace( | |
| _abc_cache={dict}, | |
| _abc_negative_cache={list, pd.Series}, | |
| _abc_negative_cache_version=1, | |
| _abc_invalidation_counter=1 | |
| ) | |
| class CustomMapping(metaclass=CustomABCMeta): | |
| pass |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Used as part of this example: