chiiidog chiiidog - 1 year ago 39
Python Question

Pass an argument to a class which becomes a keyword for a function

Using WTForms with Flask and SQLAlchemy. Taking data from a username and email field and making sure it's not already in the database. Here's what I have to do right now.

class IsUnique(object):
def __init__(self, db_field=None):
self.db_field = db_field

def __call__(self, form, field):
data =
if self.db_field=='name':
if User.query.filter_by(name=data).first() != None:
raise ValidationError('Sorry, that username is taken.')
if self.db_field=='email':
if User.query.filter_by(email=data).first() != None:
raise ValidationError(
'Sorry, that email address has already been registered.'

What I would like to do is to pass the db_field argument to the class instance as a string and pass it into
. Unfortunately all I know how to do is use an if statement, which works, but is kinda cumbersome. There's gotta be a way to do this right, but I don't know how.

Answer Source

You can pass keyword arguments as a dict, like this:

def __call__(self, form, field):
    key = self.db_field # 'name' or 'email'
    params = { key: }
    if User.query.filter_by(**params).first() != None:
        raise ValidationError('Sorry, that {} is taken.'.format(key))