checking for the existence of an attribute

B

Bob Roberts

I'm sure there must be a better way to do this:

try:
if item.page:
DoSomething()
except AttributError:
pass

Is there a simple way to check if item has "page" as one of its attributes?
 
P

Peter Otten

Bob said:
I'm sure there must be a better way to do this:

try:
if item.page:
DoSomething()
except AttributError:
pass

Is there a simple way to check if item has "page" as one of its
attributes?


try:
item.page
except AttributeError:
pass
else:
doSomething()


or

if hasattr(item, "page"):
doSomething()

Peter
 
T

Terry Reedy

Bob Roberts said:
I'm sure there must be a better way to do this:

try:
if item.page:
DoSomething()
except AttributError:
pass

This checks both the item.page exists and that it has a True value.
Is that exactly the check you want? Catching attribute errors with
try..except a standard Python idiom.
Is there a simple way to check if item has "page" as one of its
attributes?

enter 'help(hasattr)' at prompt or check lib ref 'builtin functions'.
If item is often missing a page, (>10% of tries), then explicit test
might be better.

Terry J. Reedy
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,527
Members
44,999
Latest member
MakersCBDGummiesReview

Latest Threads

Top