Goal: Reduce the wordiness of a (Python) retrieve_method using IF/ELIF/ELSE conditionals.
Structure of the Object Table and Method: This particular retrieve_method calls the user object based on elements making up the User table in the database (e.g. username
, firstname
, lastname
, email
, etc.)
As of now, my code is working, however it could use some cleaner, neater code. I am uncertain if I should use keywords
or *args
. I'm still learning Python, so any informative suggestions would be greatly appreciated. (You will notice that I am using an abstract word something_unique
at the moment to compare the input to the elements found in the table. If the two match, the method returns the matched item.)
How can I improve this? What is the best way to go? Pros? Cons?
Software: Python 2.7.9, SQLAlchemy 1.0.9
Code:
def retrieve_user(self, something_unique):
if isinstance(something_unique, int):
print 'retrieve_user_id: ', something_unique # added
return self.session.query(User).\
filter(User.id == something_unique).one()
elif isinstance(something_unique, basestring):
print 'retrieve_user: ', something_unique # added
return self.session.query(User).\
filter(func.lower(User.username) == func.lower(something_unique)).first()
elif isinstance(something_unique, basestring):
print 'retrieve_user email', something_unique
return self.session.query(User).\
filter(func.lower(User.email) == func.lower(something_unique)).first()
elif isinstance(something_unique, User):
return something_unique
else:
raise ValueError('Value being passed is an object')