rezkam
rezkam

Reputation: 1357

Is there a better way to write these in python?

Is there a better way to write these lines in python ? for example using a for:

user.name = form.name.data
user.username = form.username.data
user.password = form.password.data
user.email = form.email.data

Upvotes: 0

Views: 95

Answers (2)

sax
sax

Reputation: 3796

for el in ('name', 'username', 'password', 'email'):
    setattr(user, el, getattr(form, el).data)

anyway as per python zen 'Simple is better than complex', do not see anything wrong with your code

Upvotes: 4

Cory Kramer
Cory Kramer

Reputation: 117856

Not really. Those are doing separate tasks so it makes sense for each to statement to be on its own line. If you find yourself doing this repetitively, you can wrap it in a function if you'd like

def setUserData(user, form):
    user.name = form.name.data
    user.username = form.username.data
    user.password = form.password.data
    user.email = form.email.data

Then whenever you want to do these operations, you can just say

>>> setUserData(user, form)

Upvotes: 2

Related Questions