swedishfished
swedishfished

Reputation: 399

Can you return a return statement in Python?

I'm working on a web application and I'm creating a login & authentication form. Some pages should be off-limits if you are logged in (e.g. the login form), and I'm trying to create a systematic way of doing this.

To do this, I was trying to create a function which would return a return statement. See the code below.

def login():
    redirect_to_home_if_logged_in()
    # rest of login page
def register():
    redirect_to_home_if_logged_in()
    # rest of register page
def redirect_to_home_if_logged_in():
    if current_user.is_authenticated:
        print("squa")
        return return redirect(url_for('home'))

I was hoping that the function would return a return statement, so that the login and register pages would return a redirect. Instead I got an error.

Upvotes: 4

Views: 1066

Answers (1)

tripleee
tripleee

Reputation: 189397

No, you cannot return a return statement as such.

A common arrangement is to refactor the code so that the caller takes care of what you return, and relays that back to its caller.

Another approach is via callbacks. Something like this:

def bar():
    def foo():
        return "ick"
    return foo

Here, the return value from bar is a function object foo. This requires the caller of bar to know this and agree to call foo() at some later point in time when the value is actually required. (You could often also use a lambda in these circumstances; Python predictably calls this type of value a "callable".)

As noted by @Dair in a comment already, what you are actually trying to accomplish is probably already covered by a completely different mechanism by whichever web framework you are probably already using. Here's Flask and here's Django.

Upvotes: 3

Related Questions