I want to check a certain argument value against a regex-pattern and only continue if they match. This happens in many places within my app, so I decided to let a function do the checking and call that function whenever I need it. Now, in most cases, I need that check to be performed right at the beginning of a view, so I created it as a decorator like so:
def validate(f):
def _inner(request, argument=None):
if argument is None:
return HttpResponse(content="No argument given", status=400)
elif not re.match('^SOME_REGEX$', argument):
return HttpResponse(content="Invalid argument", status=400)
else:
return f(request, argument)
return _inner
But there are other cases where I need to call that checker from within a function, as part of nested conditions. It seems I can’t call it directly, e.g. validate(argument). Is there any way I can use the same code as a decorator as well as a normal function? Or do I have to type it twice?
You certainly don’t have to type it twice, you can just create a
validatefunction which takes a value and validates it:and then write a decorator which calls the
validatefunction as needed:Obviously, I don’t know your use case so you might want to move the check for
Noneintovalidatebut the point is, you don’t have to repeat the same regex twice.And if you feel like delving into deeper magic and insist on using the same function both as a decorator and a verifier, you might try something like this:
But I’d advise against this, since you have one function that does two very different things, depending on the type of the parameter. This results in code that is much more difficult to understand. (“You decorate a view with this function which takes a string and returns bool?!”)