A flexible decorator-based solution inspired by this and this answer:
from itertools import islice, chain, repeat
def variable_return(max_values, default=None):
def decorator(f):
def wrapper(*args, **kwargs):
return islice(chain(f(*args, **kwargs), repeat(default)), max_values)
return wrapper
return decorator
Or a pointlessly condensed version:
variable_return = lambda m, d=None: lambda f: lambda *a, **k: islice(chain(f(*a, **k), repeat(d)), m)
It can be used like this:
@variable_return(3)
def split(s):
return s.split()
x, y, z = split(s) # ('hello', 'there', None)
or like this:
x, y, z = variable_return(3)(s.split)() # ('hello', 'there', None)