tags:

views:

77

answers:

2

I want to verify that the object I created was really created, and return True or False according to that:

obj = object(name='plop')
try:
 obj.save()
 return True
except ???:
  return False

How can object creation be verified?

+2  A: 

First of all - that's a not good practice that you are doing

2nd the only case when exception can happen is database connection fail or some constrains or required required fields not set.. in that case db-backend.OperationalError is raised

Update: on constrains fail there is a IntegrityError exception

Pydev UA
Thanks for the answer.Can you let me know what's wrong practice so that I can improve ?cheers.
Martin
because when something bad happens and you just return False you will have no idea what exactly happens (and will debug a lot of time to understand bug) - There is a lot to tell about that.. just look at docs and opinions of experienced developers
Pydev UA
Why not move the try block into the caller instead of checking a boolean? That's preferred in python for numerous reasons. Return value checking is a C programming practice and not generally appropriate in any language with exception support.
Eloff
+1  A: 

save() can also raise other exceptions, such as ValidationError in django 1.2, or any arbitrary exception if the save() method has been overridden.

I don't see anything particularly wrong with attempting a save() and catching the exception. If for some reason you prefer to check a boolean return value than just catch the exception (not usually how it's done in python), then you have the right idea. Just change except ???: to except Exception:

After all you want to return False on any expected failure.

Eloff
Thanks Eloff.Yes the Idea is just to return False if failed. It doesn't matter why it failed. I guess I could log the reason of the exception, but the True/False result is being sent over xmlrpc later on and will never show on the user screen. I will use except Exception.Thanks.
Martin
Yep, that's one of those places where it's perfectly ok to catch the exception. If using django 1.2, you may wish to also catch ValidationError and IntegrityError and return a sensible error message over xmlrpc (or marshal the exception over.)
Eloff