[tor-commits] [stem/master] Adding a hash method to our Version class

atagar at torproject.org atagar at torproject.org
Wed Oct 2 14:36:26 UTC 2013


commit bcd849f0cbf3e5a823049dcea51f9158baf897b9
Author: Damian Johnson <atagar at torproject.org>
Date:   Wed Oct 2 07:32:11 2013 -0700

    Adding a hash method to our Version class
    
    Our Version class lacked a __hash__() method, causing it to behave
    unintuitively in dictionaries and sets...
    
      >>> from stem.version import Version
      >>> foo = set([Version('0.2.4.9-alpha')])
      >>> bar = set([Version('0.2.4.9-alpha')])
      >>> foo.difference(bar)
      set([<stem.version.Version object at 0xb71fae0c>])
    
    This is because python opts for the object's identity when a hash method does
    not exist.
---
 stem/version.py |   13 +++++++++++++
 1 file changed, 13 insertions(+)

diff --git a/stem/version.py b/stem/version.py
index 3630611..b529f86 100644
--- a/stem/version.py
+++ b/stem/version.py
@@ -236,6 +236,19 @@ class Version(object):
 
     return self._compare(other, lambda s, o: s >= o)
 
+  def __hash__(self):
+    my_hash = 0
+
+    for attr in ("major", "minor", "micro", "patch", "status"):
+      my_hash *= 1024
+
+      attr_value = getattr(self, attr)
+
+      if attr_value is not None:
+        my_hash += hash(attr_value)
+
+    return my_hash
+
 
 class _VersionRequirements(object):
   """



More information about the tor-commits mailing list