Sibi
Sibi

Reputation: 48644

Abstracting if statement and return by a function

I have a function like this:

def test():
    x = "3" # In actual code, this is computed

    if x is None:
        return None

    y = "3"

    if y is None:
        return None

    z = "hello"

    if z is None:
        return None

Is there a way of making the if statement go away and abstract it with some function. I'm expecting something like this:

def test():
    x = "3"
    check_None(x)

    y = "3"
    check_None(y)

    z = "hello"
    check_None(z)

Ideally, check_None should alter the control flow if the parameter passed to it is None. Is this possible?

Note: Working on Python 2.7.

Upvotes: 1

Views: 119

Answers (2)

Namit Singal
Namit Singal

Reputation: 1516

I am not really sure if we should do it like this, but one of the hacks could be like this, Also create your own exception class and only catch that particular exception so that no other exceptions are accidentally caught by the except and return None.

class MyException(Exception):
    pass

def check_none(x):
    if x is None:
        raise MyException

def test():
    try:
        z=None
        check_none(z)
    except MyException, e:
        return None

return_value = test()

Upvotes: 0

hspandher
hspandher

Reputation: 16733

You can easily code it in some thing like this.

def test():
    #compute x, y, z
    if None in [x, y, z]:
       return None
    # proceed with rest of code

An even better way would be to use an generator to generate value x, y, z so that you only does computation for one value at a time.

def compute_values():
    yield compute_x()
    yield compute_y()
    yield compute_z()

def test():
    for value in compute_values():
        if value is None:
           return None

Upvotes: 2

Related Questions