Skip to content

Commit bd0c2d1

Browse files
committed
modernize code for str and repr functions
Use format strings where possible and use setattr() instead of assigning the functions. Amend the test to check for the actual outcome of the str/repr functions.
1 parent 6e1443d commit bd0c2d1

File tree

4 files changed

+73
-60
lines changed

4 files changed

+73
-60
lines changed

src/osmium/osm/__init__.py

Lines changed: 43 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,9 @@ def create_mutable_relation(rel, **args):
2626
Way.replace = create_mutable_way
2727
Relation.replace = create_mutable_relation
2828

29-
def _make_repr(attr_list):
29+
def _make_repr(*attr_list):
3030
fmt_string = 'osmium.osm.{0}('\
31-
+ ', '.join(['{0}={{1.{0}!r}}'.format(x) for x in attr_list])\
31+
+ ', '.join([f'{x}={{1.{x}!r}}' for x in attr_list])\
3232
+ ')'
3333

3434
return lambda o: fmt_string.format(o.__class__.__name__, o)
@@ -43,55 +43,56 @@ def _list_elipse(obj):
4343
objects = objects[:47] + '...'
4444
return objects
4545

46-
Location.__repr__ = lambda l: 'osmium.osm.Location(x={0.x!r}, y={0.y!r})'.format(l) \
47-
if l.valid() else 'osmium.osm.Location()'
48-
Location.__str__ = lambda l: '{:f}/{:f}'.format(l.lon_without_check(),
49-
l.lat_without_check()) \
50-
if l.valid() else 'invalid'
46+
setattr(Location, '__repr__',
47+
lambda l: f'osmium.osm.Location(x={l.x!r}, y={l.y!r})'
48+
if l.valid() else 'osmium.osm.Location()')
49+
setattr(Location, '__str__',
50+
lambda l: f'{l.lon_without_check():.7f}/{l.lat_without_check():.7f}'
51+
if l.valid() else 'invalid')
5152

52-
Box.__repr__ = _make_repr(['bottom_left', 'top_right'])
53-
Box.__str__ = lambda b: '({0.bottom_left!s} {0.top_right!s})'.format(b)
53+
setattr(Box, '__repr__', _make_repr('bottom_left', 'top_right'))
54+
setattr(Box, '__str__', lambda b: f'({b.bottom_left!s} {b.top_right!s})')
5455

55-
Tag.__repr__ = _make_repr(['k', 'v'])
56-
Tag.__str__ = lambda t: '{0.k}={0.v}'.format(t)
56+
setattr(Tag, '__repr__', _make_repr('k', 'v'))
57+
setattr(Tag, '__str__', lambda t: f'{t.k}={t.v}')
5758

58-
TagList.__repr__ = lambda t: "osmium.osm.TagList({%s})" \
59-
% ', '.join(["%r: %r" % (i.k, i.v) for i in t])
60-
TagList.__str__ = lambda t: '{' + _list_elipse(t) + '}'
59+
setattr(TagList, '__repr__', lambda t: "osmium.osm.TagList({%s})"
60+
% ', '.join([f"{i.k!r}: {i.v!r}" for i in t]))
61+
setattr(TagList, '__str__', lambda t: f'{{{_list_elipse(t)}}}')
6162

62-
NodeRef.__repr__ = _make_repr(['ref', 'location'])
63-
NodeRef.__str__ = lambda n: '{0.ref:d}@{0.location!s}'.format(n) \
64-
if n.location.valid() else str(n.ref)
63+
setattr(NodeRef, '__repr__', _make_repr('ref', 'location'))
64+
setattr(NodeRef, '__str__', lambda n: f'{n.ref:d}@{n.location!s}'
65+
if n.location.valid() else str(n.ref))
6566

66-
NodeRefList.__repr__ = _list_repr
67-
NodeRefList.__str__ = lambda o: '[' + _list_elipse(o) + ']'
67+
setattr(NodeRefList, '__repr__', _list_repr)
68+
setattr(NodeRefList, '__str__', lambda o: f'[{_list_elipse(o)}]')
6869

