Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Django check if an attribute exists or has been set

Tags:

python

django

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?

like image 337
Chase Roberts Avatar asked Apr 20 '13 20:04

Chase Roberts


People also ask

How do you check if an attribute exists in an object Python?

We can use hasattr() function to find if a python object obj has a certain attribute or property. hasattr(obj, 'attribute'): The convention in python is that, if the property is likely to be there, simply call it and catch it with a try/except block.

How do you check is exists in Django?

Django provides a count() method for precisely this reason. Note: If you only want to determine if at least one result exists (and don't need the actual objects), it's more efficient to use exists() .

How do you check if an object has a specific attribute?

If you want to determine whether a given object has a particular attribute then hasattr() method is what you are looking for. The method accepts two arguments, the object and the attribute in string format.


1 Answers

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

like image 161
msvalkon Avatar answered Oct 10 '22 14:10

msvalkon