Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Documented Dicts

  • Loading branch information...
commit b84d19fe074885c7f405b6f543dacbd274f0912f 1 parent c82ee5d
Ask Solem authored
View
123 README.rst
@@ -97,7 +97,7 @@ Python dictionaries; It raises the KeyError exception::
Set many keys at the same time::
- >>> db.update({"name": "George Constanza",
+ >>> db.update({"name": "George Costanza",
... "company": "Vandelay Industries"})
Get a list of keys in the database::
@@ -121,12 +121,15 @@ Get all items in the database (optionally matching a pattern)
as a list of ``(key, value)`` tuples::
>>> db.items(pattern="user:*")
- [('user:company', 'Vandelay Industries'), ('user:name', 'George Constanza')]
+ [('user:company', 'Vandelay Industries'), ('user:name', 'George Costanza')]
Get all values in the database (optionally where keys matches a pattern)::
>>> db.values(pattern="user:*")
- ['Vandelay Industries', 'George Constanza']
+ ['Vandelay Industries', 'George Costanza']
+
+Iterator versions of ``keys``, ``values`` and ``items`` are also available,
+as ``iterkeys``, ``itervalues``, ``iteritems`` respectively.
Check for existence of a key in the database::
@@ -140,7 +143,7 @@ Check for existence of a key in the database::
Get and remove key from the database (atomic operation)::
>>> db.pop("user:name")
- 'George Constanza'
+ 'George Costanza'
>>> "user:name" in db
False
@@ -163,13 +166,13 @@ Get items in the list as a Python ``list``::
>>> list(l)
['Jerry', 'George']
-Add item at the end of the list::
+``append`` adds items to the end of the list::
>>> l.append("Kramer")
>>> list(l)
['Jerry', 'George', 'Kramer']
-Add item to the head of the list::
+``appendleft`` prepends item to the head of the list::
>>> l.appendleft("Elaine")
>>> list(l)
@@ -248,6 +251,114 @@ list::
>>> list(l)
['George', 'Elaine']
+
+Dicts (Hashes)
+==============
+
+
+Create a new dictionary with initial content::
+
+ >>> d = db.Dict("mydict", {"name": "George Louis Costanza"})
+
+Get the value of key ``"name"``::
+
+ >>> d["name"]
+ 'George Louis Costanza'
+
+Set store another key, ``"company"``::
+
+ >>> d["company"] = "Vandelay Industries"
+
+Check if a key exists in the dictionary, using the ``in`` operator::
+
+ >>> "company" in d
+ True
+
+Remove a key::
+
+ >>> del(d["company"])
+ >>> "company" in d
+ False
+
+Get a copy as a Python ``dict``::
+
+ >>> dict(d)
+ {'name': 'George Louis Costanza'}
+
+
+``update`` updates with the contents of a ``dict``
+(``x.update(y)`` does a merge where keys in ``y`` has precedence)::
+
+ >>> d.update({"mother": "Estelle Costanza",
+ ... "father": "Frank Costanza"})
+
+ >>> dict(d)
+ {'name': 'George Louis Costanza',
+ 'mother': 'Estelle Costanza',
+ 'father': 'Frank Costanza'}
+
+
+Get the number of keys in the dictionary::
+
+ >>> len(d)
+ 3
+
+``keys`` / ``iterkeys`` gives a list of the keys in the dictionary::
+
+ >>> d.keys()
+ ['name', 'father', 'mother']
+
+``values`` / ``itervalues`` gives a list of values in the dictionary::
+
+ >>> d.values()
+ ['George Louis Costanza', 'Frank Costanza', 'Estelle Costanza']
+
+``items`` / ``iteritems`` gives a list of ``(key, value)`` tuples
+of the items in the dictionary::
+
+ >>> d.items()
+ [('father', 'Frank Costanza'),
+ ('name', 'George Louis Costanza'),
+ ('mother', 'Estelle Costanza')]
+
+``setdefault`` returns the value of a key if present, otherwise stores a
+default value::
+
+ >>> d.setdefault("company", "Vandelay Industries")
+ 'Vandelay Industries'
+ >>> d["company"] = "New York Yankees"
+ >>> d.setdefault("company", "Vandelay Industries")
+ 'New York Yankees'
+
+``get(key, default=None)`` returns the value of a key if present, otherwise
+returns the default value::
+
+ >>> d.get("company")
+ "Vandelay Industries"
+
+ >>> d.get("address")
+ None
+
+``pop`` removes a key and returns its value. Also supports an extra
+parameters, which is the default value to return if the key does not exist::
+
+ >>> d.pop("company")
+ 'New York Yankees'
+ >>> d.pop("company")
+ Traceback (most recent call last):
+ File "<stdin>", line 1, in <module>
+ File "redish/types.py", line 373, in pop
+ val = self[key]
+ File "redish/types.py", line 290, in __getitem__
+ raise KeyError(key)
+ KeyError: 'company'
+
+ # With default value, does not raise KeyError, but returns default value.
+ >>> d.pop("company", None)
+ None
+
+
+
Sets
====
View
4 redish/tests/test_client.py
@@ -124,9 +124,9 @@ def test_pop(self):
self.client.pop("test:pop")
def test_get(self):
- self.client["test:get:exists"] = "George Constanza"
+ self.client["test:get:exists"] = "George Costanza"
self.assertEqual(self.client.get("test:get:exists"),
- "George Constanza")
+ "George Costanza")
self.assertIsNone(self.client.get("test:get:nonexistent"))
self.assertEqual(self.client.get("test:get:nonexistent", 12345),
12345)
View
19 redish/tests/test_types.py
@@ -8,7 +8,7 @@
class test_List(ClientTestCase):
def test_get_set_item(self):
- names = ("George Constanza", "Jerry Seinfeld",
+ names = ("George Costanza", "Jerry Seinfeld",
"Kosmo Kramer", "Elaine Marie Benes")
l = self.client.List("test:List:get_set_item", names)
for i, name in enumerate(names):
@@ -314,10 +314,10 @@ def test_range_by_score(self):
class test_Dict(ClientTestCase):
def test__init__(self):
- data = {"name": "George Constanza"}
+ data = {"name": "George Costanza"}
d = self.client.Dict("test:Dict:__init__", data,
company="Vandelay Industries")
- self.assertEqual(d["name"], "George Constanza")
+ self.assertEqual(d["name"], "George Costanza")
self.assertEqual(d["company"], "Vandelay Industries")
def test__missing__(self):
@@ -399,16 +399,23 @@ def test_setdefault(self):
def test_pop(self):
d = self.client.Dict("test:Dict:pop", foo="bar")
- self.assertIsNone(d.pop("nonexistent"))
+ self.assertIsNone(d.pop("nonexistent", None))
+ self.assertIsNone(d.pop("nonexistent", default=None))
self.assertEqual(d.pop("nonexistent", "12345"), "12345")
+ self.assertEqual(d.pop("nonexistent", default="12345"), "12345")
+
+ with self.assertRaises(KeyError):
+ d.pop("nonexistent")
+
self.assertEqual(d.pop("foo"), "bar")
- self.assertIsNone(d.pop("foo"))
+ with self.assertRaises(KeyError):
+ d.pop("foo")
with self.assertRaises(KeyError):
d["foo"]
def test_update(self):
- data1 = {"George Constanza": "architect",
+ data1 = {"George Costanza": "architect",
"Jerry Seinfeld": "comedian"}
data2 = {"Elaine Marie Benes": "assistant"}
d = self.client.Dict("test:Dict:update", data2)
View
14 redish/types.py
@@ -186,7 +186,7 @@ def intersection_update(self, other):
"""Update the set with the intersection of itself and another."""
return self.client.sinterstore(self.name, [self.name, other.name])
- def difference(self, others):
+ def difference(self, *others):
"""Return the difference of two or more sets as a new :class:`set`.
(i.e. all elements that are in this set but not the others.)
@@ -362,17 +362,21 @@ def setdefault(self, key, default=None):
self[key] = default
return default
- def pop(self, key, default=None):
+ def pop(self, key, *args, **kwargs):
"""Remove specified key and return the corresponding value.
- If key is not found, ``default`` is returned if given,
- otherwise :exc:`KeyError` is raised.
+ :keyword default: If key is not found, ``default`` is returned if given,
+ otherwise :exc:`KeyError` is raised.
"""
try:
val = self[key]
except KeyError:
- val = default
+ if len(args):
+ return args[0]
+ if "default" in kwargs:
+ return kwargs["default"]
+ raise
try:
del(self[key])
Please sign in to comment.
Something went wrong with that request. Please try again.