views:

149

answers:

4

I'd like to be able to pull users from a database using either a supplied e-mail address or the user id (an integer). To do this, I have to detect if the supplied string is an integer, or an e-mail. Looking for the fastest way to do this. Thanks.

def __init__(self, data):
    #populate class data
    self._fetchInfo(data)


def _fetchInfo(self, data):
    #If an email
        #SELECT ... WHERE email = 'data'
    #or if a user_id
        #SELECT ... WHERE id = 'data'

    #Fill class attributes 
    self._id = row['id']
    self._email = row['id']
    ...
+5  A: 

The canonical way to handle this in Python is to try first, ask forgiveness later:

def _fetchInfo(self, data):
    try:
        data=int(data)
        sql='SELECT ... WHERE id = %s'
        args=[data]
    except ValueError:
        sql='SELECT ... WHERE email = %s'
        args=[data]
        # This might fail, in which case, data was neither a valid integer or email address

This strategy also goes by the moniker "It is Easier to Ask for Forgiveness than Permission".

unutbu
hahaha.. that's how try and catch should be taught in all schools
Anurag
Make sure you validate input before you just put any string into a `SELECT` statement.
Alex Reynolds
"Little Bobby Tables": http://xkcd.com/327/
Alex Reynolds
+2  A: 

You can use the isinstance function:

if isinstance(data, int):
   # it's an id
else:
   # it's a string

Though personally, I'd just have two methods, fetchById and fetchByEmail to make it clear that's how it works.

Dean Harding
isinstance won't work, since: "I have to detect if the supplied **string** ..." - it will always be an instance of str.
detly
Oh yes, I see that now... in that case, ~unutbu's answer will still work.
Dean Harding
+2  A: 

You said both were strings, right? This would work, too.

if data.isdigit():
    # it's an id
else:
    # it's not
Brendan Abel
Won't work if the integers can be negative.
dan04
@dan04.True, but auto-incrementing db id's generally aren't negative.
Brendan Abel
+1  A: 
if '@' in data:
    # email
else:
    # id
Kylotan