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?
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With