Question

I have an array row. I want to add a set of attributes of an object actor to to the array. However, not all actors have each of the attributes.

I want to run a loop that will add the attribute if it exists, but add 'none' if it does not.

I can't seem to find a way to do the testing in the loop, using either try or hasattr. This is as far as I got. Of course, it does not work, because the attributes are referenced outside of the loop:

for attribute in [actor.x, actor.y, actor.parent, actor.force, actor.hunger, actor.size]:
    try:
        row.append(attribute)
    except AttributeError:
        row.append('none')

What is the best way to go about this?

Was it helpful?

Solution

for attribute in ['x', 'y', 'parent', 'force', 'hunger', 'size']:
    row.append(getattr(actor, attribute, 'none'))

getattr takes an optional 3rd argument setting a default value for if the object doesn't have the attribute.

Some notes here:

Why are some of these actors missing attributes? Should they instead have 'none' or None or some other default value?

Lists of strings are prone to bugs, due to implicit string literal concatenation. This is one of many good reasons to get a linting tool, if you're not using one already.

Are you sure you want 'none' as a default? It might make more sense to use None, or a zero-like value of whatever type the attributes are expected to be. (If they're expected to be strings, 'none' may make sense.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top