Looking for idiomatic way to evaluate to False if argument is False in Python 3
I attempted to use ternary operators, but they don't evaluate correctly.
def func(inp): return int(inp['value']) + 1 if inp else False
throws a TypeError, bool not subscriptable, if
i == False
becauseinp['value']
is evaluated before the conditional.
This is not true - that code works. Further, you can just write
def func(inp):
return inp and (int(inp['value']) + 1)
To automatically wrap functions like this, make a function that wraps a function:
def fallthrough_on_false(function):
def inner(inp):
return inp and function(inp)
return inner
This should be improved by using functools.wraps
to carry through decorators and names, and it should probably take a variadic number of arguments to allow for optional extensions:
from functools import wraps
def fallthrough_on_false(function):
@wraps(function)
def inner(inp, *args, **kwargs):
return inp and function(inp, *args, **kwargs)
return inner
Decorator should look like:
def validate_inp(fun):
def wrapper(inp):
return fun(inp) if inp else False
return wrapper
@validate_inp
def func(inp):
return int(inp['value']) + 1
print(func(False))
print(func({'value': 1}))
If you want to use your decorator with a class member:
def validate_inp(fun):
def wrapper(self, inp):
return fun(self, inp) if inp else False
return wrapper
class Foo(object):
@validate_inp
def func(self, inp):
return int(inp['value']) + 1 if inp else False
foo = Foo()
print(foo.func(False))
print(foo.func({'value': 1}))