checking for the existence of an attribute

Ian Bicking ianb at colorstudy.com
Sun Oct 12 13:38:24 EDT 2003


On Sunday, October 12, 2003, at 12:23 PM, Bob Roberts wrote:
> I'm sure there must be a better way to do this:
>
>         try:
>             if item.page:
>                 DoSomething()
>         except AttributError:
>             pass

Well, you could try:

try:
     item.page
     DoSomething()
except AttributeError:
     pass

Since the if statement is kind of redundant, unless you expect the 
attribute to exist but be set to None or something.

But you're probably looking for:

if getattr(item, 'page', None):
     DoSomething()

The third argument to getattr is a default to return when the attribute 
isn't found.

--
Ian Bicking | ianb at colorstudy.com | http://blog.ianbicking.org






More information about the Python-list mailing list