سؤال

I have this very little and simple if blocks:

if obj_type == "domain":
    key = "domain"
elif obj_type == "db_user":
    key = "username"
else:
    key = "name"

These can be converted to an if expression:
key = "domain" if obj_type == "domain" else "usernme" if obj_type == "db_user" else "name"

Are there any advantages in performance? If that's not a factor, which one should by preferred for readability, PEP8 compliance?

هل كانت مفيدة؟

المحلول

They perform identically, so use the first one if you need to choose between the two.

Since you're really just creating a mapping between two sets, using a dictionary would be a better approach. It's faster and arguably more readable:

mapping = {
    'domain': 'domain',
    'db_user': 'username',
}

key = mapping.get(obj_type, 'name')
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top