69-
RelationMember.__repr__ = _make_repr(['ref', 'type', 'role'])
70-
RelationMember.__str__ = lambda r: ('{0.type}{0.ref:d}@{0.role}' \
71-
if r.role else '{0.type}{0.ref:d}').format(r)
70+
setattr(RelationMember, '__repr__', _make_repr('ref', 'type', 'role'))
71+
setattr(RelationMember, '__str__', lambda r: f'{r.type}{r.ref:d}@{r.role}' \
72+
if r.role else f'{r.type}{r.ref:d}')
7273

73-
RelationMemberList.__repr__ = _list_repr
74-
RelationMemberList.__str__ = lambda o: '[' + _list_elipse(o) + ']'
74+
setattr(RelationMemberList, '__repr__', _list_repr)
75+
setattr(RelationMemberList, '__str__', lambda o: f'[{_list_elipse(o)}]')
7576

76-
OSMObject.__repr__ = _make_repr(['id', 'deleted', 'visible', 'version', 'changeset',
77-
'uid', 'timestamp', 'user', 'tags'])
77+
setattr(OSMObject, '__repr__', _make_repr('id', 'deleted', 'visible', 'version',
78+
'changeset', 'uid', 'timestamp', 'user',
79+
'tags'))
7880

79-
Node.__repr__ = _make_repr(['id', 'deleted', 'visible', 'version', 'changeset',
80-
'uid', 'timestamp', 'user', 'tags', 'location'])
81-
Node.__str__ = lambda n: 'n{0.id:d}: location={0.location!s} tags={0.tags!s}'\
82-
.format(n)
81+
setattr(Node, '__repr__', _make_repr('id', 'deleted', 'visible', 'version',
82+
'changeset', 'uid', 'timestamp', 'user',
83+
'tags', 'location'))
84+
setattr(Node, '__str__', lambda n: f'n{n.id:d}: location={n.location!s} tags={n.tags!s}')
8385

84-
Way.__repr__ = _make_repr(['id', 'deleted', 'visible', 'version', 'changeset',
85-
'uid', 'timestamp', 'user', 'tags', 'nodes'])
86-
Way.__str__ = lambda o: 'w{0.id:d}: nodes={0.nodes!s} tags={0.tags!s}' \
87-
.format(o)
86+
setattr(Way, '__repr__', _make_repr('id', 'deleted', 'visible', 'version', 'changeset',
87+
'uid', 'timestamp', 'user', 'tags', 'nodes'))
88+
setattr(Way, '__str__', lambda o: f'w{o.id:d}: nodes={o.nodes!s} tags={o.tags!s}')
8889

89-
Relation.__repr__ = _make_repr(['id', 'deleted', 'visible', 'version', 'changeset',
90-
'uid', 'timestamp', 'user', 'tags', 'members'])
91-
Relation.__str__ = lambda o: 'r{0.id:d}: members={0.members!s}, tags={0.tags!s}' \
92-
.format(o)
90+
setattr(Relation, '__repr__', _make_repr('id', 'deleted', 'visible', 'version',
91+
'changeset', 'uid', 'timestamp', 'user',
92+
'tags', 'members'))
93+
setattr(Relation, '__str__', lambda o: f'r{o.id:d}: members={o.members!s}, tags={o.tags!s}')
9394

94-
Changeset.__repr__ = _make_repr(['id', 'uid', 'created_at', 'closed_at', 'open',
95-
'num_changes', 'bounds', 'user', 'tags'])
96-
Changeset.__str__ = lambda o: 'c{0.id:d}: closed_at={0.closed_at!s}, bounds={0.bounds!s}, tags={0.tags!s}' \
97-
.format(o)
95+
setattr(Changeset, '__repr__', _make_repr('id', 'uid', 'created_at', 'closed_at',
96+
'open', 'num_changes', 'bounds', 'user',
97+
'tags'))
98+
setattr(Changeset, '__str__', lambda o: f'c{o.id:d}: closed_at={o.closed_at!s}, bounds={o.bounds!s}, tags={o.tags!s}')

test/helpers.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,6 @@
77
def mkdate(*args):
88
return datetime(*args, tzinfo=timezone.utc)
99

