summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBob Ippolito <bob@redivi.com>2012-02-27 11:58:44 -0800
committerBob Ippolito <bob@redivi.com>2012-02-27 11:58:44 -0800
commit51744f7fa9aed5b29eabfd5598a9272c76d4879d (patch)
treed2f5fbb83d5aee8a7c480cdd6458791b81079bf9
parent9b69bb2834e41005c2e7fc8ad7ce3a0d8fecdbd9 (diff)
parent7eac6360ba65050769aae8881a00c6b84eecb5c3 (diff)
downloadsimplejson-51744f7fa9aed5b29eabfd5598a9272c76d4879d.tar.gz
Merge pull request #29 from kini/indent-eafp
Allow unknown numerical types for indent parameter
-rw-r--r--simplejson/encoder.py6
-rw-r--r--simplejson/tests/test_dump.py42
2 files changed, 45 insertions, 3 deletions
diff --git a/simplejson/encoder.py b/simplejson/encoder.py
index 8a26141..74719d2 100644
--- a/simplejson/encoder.py
+++ b/simplejson/encoder.py
@@ -170,8 +170,10 @@ class JSONEncoder(object):
self.use_decimal = use_decimal
self.namedtuple_as_object = namedtuple_as_object
self.tuple_as_array = tuple_as_array
- if isinstance(indent, (int, long)):
- indent = ' ' * indent
+ try:
+ indent = indent * ' '
+ except TypeError:
+ pass
self.indent = indent
if separators is not None:
self.item_separator, self.key_separator = separators
diff --git a/simplejson/tests/test_dump.py b/simplejson/tests/test_dump.py
index 8b34004..eab040c 100644
--- a/simplejson/tests/test_dump.py
+++ b/simplejson/tests/test_dump.py
@@ -24,4 +24,44 @@ class TestDump(TestCase):
# http://bugs.python.org/issue6105
items = [('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5)]
s = json.dumps(json.OrderedDict(items))
- self.assertEqual(s, '{"one": 1, "two": 2, "three": 3, "four": 4, "five": 5}') \ No newline at end of file
+ self.assertEqual(s, '{"one": 1, "two": 2, "three": 3, "four": 4, "five": 5}')
+
+ def test_indent_unknown_type_acceptance(self):
+ """
+ A test against the regression mentioned at `github issue 29`_.
+
+ The indent parameter should accept any type which pretends to be
+ an instance of int or long when it comes to being multiplied by
+ strings, even if it is not actually an int or long, for
+ backwards compatibility.
+
+ .. _github issue 29:
+ http://github.com/simplejson/simplejson/issue/29
+ """
+
+ class AwesomeInt(object):
+ """An awesome reimplementation of integers"""
+
+ def __init__(self, *args, **kwargs):
+ if len(args) > 0:
+ # [construct from literals, objects, etc.]
+ # ...
+
+ # Finally, if args[0] is an integer, store it
+ if isinstance(args[0], int):
+ self._int = args[0]
+
+ # [various methods]
+
+ def __mul__(self, other):
+ # [various ways to multiply AwesomeInt objects]
+ # ... finally, if the right-hand operand is not awesome enough,
+ # try to do a normal integer multiplication
+ if hasattr(self, '_int'):
+ return self._int * other
+ else:
+ raise NotImplementedError("To do non-awesome things with"
+ " this object, please construct it from an integer!")
+
+ s = json.dumps(range(3), indent=AwesomeInt(3))
+ self.assertEqual(s, '[\n 0,\n 1,\n 2\n]')