Ah, it depends on the exact code. Your two tools:
- hasattr(obj, 'attr') return True if and only if obj.attr exists.
- getattr(obj, 'attr', other_value) returns obj.attr if it exists, else other_value
- try a = obj.attr/except failure()/else do_something(a) when performance beats readability.
Here are the most common cases:
the_name = getattr(user, 'name', '<Unknown User>')
user.name = getattr(user, 'name', '<Unknown User>')
if not hasattr(name, 'user'):
try_asking_again()
name = user.name if hasattr(user, 'name') else do_expensive_name_lookup(user)
To better understand the whole process, look at this snippet:
class Thing():
def __init__(self):
self.a = 'A'
def __getattr__(self, attr):
if attr == "b":
return "B"
else:
raise AttributeError("Thing instance has no attribute '" + attr + "'")
item = Thing()
print "hasattr(a) is " + str(hasattr(item, "a"))
print "a is " + item.a
print "hasattr(b) is " + str(hasattr(item, "b"))
print "b is " + item.b
out = "c is " + item.c if hasattr(item, "c") else "No C"
print out
print "and c is also " + getattr(item, "c", "Not Assigned")
print "c throws an Attribute exception " + item.c
which has this output:
hasattr(a) is True
a is A
hasattr(b) is True
b is B
No C
and c is also Not Assigned
Traceback (most recent call last):
File "attr_snippet.py", line 23, in <module>
print "c throws an Attribute exception " + item.c
File "attr_snippet.py", line 9, in __getattr__
raise AttributeError("Thing instance has no attribute '" + attr + "'")
AttributeError: Thing instance has no attribute 'c'