10-
def check_repr(o):
11-
return not str(o).startswith('<') and not repr(o).startswith('<')
12-
1310
class CountingHandler(osmium.SimpleHandler):
1411

1512
def __init__(self):

test/test_osm.py

Lines changed: 26 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,11 @@
33
# This file is part of Pyosmium.
44
#
55
# Copyright (C) 2022 Sarah Hoffmann.
6+
import re
67
from itertools import count
78
import pytest
89

9-
from helpers import check_repr, mkdate
10+
from helpers import mkdate
1011

1112
import osmium as o
1213

@@ -62,7 +63,9 @@ def area_importer(request, tmp_path, to_opl):
6263
def test_invalid_location():
6364
loc = o.osm.Location()
6465
assert not loc.valid()
65-
assert check_repr(loc)
66+
assert str(loc) == 'invalid'
67+
assert repr(loc) == 'osmium.osm.Location()'
68+
6669
with pytest.raises(o.InvalidLocationError):
6770
lat = loc.lat
6871
with pytest.raises(o.InvalidLocationError):
@@ -73,12 +76,13 @@ def test_invalid_location():
7376

7477

7578
def test_valid_location():
76-
loc = o.osm.Location(1,10)
77-
assert loc.lon == pytest.approx(1)
79+
loc = o.osm.Location(-1, 10)
80+
assert loc.lon == pytest.approx(-1)
7881
assert loc.lat == pytest.approx(10)
79-
assert loc.x == 10000000
82+
assert loc.x == -10000000
8083
assert loc.y == 100000000
81-
assert check_repr(loc)
84+
assert re.fullmatch('-1.0*/10.0*', str(loc))
85+
assert repr(loc) == 'osmium.osm.Location(x=-10000000, y=100000000)'
8286

8387

8488
def test_node_attributes(test_importer):
@@ -92,7 +96,8 @@ def node(n):
9296
assert n.timestamp == mkdate(2014, 1, 31, 6, 23, 35)
9397
assert n.user == u'änonymous'
9498
assert n.positive_id() == 1
95-
assert check_repr(n)
99+
assert str(n) == 'n1: location=invalid tags={}'
100+
assert repr(n) == "osmium.osm.Node(id=1, deleted=False, visible=True, version=5, changeset=58674, uid=42, timestamp=datetime.datetime(2014, 1, 31, 6, 23, 35, tzinfo=datetime.timezone.utc), user='änonymous', tags=osmium.osm.TagList({}), location=osmium.osm.Location())"
96101

97102
assert 1 == test_importer('n1 v5 c58674 t2014-01-31T06:23:35Z i42 uänonymous',
98103
node=node)
@@ -125,8 +130,12 @@ def way(o):
125130
assert not o.is_closed()
126131
assert not o.ends_have_same_id()
127132
assert not o.ends_have_same_location()
128-
assert check_repr(o)
129-
assert check_repr(o.nodes)
133+
134+
assert str(o) == 'w1: nodes=[[email protected]/0.0000000,2,[email protected]/1.0000000] tags={}'
135+
assert repr(o) == "osmium.osm.Way(id=1, deleted=False, visible=True, version=5, changeset=58674, uid=42, timestamp=datetime.datetime(2014, 1, 31, 6, 23, 35, tzinfo=datetime.timezone.utc), user='anonymous', tags=osmium.osm.TagList({}), nodes=osmium.osm.WayNodeList([osmium.osm.NodeRef(ref=1, location=osmium.osm.Location(x=0, y=0)), osmium.osm.NodeRef(ref=2, location=osmium.osm.Location()), osmium.osm.NodeRef(ref=3, location=osmium.osm.Location(x=10000000, y=10000000))]))"
136+
137+
assert str(o.nodes) == '[[email protected]/0.0000000,2,[email protected]/1.0000000]'
138+
assert repr(o.nodes) == "osmium.osm.WayNodeList([osmium.osm.NodeRef(ref=1, location=osmium.osm.Location(x=0, y=0)), osmium.osm.NodeRef(ref=2, location=osmium.osm.Location()), osmium.osm.NodeRef(ref=3, location=osmium.osm.Location(x=10000000, y=10000000))])"
130139

