Let's say a have
return [getattr(person, 'id'), ]
Your approach is pythonic, just do some little changes. First off don't return inside the try, you can preserve the
id value in a variable and return it properly within
else clause. The reason is that you are doing multiple operation like getting attribute and converting to list (and maybe more(in other cases)) while you are just catching the
AttributeError. And when you use
else you can handle other exceptions easily, also it's more elegant from coding style's perspective.
Secondly you don't need to use
getattr in this case, you can simply use direct attribute access.
Also instead of using the
try-except you might want to check if the object has the attribute then return its value but due to It's easier to ask forgiveness than it is to get permission. principal the
try-exepct is better.
def get_id_list(person): try: id = person.id except AttributeError: return  else: return [id]