Skip to content

Commit fd552cc

Browse files
authored
Merge pull request #22 from tosky/store-line-number
Expose the line number in the parsed content
2 parents 834465e + 947437a commit fd552cc

File tree

2 files changed

+17
-5
lines changed

2 files changed

+17
-5
lines changed

iniparse/ini.py

+8-1
Original file line numberDiff line numberDiff line change
@@ -282,10 +282,15 @@ def set_value(self, data):
282282
else:
283283
self.add(EmptyLine())
284284

285+
def get_line_number(self):
286+
return self.contents[0].line_number if self.contents else None
287+
285288
name = property(get_name, set_name)
286289

287290
value = property(get_value, set_value)
288291

292+
line_number = property(get_line_number)
293+
289294
def __str__(self):
290295
s = [x.__str__() for x in self.contents]
291296
return '\n'.join(s)
@@ -568,7 +573,6 @@ def _readfp(self, fp):
568573

569574
line_obj = self._parse(line)
570575
line_count += 1
571-
572576
if not cur_section and not isinstance(line_obj, (CommentLine, EmptyLine, SectionLine)):
573577
if self._parse_exc:
574578
raise MissingSectionHeaderError(fname, line_count, line)
@@ -644,6 +648,9 @@ def _readfp(self, fp):
644648
if isinstance(line_obj, EmptyLine):
645649
pending_empty_lines = True
646650

651+
if line_obj:
652+
line_obj.line_number = line_count
653+
647654
self._data.extend(pending_lines)
648655
if line and line[-1] == '\n':
649656
self._data.add(EmptyLine())

tests/test_ini.py

+9-4
Original file line numberDiff line numberDiff line change
@@ -201,10 +201,15 @@ class TestIni(unittest.TestCase):
201201
def test_basic(self):
202202
sio = StringIO(self.s1)
203203
p = ini.INIConfig(sio)
204-
self.assertEqual(str(p), self.s1)
205-
self.assertEqual(p._data.find('section1').find('but').value, 'also me')
206-
self.assertEqual(p._data.find('section1').find('help').value, 'yourself')
207-
self.assertEqual(p._data.find('section2').find('just').value, 'kidding')
204+
section1_but = p._data.find('section1').find('but')
205+
self.assertEqual(section1_but.value, 'also me')
206+
self.assertEqual(section1_but.line_number, 14)
207+
section1_help = p._data.find('section1').find('help')
208+
self.assertEqual(section1_help.value, 'yourself')
209+
self.assertEqual(section1_help.line_number, 13)
210+
section2_just = p._data.find('section2').find('just')
211+
self.assertEqual(section2_just.value, 'kidding')
212+
self.assertEqual(section2_just.line_number, 10)
208213

209214
itr = p._data.finditer('section1')
210215
v = next(itr)

0 commit comments

Comments
 (0)