I have code which gets data from a
POST request (
request.form dict), compares with corresponding attribute in object
accident and does some action. The code looks needlessly verbose. How can I optimize it?
if accident.status == 1: if request.form.get('reason') \ and request.form['reason'] != accident.reason: accident.set_reason(request.form['reason'], current_user) if request.form.get('note') \ and request.form['note'] != accident.note: accident.note = request.form['note'] else: if request.form.get('priority') \ and int(request.form['priority']) != accident.priority: accident.set_priority(current_user, int(request.form['priority'])) if request.form.get('status') \ and int(request.form['status']) != accident.status: accident.set_status(current_user, int(request.form['status'])) if request.form.get('duration') \ and int(request.form['duration']) != accident.duration: accident.duration = int(request.form['duration']) if request.form.get('service_status') \ and int(request.form['service_status']) != accident.service_status: accident.set_service_status(int(request.form['service_status']))
Below is a stripped down version of
Accident class, which is inconsistent because there are many fields, and sometimes setting a field requires many additional actions like logging or checking for user rights. The class derives from MongoEngine schema class.
class Accident(Document): priority = IntField(choices=PRIORITIES) status = IntField(choices=STATUSES, default=0) duration = IntField() region = StringField() service_status = IntField(choices=(0, 1, 2)) reason = StringField(default=u"") note = StringField(default=u"") def set_priority(self, user=None, priority=None): self.priority = priority # Functions starting with `set_` do some activity that has # nothing to do with setting and validating a value. That's # why i don't use @property decorator. `to_history(user)` is # just an example. to_history(user) def set_status(self, user, status): self.status = status to_history(user) def set_reason(self, reason, user): self.reason = reason to_history(user) def set_service_status(self, ss): self.service_status = ss to_history(user)
If this is necessary, how can i improve class structure? It seems like I can't use
@property decorator for setters, because my setters accept additional parameters. However I don't like the idea of writing a setter for all possible attributes. I use
request.form.get(foo) instead of
foo in request.form, because the dictionary may contain
foo: None pair, and I don't want to accidentally set an attribute to