summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorLaurent Bachelier <laurent@bachelier.name>2011-12-21 12:43:15 +0100
committerLaurent Bachelier <laurent@bachelier.name>2011-12-21 12:43:15 +0100
commita87016605e8b512410d6398dcaa89e5d857147b1 (patch)
tree6b9791139e79288a658cd261b279b60107ebdf12
parentTest for custom type handling (diff)
downloadffs-a87016605e8b512410d6398dcaa89e5d857147b1.tar.xz
Move the encode to/decode from strings in separate methods
Since they are starting to grow.
-rw-r--r--ffs.py43
1 files changed, 24 insertions, 19 deletions
diff --git a/ffs.py b/ffs.py
index f420473..e8c2e47 100644
--- a/ffs.py
+++ b/ffs.py
@@ -44,14 +44,17 @@ class Dict(MutableMapping):
else:
with open(self._get_path(key), 'rb') as f:
data = f.read()
- # it's already the class
- if isinstance(data, cls):
- return data
- # lots of classes seem to have this method
- if hasattr(cls, 'fromstring'):
- return cls.fromstring(data)
- # works for int, for instance
- return cls(data)
+ return self._decode(data, cls)
+
+ def _decode(self, data, cls):
+ # it's already the class
+ if isinstance(data, cls):
+ return data
+ # lots of classes seem to have this method
+ if hasattr(cls, 'fromstring'):
+ return cls.fromstring(data)
+ # works for int, for instance
+ return cls(data)
def _get_cls(self, key):
cls = self.router.route(key)
@@ -86,20 +89,22 @@ class Dict(MutableMapping):
else:
if not isinstance(value, cls):
raise ValueError("%s is not a %s." % (repr(value), cls.__name__))
- # lots of classes have this method. usually does not lose information
- if hasattr(cls, 'tostring'):
- data = value.tostring()
- # no need for conversion
- elif isinstance(value, basestring):
- data = value
- # whitelist of classes with a __str__ that do not lose information
- elif isinstance(value, (int, long)):
- data = str(value)
- else:
- raise ValueError("Unable to convert %s to a string." % repr(value))
+ data = self._encode(value, cls)
with open(self._get_path(key), 'wb') as f:
f.write(data)
+ def _encode(self, value, cls):
+ # lots of classes have this method. usually does not lose information
+ if hasattr(cls, 'tostring'):
+ return value.tostring()
+ # no need for conversion
+ if isinstance(value, basestring):
+ return value
+ # whitelist of classes with a __str__ that do not lose information
+ if isinstance(value, (int, long)):
+ return str(value)
+ raise ValueError("Unable to convert %s to a string." % repr(value))
+
def keys(self):
return [f for f in os.listdir(self.root) if self.router.route(f)]