简体   繁体   中英

Better Python Design Pattern when calling same function multiple times

I have the below Python code to store key and value attributes to Key Value database.

 try:
        persistence.set(student_first_name + ".firstname", student_first_name)
        persistence.set(student_last_name + ".last", student_last_name)
        persistence.set(student_id + ".id", student_id)
        persistence.set(student_sex + ".sex", student_sex)
        persistence.set(student_year + ".year", student_year)

    except ValueError:
        exception

Is there a better Design Pattern that calling the same persistence.set() with different parameters again and again? I have the same code being called in for loop in a different part of the application too.

If you store each piece of data in an its own variable, then you have little choice but to persist each one manually. But if you store all of them in one collection type, such as a dict, then you can iterate over the values using a loop. For example:

student = {
    "firstname": "John",
    "last": "Smith",
    "id": "4815162342",
    "sex": "male",
    "year": "2000"
}

for key, value in student.items():
    persistence.set(value + "." + key, value)

Incidentally it's a little unusual to me that you're creating redis keys by concatenating the object's value with a string indicating its purpose. It seems self-defeating to me. You won't be able to retrieve John Smith's year unless you know it's stored under the key "2000.year", but if you already know that, then there's no point getting it from the database.

I don't know what the idiomatic solution is, but it might make sense to prepend keys with a value that's unique to each student. The id might be sufficient:

for key, value in student.items():
    persistence.set(student["id"]+ "." + key, value)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM