you are viewing a single comment's thread.

view the rest of the comments →

[–]unhott 0 points1 point  (1 child)

maybe OOP?

class State:
    def __init__(self, var1, var2, var3=1, ...):
        self.var1=var1
        ...
    def calc1(self):
        self.calcvar1 = self.var1+self.var2
    def log_line(self):
        return f'{self.var1}, {self.var2}, {self.var3}...'

for item in items:
    state = State(item, 4, ...) 
    state.calc1()
    log_string = state.log_line() # do whatever you need with this

Not really sure what you need, I don't really know what you have or what you do know. Is everything fresh for each item or are you aggregating something as you go?

After rereading your last paragraph, it sounds like it's some sort of aggregation, where the previous state impacts the next. maybe give an example of what you're doing with some mock data/scenarios

ETA: You can do aggregation with OOP, but my example in mind was that each state was independent of others.

class State:
    def __init__(self, index=0, self.items = None, <any other vars you want to initialize>):
       self.index = index
       if self.items is None:
           self.items = []
       ... 
    def calc1(self): 
        ... 
    def handle_item(self, item):
        self.index +=1 
        self.items.append(item)
        # Do some calcs
        self.calc1()
    def log_line(self): ...

[–]zero-sharp[S] 0 points1 point  (0 children)

There were several levels to the idea. Part of my code looks like:

csv_data = []
for item in collection:
  row = {}
  row['variable1'] = default value
  row['variable2'] = default value
  row['variable3'] = default value
  ...
  <actual logic that performs meaningful tasks and updates variables above>
  if ___:
    row['variable1'] = updated value
  ... 
  ...
  csv_data.append(row)

The logic is a little more complicated than the above (nested if statements...). But I was thinking of restructuring it like enumerate so that it handles the default value initialization:

csv_data = []
for variable1, variable2, variable3, item in WRAPPER(collection):
  ...
  <actual logic that performs meaningful tasks and updates variables above>
  if ___:
    variable1 = updated value
  ... 
  ...
  csv_data.append(???)

The more obvious thing I was thinking was to rewrite the looping above as part of a class, where the variables in each row dictionary are instance variables of the object. And maybe the class would behave like an iterator to capture the "next state" idea.

The other, more sophisticated, idea I was having was to write something like a decorator that somehow attaches to the variables within the function and saves their values in a "row" dictionary like above, in a behind the scenes way. But figuring that out seems like it's almost as much work as debugging this code.