Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python try/except ... function always returns false

Tags:

python

pylons

I'm trying to figure out the problem in this short paragraph of code. Any help would be appreciated. Regardless of what I specify User.email to be, it always returns false.

def add(self):

    #1 -- VALIDATE EMAIL ADDRESS
    #Check that e-mail has been completed
    try:
        #Validate if e-mail address is in correct format
        if (isAddressValid(self.email) == 0):
            self.errors['email'] = 'You have entered an invalid e-mail address';
            return 0

    except NameError:
        self.errors['email'] = 'Please enter your e-mail'
        return 0

>>> u = User()
>>> u.email = '[email protected]'
>>> u.add()
0
>>> print u.errors
{'email': 'Please enter your e-mail'}

I have confirmed that the false being returned is coming from except NameError.

Also, isAddressValid() is just a method to check the structure of an e-mail address.

Thanks.

like image 633
ensnare Avatar asked Mar 18 '26 14:03

ensnare


1 Answers

You haven't included a return statement for the positive case... Also, when a function doesn't include a return statement, the caller receives None instead...

def add(self):

    #1 -- VALIDATE EMAIL ADDRESS
    #Check that e-mail has been completed
    try:
        #Validate if e-mail address is in correct format
        if (isAddressValid(self.email) == 0):
            self.errors['email'] = 'You have entered an invalid e-mail address';
            return False

    except NameError:
        self.errors['email'] = 'Please enter your e-mail'
        return False

    return True
like image 138
jldupont Avatar answered Mar 20 '26 06:03

jldupont



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!