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