Advertisement
Uno-Dan

Set method fixed.

Sep 7th, 2019
255
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.25 KB | None | 0 0
  1. cfg = {
  2.     'level_1': {
  3.         'level_2': {
  4.             'item1': 10,
  5.             'item2': 20,
  6.         }
  7.     }
  8. }
  9. more_cfg = {
  10.     'level_3': {
  11.         'level_4': {
  12.             'item3': 10,
  13.             'item4': 20,
  14.         }
  15.     }
  16. }
  17.  
  18.  
  19. class Cache:
  20.     def __init__(self, **data):
  21.         self.nodes = data
  22.  
  23.     def get(self, uri=None):
  24.         if not uri:
  25.             return self.nodes
  26.  
  27.         def walk(_uri, nodes):
  28.             parts = _uri.split('/', 1)
  29.             key = parts.pop(0)
  30.  
  31.             if key in nodes:
  32.                 node = nodes[key]
  33.  
  34.                 if not parts:
  35.                     return node
  36.                 else:
  37.                     return walk(parts[0], node)
  38.  
  39.         return walk(uri, self.nodes)
  40.  
  41.     def set(self, uri, *args, **kwargs):
  42.  
  43.         def walk(_uri, nodes):
  44.             parts = _uri.split('/', 1)
  45.             key = parts.pop(0)
  46.  
  47.             if key in nodes and parts:
  48.                 return walk(parts[0], nodes[key])
  49.             elif len(_uri.split('/')) == 1:
  50.                 parameters = args[0] if args else kwargs
  51.                 nodes[key] = parameters
  52.  
  53.         return walk(uri, self.nodes)
  54.  
  55.     def dump(self, indent=None):
  56.         """ Dumps the contents of the cache to the screen.
  57.        The output from dump goes stdout and is used to view the cache contents.
  58.        Default indentation is a dot for each level.
  59.        :param indent:
  60.            indent (str): String to be use for indenting levels.
  61.        :return:
  62.            Nothing.
  63.        """
  64.         indent = indent if indent else '.'
  65.  
  66.         print('-------------------------------------------------------------------------------------------------------')
  67.  
  68.         if self.nodes:
  69.             def walk(_cfg, count):
  70.                 count += 1
  71.                 for key, value in _cfg.items():
  72.                     if isinstance(value, dict):
  73.                         print(indent * count, key)
  74.                         walk(value, count)
  75.                     else:
  76.                         if isinstance(value, str):
  77.                             value = f'"{value}"'
  78.                         print(indent * count, key, value)
  79.             walk(self.nodes, 0)
  80.         else:
  81.             print(' (No Data)')
  82.  
  83.         print('-------------------------------------------------------------------------------------------------------')
  84.  
  85.     def remove(self, uri):
  86.         """ Remove entree from cache.
  87.        Removes an entree from the cache if it exists.
  88.        :param uri:
  89.            uri (str): URI that points to the entree to remove.
  90.        :return:
  91.            Nothing.
  92.        """
  93.         uri = uri.lstrip('/')
  94.         if self.exists(uri):
  95.             node = self.get('/'.join(uri.split('/')[:-1]))
  96.             del node[uri.split('/')[-1]]
  97.  
  98.     def exists(self, uri):
  99.         """ Test if URI exists in the cache.
  100.  
  101.        :param uri:
  102.        :return:
  103.        """
  104.         return True if self.get(uri) else False
  105.  
  106.  
  107. c = cache = Cache(**cfg)
  108.  
  109. print(c.get('level_1/level_2/item2'))
  110.  
  111. c.set('level_1/level_2/more_cfg', 100)
  112.  
  113. if c.exists('level_1/level_2/more_cfg'):
  114.     print(c.get('level_1/level_2/more_cfg'))
  115.  
  116. c.dump()
  117.  
  118. if c.exists('level_1/level_2/item1'):
  119.     c.remove('level_1/level_2/item1')
  120.     c.dump()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement