fork download
  1. class UnpairedException(Exception):
  2. pass
  3.  
  4.  
  5. class PairedConnections(dict):
  6. def __init__(self, *args, **kwargs):
  7. self.waiting = set() # сдесь хранятся соединения "в состоянии ожидания"
  8. super().__init__(*args, **kwargs)
  9.  
  10. def __delitem__(self, key):
  11. paired_key = self[key]
  12. if paired_key is not None:
  13. try:
  14. super().__delitem__(paired_key)
  15. except KeyError as e:
  16. raise UnpairedException(f"Paired key {paired_key} not found")
  17. else:
  18. self.waiting.remove(key)
  19. super().__delitem__(key)
  20.  
  21. def __setitem__(self, key, value):
  22. if value is not None:
  23. try:
  24. self[value]
  25. except KeyError as e:
  26. raise UnpairedException(f"Connection {key}-{value} not paired")
  27. super().__setitem__(value, key)
  28. self.waiting.remove(key)
  29. self.waiting.remove(value)
  30. else:
  31. self.waiting.add(key)
  32. super().__setitem__(key, value)
  33.  
  34. # тест
  35. if __name__ == "__main__":
  36. conns = PairedConnections()
  37. conns['one'] = None
  38. conns['two'] = None
  39. conns['three'] = None
  40. print('1:', conns)
  41. print('\t', conns.waiting)
  42. conns['two'] = 'one'
  43. print('2:', conns)
  44. print('\t', conns.waiting)
  45. del conns['one']
  46. print('3:', conns)
  47. print('\t', conns.waiting)
  48. del conns['three']
  49. print('4:', conns)
  50. print('\t', conns.waiting)
  51. # по идее ошибок возникать не должно
Success #stdin #stdout 0.02s 9228KB
stdin
Standard input is empty
stdout
1: {'one': None, 'two': None, 'three': None}
	 {'one', 'two', 'three'}
2: {'one': 'two', 'two': 'one', 'three': None}
	 {'three'}
3: {'three': None}
	 {'three'}
4: {}
	 set()