Created
May 9, 2022 12:27
-
-
Save Yourun-proger/432d6bb0ad233389d4f519350a571c20 to your computer and use it in GitHub Desktop.
One of @Tishka17 tasks. Maybe it's wrong
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 time | |
from dataclasses import dataclass | |
from typing import List | |
@dataclass | |
class Item: | |
id: int | |
name: str | |
class SomeClient: | |
def get_object(self, item_id) -> Item: | |
time.sleep(1) | |
return Item(item_id, "name") | |
def list_objects(self) -> List[Item]: | |
time.sleep(1) | |
return [Item(i, "name") for i in range(10)] | |
def put_object(self, item: Item) -> None: | |
time.sleep(1) | |
class CachedClient: | |
def __init__(self, client): | |
self.client = client | |
self.cache = {} | |
def get_object(self, item_id) -> Item: | |
if self.cache.get(item_id): | |
return self.cache[item_id] | |
obj = self.client.get_object(item_id) | |
self.cache[item_id] = obj | |
return obj | |
def list_objects(self) -> List[Item]: | |
if self.cache.get('lst'): | |
return self.cache['lst'] | |
lst = self.client.list_objects() | |
self.cache['lst'] = lst | |
return lst | |
def put_object(self, item: Item) -> None: | |
self.cache[item.id] = Item | |
c = SomeClient() | |
cached_c = CachedClient(c) | |
print(cached_c.get_object(4)) # Slowly | |
print(cached_c.get_object(4)) # Fast | |
print("_______________________") | |
print(cached_c.list_objects()) # Slowly | |
print(cached_c.list_objects()) # Fast | |
print("_______________________") | |
cached_c.put_object(Item(id=42, name='bob')) | |
print(cached_c.cache) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment