Created
December 15, 2019 16:08
-
-
Save tweakimp/6b8760ec77fa3aaeb52f141c23583a9c to your computer and use it in GitHub Desktop.
Cached
This file contains 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 weakref | |
class Cached(type): | |
""" | |
Metaclass. | |
Only allows the creation of one type of instance, all other instances | |
with the same initialization variables return the same instance of the | |
first creation. | |
Use: | |
class Test(metaclass=Cached): | |
... | |
""" | |
def __init__(self, *args, **kwargs): | |
super().__init__(*args, **kwargs) | |
self.__cache = weakref.WeakValueDictionary() | |
def __call__(self, *args): | |
if args in self.__cache: | |
return self.__cache[args] | |
else: | |
obj = super().__call__(*args) | |
self.__cache[args] = obj | |
return obj | |
if __name__ == "__main__": | |
class Test(metaclass=Cached): | |
def __init__(self, name): | |
self.name = name | |
print(f"Initializing Test({name})") | |
a = Test("A") | |
b = Test("B") | |
c = Test("A") # Cached | |
print(a is b) | |
print(a is c) # Cached value returned |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment