0

I'm trying to set some booleans based on whether or not an object has attributes:

try:
    att1 = myobj.att1
    att2 = myobj.att2
    att3 = myobj.att3
except AttributeError:
    pass

However, if att1 is not present and throws an AttributeError, it won't try the other two. Must I loop (is there no way to do it in one try statement?)

Thanks!

5 Answers 5

3

why not just do :

your_boolean = hasattr(obj, att1) or hasattr(obj, att2) or hasattr(obj, att3)
Sign up to request clarification or add additional context in comments.

Comments

1

No need for a try statement here. For example:

myobj = 10
names = ['att1', 'att2', 'att3', 'real']
results = dict((name, getattr(myobj, name, None)) for name in names)
#{'real': 10, 'att3': None, 'att2': None, 'att1': None}

2 Comments

Quite true. I like this getattr function.
Very few languages make meta programming as simple AND as clean as python.
0

Are you using this only to check whether some object has attributes? If so, use the built-in function hasattr (which in fact does the same test as you have implemented manually anyway.


Otherwise, you must loop.

If you think about the structure of the code, what you are really wanting is three try...except blocks -- after all, if exceptions returned flow to where they were raised after being processed, they wouldn't be very exceptional!

It would be pretty easy to write a loop, though:

atts = []
for attr in ("att1", "att2", "att3"):
    try:
        attrs.append(getattr(myobj, attr))
    except AttributeError:
        attrs.append[None]
att1, att2, att3 = atts

If you really want the attributes as local variables, you could even do:

for attr in ("att1", "att2", "att3"):
    try:
        locals()[attr] = getattr(myobj, attr)
    except AttributeError:
        pass

1 Comment

Awesome. I wasn't testing for mere existence, so I guess I must loop. Thanks for the explanation.
0

Considering there is 2*2*2 possible existence combinations, why not have set?

set(attr for attr in ('att%i' for i in range(1,4)) if obj.hasattr(attr))

Comments

0

I think this also works:

try:
    (var1 and var2)
except NameError:
    ...

It will test all variables before making a decision.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.