Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialdodders
Python Development Techdegree Graduate 38,679 PointsWhy do the calls to name_exists and email_exists not need parentheses?
Why the calls to the custom validators 'name_exists' and 'email_exists' not need parentheses?
Especially confusing as the Flask provided validators such as DataRequired does need the parentheses.
1 Answer
Jeff Muday
Treehouse Moderator 28,720 PointsThe validator is taking in the function as an object reference rather than results. It's sort of a generic way that you can pass a function as an object.
Recall that Python functions are "first class citizens" just like all other objects. In this case, those functions are being passed as objects to the validator. And we can also get a variable number of arguments *args
or keyword arguments **kwargs
` see example below...
def generic_function_executor(my_function, *args, **kwargs):
"""Here is a generic function executor which will execute ANY function object"""
result = my_function(*args, **kwargs)
return result
def add(x,y):
"""Here is a simple add function of two variables"""
return x+y
def mult(x,y):
"""This is a simple multiplier of two variables"""
return x*y
def greet(name):
"""This function just prints hello name! to the console"""
print("Hello {}!".format(name))
# now, we can execute these functions with a single argument or an argument list.
print( generic_function_executor(add, 2, 3) )
print( generic_function_executor(mult, 2, 3) )
generic_function_executor(greet, "Pythoneer")
results in this output
5
6
Hello Pythoneer!