checking for the existence of an attribute

Peter Otten __peter__ at web.de
Sun Oct 12 13:37:26 EDT 2003


Bob Roberts wrote:

> 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




More information about the Python-list mailing list