[tor-commits] [stem/master] Making CircuitEvent sortable

atagar at torproject.org atagar at torproject.org
Wed Mar 26 16:59:02 UTC 2014


commit 4e81cb78d00d3d0b375261829b7f14a1671b0192
Author: Damian Johnson <atagar at torproject.org>
Date:   Wed Mar 26 09:42:28 2014 -0700

    Making CircuitEvent sortable
    
    Circuits should be sortable by their id. Making that the case so the following
    works...
    
      for circ in sorted(controller.get_circuits()):
        ... do stuff...
---
 stem/response/events.py |   37 +++++++++++++++++++++++++++++++++++++
 1 file changed, 37 insertions(+)

diff --git a/stem/response/events.py b/stem/response/events.py
index b0bebfb..250697d 100644
--- a/stem/response/events.py
+++ b/stem/response/events.py
@@ -373,6 +373,43 @@ class CircuitEvent(Event):
     self._log_if_unrecognized('reason', stem.CircClosureReason)
     self._log_if_unrecognized('remote_reason', stem.CircClosureReason)
 
+  def _compare(self, other, method):
+    if not isinstance(other, CircuitEvent):
+      return False
+
+    for attr in ('id', 'status', 'path', 'build_flags', 'purpose', 'hs_state', 'rend_query', 'created', 'reason', 'remote_reason'):
+      my_attr = getattr(self, attr)
+      other_attr = getattr(other, attr)
+
+      # Our id attribute is technically a string, but Tor conventionally uses
+      # ints. Attempt to handle as ints if that's the case so we get numeric
+      # ordering.
+
+      if attr == 'id' and my_attr and other_attr:
+        if my_attr.isdigit() and other_attr.isdigit():
+          my_attr = int(my_attr)
+          other_attr = int(other_attr)
+
+      if my_attr is None:
+        my_attr = ''
+
+      if other_attr is None:
+        other_attr = ''
+
+      if my_attr != other_attr:
+        return method(my_attr, other_attr)
+
+    return True
+
+  def __eq__(self, other):
+    return self._compare(other, lambda s, o: s == o)
+
+  def __gt__(self, other):
+    return self._compare(other, lambda s, o: s > o)
+
+  def __ge__(self, other):
+    return self._compare(other, lambda s, o: s >= o)
+
 
 class CircMinorEvent(Event):
   """





More information about the tor-commits mailing list