|  | 
|  | 1 | +# oop/cached.property.py | 
|  | 2 | +from functools import cached_property | 
|  | 3 | + | 
|  | 4 | + | 
|  | 5 | +class Client: | 
|  | 6 | +    def __init__(self): | 
|  | 7 | +        print("Setting up the client...") | 
|  | 8 | + | 
|  | 9 | +    def query(self, **kwargs): | 
|  | 10 | +        print(f"Performing a query: {kwargs}") | 
|  | 11 | + | 
|  | 12 | + | 
|  | 13 | +class Manager: | 
|  | 14 | +    @property | 
|  | 15 | +    def client(self): | 
|  | 16 | +        return Client() | 
|  | 17 | + | 
|  | 18 | +    def perform_query(self, **kwargs): | 
|  | 19 | +        return self.client.query(**kwargs) | 
|  | 20 | + | 
|  | 21 | + | 
|  | 22 | +class ManualCacheManager: | 
|  | 23 | +    @property | 
|  | 24 | +    def client(self): | 
|  | 25 | +        if not hasattr(self, '_client'): | 
|  | 26 | +            self._client = Client() | 
|  | 27 | +        return self._client | 
|  | 28 | + | 
|  | 29 | +    def perform_query(self, **kwargs): | 
|  | 30 | +        return self.client.query(**kwargs) | 
|  | 31 | + | 
|  | 32 | + | 
|  | 33 | +class CachedPropertyManager: | 
|  | 34 | +    @cached_property | 
|  | 35 | +    def client(self): | 
|  | 36 | +        return Client() | 
|  | 37 | + | 
|  | 38 | +    def perform_query(self, **kwargs): | 
|  | 39 | +        return self.client.query(**kwargs) | 
|  | 40 | + | 
|  | 41 | + | 
|  | 42 | +manager = CachedPropertyManager() | 
|  | 43 | +manager.perform_query(object_id=42) | 
|  | 44 | +manager.perform_query(name_ilike='%Python%') | 
|  | 45 | + | 
|  | 46 | +del manager.client  # This causes a new Client on next call | 
|  | 47 | +manager.perform_query(age_gte=18) | 
|  | 48 | + | 
|  | 49 | + | 
|  | 50 | +""" | 
|  | 51 | +$ python cached.property.py | 
|  | 52 | +Setting up the client...                         # New Client | 
|  | 53 | +Performing a query: {'object_id': 42}            # first query | 
|  | 54 | +Performing a query: {'name_ilike': '%Python%'}   # second query | 
|  | 55 | +Setting up the client...                         # Another Client | 
|  | 56 | +Performing a query: {'age_gte': 18}              # Third query | 
|  | 57 | +""" | 
0 commit comments