7

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?

Chase Roberts
  • 9,082
  • 13
  • 73
  • 131
  • 9
    Try `hasattr(user, 'user_info')` and `'user_info' in user`. – Blender Apr 20 '13 at 20:31
  • anothering thing to consider, is if every user should have a `UserInfo` object you could subscribe to user creation signal and initialize a `UserInfo` object automatically for every user created. https://docs.djangoproject.com/en/dev/topics/signals/ – dm03514 Apr 20 '13 at 20:34
  • 1
    http://stackoverflow.com/questions/610883/how-to-know-if-an-object-has-an-attribute-in-python – phazei Sep 26 '13 at 02:49

1 Answers1

13

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

Community
  • 1
  • 1
msvalkon
  • 11,887
  • 2
  • 42
  • 38