DanH
DanH

Reputation: 5818

Short form to return method result if condition passed

I'm wondering if there's any pythonic or short-form method to achieve the following:

    error_response = self.check_conditions(request)
    # If we have an error response, return it, otherwise continue as normal.
    if error_response:
        return error_response

Something like:

(return self.check_conditions(request)) or pass

Alternatively, is it possible for a function to return the calling method, such as:

self.check_conditions(request)

def check_conditions(self, request):
    error_response = do_stuff()
    if error_response:
        return_parent error_response

I get the feeling the second concept is breaking a ton of programming laws to prevent chaos and the apocalypse, just a thought though :)

Upvotes: 1

Views: 50

Answers (2)

cg909
cg909

Reputation: 2546

No, there is no short form for a conditional return.

But, to get to the second part of your question:

There are exceptions in Python. You can write something like this:

class MyErrorResponse(Exception): pass

class MyClass:
    ...
    def check_conditions(self, request):
        error_response = do_stuff()
        if error_response:
            raise MyErrorResponse(error_response)

    def do_the_main_stuff():
        try:
            self.check_conditions()
            ...
        except MyErrorResponse as e:
            return e.args[0]

Upvotes: 1

Adam Smith
Adam Smith

Reputation: 54203

That depends a lot on what check_conditions does under the hood. It's likely that you can move error handling down a level of abstraction and handle things directly:

Compare:

error = False

def foo(request):
    global error
    try:
        result = do_something_with(request)
    except SomeWellDefinedError:
        error = True

def check_conditions(request):
    foo(request)
    return error

def main():
    error_response = check_conditions(some_request)
    if error_response:
        # freak out!

With

def foo(request):
    try:
        result = do_something_with(request)
    except SomeWellDefinedError:
        # you can try to handle the error here, or...
        raise  # uh oh!

def main():
    try:
        foo(some_request)
    except SomeWellDefinedError:
        # handle the error here, instead!

Upvotes: 1

Related Questions