131140
assert 1 == test_importer(['n1 x0 y0', 'n3 x1 y1',
132141
'w1 v5 c58674 t2014-01-31T06:23:35Z i42 uanonymous Nn1,n2,n3'],
@@ -145,8 +154,12 @@ def relation(o):
145154
assert o.timestamp == mkdate(2014, 1, 31, 6, 23, 35)
146155
assert o.user == ' anonymous'
147156
assert o.positive_id() == 1
148-
assert check_repr(o)
149-
assert check_repr(o.members)
157+
158+
assert str(o) == 'r1: members=[w1], tags={}'
159+
assert repr(o) == "osmium.osm.Relation(id=1, deleted=False, visible=True, version=5, changeset=58674, uid=42, timestamp=datetime.datetime(2014, 1, 31, 6, 23, 35, tzinfo=datetime.timezone.utc), user=' anonymous', tags=osmium.osm.TagList({}), members=osmium.osm.RelationMemberList([osmium.osm.RelationMember(ref=1, type='w', role='')]))"
160+
161+
assert str(o.members) == '[w1]'
162+
assert repr(o.members) == "osmium.osm.RelationMemberList([osmium.osm.RelationMember(ref=1, type='w', role='')])"
150163

151164
assert 1 == test_importer('r1 v5 c58674 t2014-01-31T06:23:35Z i42 u%20%anonymous Mw1@',
152165
relation=relation)
@@ -230,7 +243,8 @@ def changeset(c):
230243
assert 515288620 == c.bounds.top_right.y
231244
assert -1465242 == c.bounds.bottom_left.x
232245
assert 515288506 == c.bounds.bottom_left.y
233-
assert check_repr(c)
246+
assert str(c) == 'c34: closed_at=2005-04-09 20:54:39+00:00, bounds=(-0.1465242/51.5288506 -0.1464925/51.5288620), tags={}'
247+
assert repr(c) == "osmium.osm.Changeset(id=34, uid=1, created_at=datetime.datetime(2005, 4, 9, 19, 54, 13, tzinfo=datetime.timezone.utc), closed_at=datetime.datetime(2005, 4, 9, 20, 54, 39, tzinfo=datetime.timezone.utc), open=False, num_changes=2, bounds=osmium.osm.Box(bottom_left=osmium.osm.Location(x=-1465242, y=515288506), top_right=osmium.osm.Location(x=-1464925, y=515288620)), user='Steve', tags=osmium.osm.TagList({}))"
234248

235249
assert 1 == area_importer('c34 k2 s2005-04-09T19:54:13Z e2005-04-09T20:54:39Z '
236250
'd34 i1 uSteve x-0.1465242 y51.5288506 X-0.1464925 Y51.5288620',

test/test_taglist.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,6 @@
55
# Copyright (C) 2022 Sarah Hoffmann.
66
import pytest
77

8-
from helpers import check_repr
9-
108
import osmium as o
119

1210
@pytest.fixture
@@ -19,7 +17,6 @@ def node(n):
1917
del tags[None]
2018
tags.update(n.tags)
2119
tests(n)
22-
assert check_repr(n.tags)
2320

2421
simple_handler(data, node=node)
2522

@@ -32,6 +29,8 @@ def test_empty_taglist_length(tag_handler):
3229
def tests(n):
3330
assert 0 == len(n.tags)
3431
assert not n.tags
32+
assert str(n.tags) == '{}'
33+
assert repr(n.tags) == 'osmium.osm.TagList({})'
3534

3635
tags = tag_handler("n234 x1 y2", tests)
3736
assert tags == {}
@@ -91,6 +90,8 @@ def tests(n):
9190
assert "x" not in n.tags
9291
assert None not in n.tags
9392
assert "" not in n.tags
93+
assert str(n.tags) == '{abba=x,2=vvv,xx=abba}'
94+
assert repr(n.tags) == "osmium.osm.TagList({'abba': 'x', '2': 'vvv', 'xx': 'abba'})"
9495

9596
tags = tag_handler("n234 Tabba=x,2=vvv,xx=abba", tests)
9697

0 commit comments

Comments
 (0)