Getting a Python function to cleanly return a scalar or list, depending on number of arguments

走远了吗. 提交于 2019-11-28 12:33:34

You can easily write a function scalify that returns the element from the list if the list has only one element, i.e. it tries to make it a scalar (hence the name).

def scalify(l):
    return l if len(l) > 1 else l[0]

Then you can use it in your functions like so:

def foo(*args):
    return scalify([a + 1 for a in args])

This will do the trick, but I'm with those who suggest you don't do it. For one reason, it rules out iterating over the result unless you know you passed in at least two items. Also, if you have a list, you have to unpack the list when calling the function, losing its "listness," and you know you may not get a list back. These drawbacks seem to me to overshadow any benefit you may see to the technique.

You can always write a decorator to elide that if statement if that is nicer to you:

import functools
def unpacked(method):
    @functools.wraps(method)
    def _decorator(*args):
        result = method(*args)
        return results if len(results) != 1 else results[0]
    return _decorator

Usage:

@unpacked
def foo(*args):
    return [arg + 1 for arg in args]

Do you mean you want a tuple with the same number of arguments? Is this not a solution?

return tuple([a + 1 for a in args])

def foo(*args):
    return (None, args[0]+1 if args else None, map(lambda a: a + 1, args))[len(args) if len(args) < 3 else 2]

:-) it is hell

This will handle 0 or more args, I think that's what you're looking for.

def foo(*args):
    return map(lambda x: x + 1, args) or [None]

edit: I revised to add a None list incase of unpacking 0 args

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!