Class fields not being updated

I have a text file like this:

id = 1 foo start = 100
id = 1 foo end = 101
id = 1 bar start = 200
id = 1 bar end = 242
id = 1 baz start = 120
id = 1 baz end = 123
id = 2 foo start = 2324
id = 2 foo end = 2566

I’m parsing the file like this:

import sys

class Data:
    def __init__(self):
        self.foo_start = None
        self.foo_end = None
        self.bar_start = None
        self.bar_end = None
        self.baz_start = None
        self.baz_end = None
   def __str__(self) -> str:
        return "foo_start: {}, foo_end: {}, bar_start: {}, bar_end: {}, baz_start: {}, baz_end: {}".format(self.foo_start, self.foo_end, self.bar_start, self.bar_end, self.baz_start, self.baz_end)

cache = dict()
for line in sys.stdin:
       split_line = line.split(' ')
       id = int(split_line[2])
       time = int(split_line[5])

       if not id in cache:
          cache[id] = Data()

       data = cache[id]

       if 'start' in line:
           if 'foo' in line:
              data.foo_start = time
           if 'bar' in line:
              data.bar_start = time
           if 'baz' in line:
              data.baz_start = time
        elif 'end' in line:
           if 'foo' in line:
              data.foo_end = time
          # Continue for rest of the fields

In the end I expect each field of the Data class to be a non-None integer value. Instead, what I get is that
foo_start and foo_end values are non-None, while the rest of them are None.

I confirmed that execution is reaching the all of the statements, so I’m not sure why some values are still None.


It looks like you want data rather than self in the if blocks at the end.

Oops, a mistake. Was meant to be written as data. Fixed. The problem is exists.

In your sample text the items are separated by 1 space, and in your code it’s splitting on 1 space, so the time would be in split_line[6]:

>>> 'id = 1 foo start = 100'.split(' ')
['id', '=', '1', 'foo', 'start', '=', '100']

When I fix that and add the missing lines for the rest of the fields, I’m not seeing a problem.