6

For example:

def update_condition(self, type, params):
    for condition in self.conditions:
        condition_loaded = json.loads(condition)
        if condition_loaded['type'] == type:
            condition_loaded['params'] = params
            condition = json.dumps(condition_loaded)

The above code does nothing because condition isn't by reference. What's the proper way to do this?

Joren
  • 9,623
  • 19
  • 63
  • 104

2 Answers2

14

You could use enumerate:

def update_condition(self, type, params):
    for i,condition in enumerate(self.conditions):
        condition_loaded = json.loads(condition)
        if condition_loaded['type'] == type:
            condition_loaded['params'] = params
            self.conditions[i] = json.dumps(condition_loaded)

But, in general, these things are a little cleaner with helper functions and list comprehensions:

def helper(condition,type,params)
    loaded = json.loads(condition)
    if loaded['type'] == type:
       loaded['params'] = params
       return json.dumps(loaded)
    return condition

...

def update_condition(self, type, params):
    self.conditions = [helper(c,type,params) for c in self.conditions]

It should be noted that this second solution doesn't update the list in place -- In other words, if you have other references to this list, they won't be influenced. If you want, you can make the substitution in place pretty easily using slice assignment:

def update_condition(self, type, params):
    self.conditions[:] = [helper(c,type,params) for c in self.conditions]
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • +1. Nice clear explanation of both the mutating and non-mutating alternatives (without writing 3 pages of text like I usually end up doing in these cases). – abarnert Jan 18 '13 at 20:46
  • @abarnert -- Thanks for the feedback. It's always nice when someone who consistently writes good answers leaves a nice note :) – mgilson Jan 18 '13 at 20:56
1

You could use a list comprehension:

def update_single_condition(self, condition, type, params):
    condition_loaded = json.loads(condition)
    if condition_loaded['type'] == type:
        condition_loaded['params'] = params
    return json.dumps(condition_loaded)

def update_conditions(self, type, params): 
    self.conditions = [self.update_single_condition(c, type, params) for c in self.conditions]
mgilson
  • 300,191
  • 65
  • 633
  • 696
Thomas Orozco
  • 53,284
  • 11
  • 113
  • 116
  • It seems to me that `update_single_condition` could be a staticmethod or just a regular function. Otherwise, good answer +1. – mgilson Jan 18 '13 at 19:53