Default values for iterable unpacking

后端 未结 2 686
面向向阳花
面向向阳花 2021-01-18 02:28

I\'ve often been frustrated by the lack of flexibility in Python\'s iterable unpacking.

Take the following example:

a, b = range(2)

2条回答
  •  囚心锁ツ
    2021-01-18 02:59

    Here's an alternative version of the decorator solution by @supersam654, using iterators rather than lists for efficiency:

    def variable_return(max_values, default=None):
        def decorator(f):
            def wrapper(*args, **kwargs):
                actual_values = f(*args, **kwargs)
                try:
                    for count, value in enumerate(actual_values, 1):
                        yield value
                except TypeError:
                    count = 1
                    yield actual_values
                yield from [default] * (max_values - count)
            return wrapper
        return decorator
    

    It's used in the same way:

    @variable_return(3)
    def ret_n(n):
        return tuple(range(n))
    
    a, b, c = ret_n(2)
    

    This could also be used with non-user-defined functions like so:

    a, b, c = variable_return(3)(range)(2)
    

提交回复
热议问题