views:

229

answers:

5

Hello, i have code like this:

try:
            var = request.POST['var']                                        
except NameError:                
            var = ''

Why always code after "except" is executing? Even if request.POST['var'] exist.

+8  A: 

How do you know it is executing? Perhaps request.POST['var'] is also '' so you couldn't tell the difference.

Also, the only way that

var = request.POST['var'] 

could raise a NameError is if request doesn't exist.

If request.POST doesn't exist, means POST doesn't exist as an attribute of request thus raising AttributeError instead, and if request.POST['var'] doesn't exist, means 'var' is not a key of request.POST thus raising KeyError instead.


EDIT:

My guess is that you're not sending a POST. But can't know for sure.

nosklo
'var' is definately not epmty - I see it in firebug. When I'm using AtrributeError instead of Name error i see message "Key 'var' not found in <QueryDict: {}>"
DJPython
huh, that means there's no `'var'` in `request.POST` - firebug *is not python** , it can't show python memory, python object contents, or anything on the script running on the server, since firebug runs on the browser. You're wrong about your assumption.
nosklo
you are mixing up the two 'var's - the 'var' in the stack frame might exist. But it certainly doesn't exist as a key in your POST! that's what the error message is telling you.
Sanjay Manohar
+1  A: 

A better way to do what you seem to be trying to do might be

var = request.POST.get('var', 'some default value')

where the second argument to the POST dict's get method is the value to return if the key ('var' in this case) doesn't exist. Translating your example exactly would result in:

var = request.POST.get('var', '')

That way, no try...except block or conditional statements are needed.

Will McCutchen
Won't help if `request` is undefined which seems to be the case here.
Noufal Ibrahim
+2  A: 

Eliminate the guesswork and replace NameError with something like KeyboardInterrupt, look at the traceback and you'll know exactly what the problem is.

Noufal Ibrahim
This is the best way to find the cause of the problem. try/except blocks are useful, but they can also hide problems that you want to find. Take it out of the equation first. Then, after you've solved the problem, put it back in.
jcdyer
+1  A: 

what's the result of the following in your case?

except NameError, e:
    print e
Antony Hatchkins
A: 

try

try:
            if request.method == 'POST':
               var = request.POST['var']                                        
except NameError:                
               var = ''
George