Skip to content

Commit 04e4ac2

Browse files
committed
Add __str__ and __repr__ methods
1 parent 66ec8f7 commit 04e4ac2

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

jsonpointer.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,10 @@
4444
try:
4545
from itertools import izip
4646
str = unicode
47+
encode_str = lambda u: u.encode("raw_unicode_escape")
4748
except ImportError: # Python 3
4849
izip = zip
50+
encode_str = lambda u: u
4951

5052
try:
5153
from collections.abc import Mapping, Sequence
@@ -322,6 +324,12 @@ def __eq__(self, other):
322324
def __hash__(self):
323325
return hash(tuple(self.parts))
324326

327+
def __str__(self):
328+
return encode_str(self.path)
329+
330+
def __repr__(self):
331+
return "JsonPointer(" + repr(self.path) + ")"
332+
325333
@classmethod
326334
def from_parts(cls, parts):
327335
"""Constructs a JsonPointer from a list of (unescaped) paths

tests.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,50 @@ def test_round_trip(self):
7575
new_ptr = JsonPointer.from_parts(parts)
7676
self.assertEqual(ptr, new_ptr)
7777

78+
def test_str_and_repr(self):
79+
paths = [
80+
("", "", "JsonPointer({u}'')"),
81+
("/foo", "/foo", "JsonPointer({u}'/foo')"),
82+
("/foo/0", "/foo/0", "JsonPointer({u}'/foo/0')"),
83+
("/", "/", "JsonPointer({u}'/')"),
84+
("/a~1b", "/a~1b", "JsonPointer({u}'/a~1b')"),
85+
("/c%d", "/c%d", "JsonPointer({u}'/c%d')"),
86+
("/e^f", "/e^f", "JsonPointer({u}'/e^f')"),
87+
("/g|h", "/g|h", "JsonPointer({u}'/g|h')"),
88+
("/i\\j", "/i\\j", "JsonPointer({u}'/i\\\\j')"),
89+
("/k\"l", "/k\"l", "JsonPointer({u}'/k\"l')"),
90+
("/ ", "/ ", "JsonPointer({u}'/ ')"),
91+
("/m~0n", "/m~0n", "JsonPointer({u}'/m~0n')"),
92+
]
93+
for path, ptr_str, ptr_repr in paths:
94+
ptr = JsonPointer(path)
95+
self.assertEqual(path, ptr.path)
96+
97+
if sys.version_info[0] == 2:
98+
u_str = "u"
99+
else:
100+
u_str = ""
101+
self.assertEqual(ptr_str, str(ptr))
102+
self.assertEqual(ptr_repr.format(u=u_str), repr(ptr))
103+
104+
if sys.version_info[0] == 2:
105+
path = "/\xee"
106+
ptr_str = b"/\xee"
107+
ptr_repr = "JsonPointer(u'/\\xee')"
108+
else:
109+
path = "/\xee"
110+
ptr_str = "/\xee"
111+
ptr_repr = "JsonPointer('/\xee')"
112+
ptr = JsonPointer(path)
113+
self.assertEqual(path, ptr.path)
114+
115+
self.assertEqual(ptr_str, str(ptr))
116+
self.assertEqual(ptr_repr, repr(ptr))
117+
118+
# should not be unicode in Python 2
119+
self.assertIsInstance(str(ptr), str)
120+
self.assertIsInstance(repr(ptr), str)
121+
78122
def test_parts(self):
79123
paths = [
80124
("", []),

0 commit comments

Comments
 (0)