2

I have a section in my code at the end of a recursive call that is as follows:

if (condition):
    # Some code here
else:
    return function_call(some_parameters) or function_call(some_parameters)

and it may evaluate to

return None or 0

where it will return 0 (an integer, as expected) or

return 0 or None

where it will return None (expected 0)

My question is, is it possible to have Python to return 0 (as an INTEGER) in the case immediately above?

Here is some code representing the scenario

$ cat test.py
#!/usr/bin/python3
def test_return():
    return 0 or None
def test_return2():
    return None or 0
def test_return3():
    return '0' or None #Equivalent of `return str(0) or None`

print( test_return() )
print( test_return2() )
print( test_return3() )

$ ./test.py
None
0
0

Note: 0 should be returned as an integer.

Kedwin Chen
  • 21
  • 1
  • 2

3 Answers3

3

The Python behaves None, 0, {}, [], '' as Falsy. Other values will be considered as Truthy So the following are normal behavior

def test_return():
    return 0 or None   # 0 is Falsy so None will be returned
def test_return2():
    return None or 0   # None is Falsy so 0 will be returned
def test_return3():
    return '0' or None # '0' is Truthy so will return '0'
Serjik
  • 10,543
  • 8
  • 61
  • 70
1

You can use decorators, if its a specific case. Example below:

def test_return(f):
    def wrapper():
        result = f()
        if result == None or result == '0':
            return 0
        else:
            return result
    return wrapper

@test_return
def f1():
    return 0 or None

@test_return
def f2():
    return None or 0

@test_return
def f3():
    return '0' or None

Output:

print(f1())
print(f2())
print(f3())

0
0
0

Click here for further read on decorators.

dalonlobo
  • 484
  • 4
  • 18
0

inline if else:

return 0 if (a == 0) + (b == 0) else None

by using the + arithmetic operator both a and b are evaluated, no 'shortcircuit' as with or

where a, b stand in for your function calls

tst = ((0, 0), (0, None), (None, 0), (None, None))


[0 if (a == 0) + (b == 0) else None for a, b in tst]
Out[112]: [0, 0, 0, None]
f5r5e5d
  • 3,656
  • 3
  • 14
  • 18