Skip to content

Commit 807eb9c

Browse files
committed
Added most_specific method to Subdivisions
This method throws a ValueError exception if the object does not contain any Subdivision objects
1 parent fa90dd6 commit 807eb9c

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

geoip2/records.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,18 @@ def __new__(cls, languages, *subdivisions):
210210
subdivisions = [Subdivision(languages, **x) for x in subdivisions]
211211
return super(cls, Subdivisions).__new__(cls, subdivisions)
212212

213+
def most_specific(self):
214+
"""The most specific subdivision available
215+
216+
:returns: The most specific (smallest) :py:class:`Subdivision`
217+
:raises: :py:exc:`ValueError` if :py:class:`Subdivisions` does
218+
not contain any :py:class:`Subdivision` objects
219+
220+
"""
221+
try:
222+
return self[-1]
223+
except IndexError:
224+
raise ValueError('No subdivisions are available');
213225

214226
class Traits(Record):
215227
""" Contains data for the traits record associated with an IP address

tests/models_test.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,8 @@ def test_omni_full(self):
102102
{'en': 'Minnesota'}, 'div 1 names are correct')
103103
self.assertEqual(model.subdivisions[1].name, 'Hennepin',
104104
'div 2 has correct name')
105+
self.assertEqual(model.subdivisions.most_specific().iso_code, 'HP',
106+
'subdivisions.most_specific returns HP')
105107

106108
def test_omni_min(self):
107109
model = geoip2.models.Omni({'traits': {'ip_address': '5.6.7.8'}})
@@ -120,6 +122,9 @@ def test_omni_min(self):
120122
'geoip2.records.Location object')
121123
self.assertEqual(type(model.traits), geoip2.records.Traits,
122124
'geoip2.records.Traits object')
125+
with self.assertRaisesRegex(ValueError,
126+
'No subdivisions are available'):
127+
model.subdivisions.most_specific()
123128

124129
def test_city_full(self):
125130
raw = {

0 commit comments

Comments
 (0)