Dee Dee - 4 months ago 11
R Question

equivalent to R's `do.call` in python

Is there an equivalent to R's

do.call
in python?

do.call(what = 'sum', args = list(1:10)) #[1] 55
do.call(what = 'mean', args = list(1:10)) #[1] 5.5

?do.call
# Description
# do.call constructs and executes a function call from a name or a function and a list of arguments to be passed to it.

Answer

There is no built-in for this, but it is easy enough to construct an equivalent.

You can look up any object from the built-ins namespace using the __builtin__ (Python 2) or builtins (Python 3) modules then apply arbitrary arguments to that with *args and **kwargs syntax:

try:
    # Python 2
    import __builtin__ as builtins
except ImportError:
    # Python 3
    import builtins

def do_call(what, *args, **kwargs):
    return getattr(builtins, what)(*args, **kwargs)

do_call('sum', range(1, 11))

Generally speaking, we don't do this in Python. If you must translate strings into function objects, it is generally preferred to build a custom dictionary:

functions = {
    'sum': sum,
    'mean': lambda v: sum(v) / len(v),
}

then look up functions from that dictionary instead:

functions['sum'](range(1, 11))

This lets you strictly control what names are available to dynamic code, preventing a user from making a nuisance of themselves by calling built-ins for their destructive or disruptive effects.

Comments