Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow unknown numerical types for indent parameter #29

Merged
merged 2 commits into from Feb 27, 2012
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 4 additions & 2 deletions simplejson/encoder.py
Expand Up @@ -170,8 +170,10 @@ def __init__(self, skipkeys=False, ensure_ascii=True,
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
Expand Down
42 changes: 41 additions & 1 deletion simplejson/tests/test_dump.py
Expand Up @@ -24,4 +24,44 @@ def test_ordered_dict(self):
# 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}')
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]')