Walter Renner Walter Renner - 1 month ago 5
Python Question

What is the "pythonic" way to create a list with one element or just keep it empty?

Let's say a have

Person
instance
person
.
person
may have an attribute
id
.

I want to write a function that gets me either an empty list
[]
when the attribute is
None
or missing or the list
[12, ]
when the attribute
id
is 12.

def get_id_list(person):
try:
return [getattr(person, 'id'), ]
except AttributeError:
return []


This works perfectly but is there a "pythonic" way of doing this without the try-except block and maybe in one line?

Answer

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]
Comments