Chase Roberts
Chase Roberts

Reputation: 9376

Python Django check if an attribute exists or has been set

I have a User object and a UserInfo object which have a one to one relationship. I am just adding the UserInfo object so some users already have User objects but not UserInfo objects. I want to check to see if the User object has a UserInfo object associated with it yet and if not redirect them to a page where I can get some info. I am still new to python and have tried doing an if request.user.user_info: which throws an exception when it doesn't exist so I ended up doing this:

 user = request.user
    try:
        user.user_info.university
    except:
        print 'redirect to info page'

which works fine, but I feel like exceptions should be for exceptions and not for if statement substitutes. Is there a better way to do this?

Upvotes: 7

Views: 13452

Answers (1)

msvalkon
msvalkon

Reputation: 12077

I'd say that handling this with exceptions is the pythonic approach. You can do something like this:

try:
    # do your thing when user.user_info exists
except AttributeError: # Be explicit with catching exceptions.
    # Redirect.

There's a programming concept called it's easier to ask for forgiveness than permission (EAFP) which is used extensively in Python. We assume that attributes, keys and so forth exist for a given object and catch exceptions when they do not.

Here are some references and SO questions about EAFP.

Python glossary
What is the EAFP principle in Python
EAFP and what is really exceptional

Upvotes: 13

Related Questions