]> asedeno.scripts.mit.edu Git - bluechips.git/blobdiff - bluechips/model/types.py
fixed some issues resulting from upgrading sqlalchemy, made more ORM-y
[bluechips.git] / bluechips / model / types.py
index 4de0033c3a2b8b86c7256210b8f13ef655382567..d4454813bd7e5463fc513518359b755b53abd25f 100644 (file)
@@ -5,16 +5,29 @@ Define special types used in BlueChips
 import sqlalchemy as sa
 from bluechips.lib.subclass import SmartSubclass
 
+from weakref import WeakValueDictionary
+
 class Currency(object):
     """
     Store currency values as an integral number of cents
     """
     __metaclass__ = SmartSubclass(int)
-    def __init__(self, value):
-        if isinstance(value, str):
-            self.value = int(float(value) * 100)
+    __old_values__ = WeakValueDictionary()
+    def __new__(cls, value):
+        if value is None:
+            value = 0
+        elif isinstance(value, str):
+            value = int(float(value) * 100)
+        else:
+            value = int(value)
+        
+        if value not in cls.__old_values__:
+            new_object = super(cls, cls).__new__(cls)
+            new_object.value = value
+            cls.__old_values__[value] = new_object
+            return new_object
         else:
-            self.value = int(value)
+            return cls.__old_values__[value]
     
     def __int__(self):
         """
@@ -62,7 +75,7 @@ class Currency(object):
         """
         Get to the formatted string without the dollar sign
         """
-        return str(self)[1:]
+        return str(self).replace('$', '')
     
     def __repr__(self):
         return '%s("%s")' % (self.__class__.__name__, str(self))
@@ -70,7 +83,7 @@ class Currency(object):
         sign = '-' if self.value < 0 else ''
         cents = abs(self.value) % 100
         dollars = (abs(self.value) - cents) / 100
-        return '$%s%s.%.02d' % (sign, dollars, cents)
+        return '%s$%s.%.02d' % (sign, dollars, cents)
 
 class DBCurrency(sa.types.TypeDecorator):
     """
@@ -86,3 +99,4 @@ class DBCurrency(sa.types.TypeDecorator):
     
     def convert_result_value(self, value, engine):
         return Currency(value)
+    process_result_value = convert_result_value