Dee Dee - 1 year ago 106
R Question

equivalent to R's `` in python

Is there an equivalent to R's
in python? = 'sum', args = list(1:10)) #[1] 55 = 'mean', args = list(1:10)) #[1] 5.5

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

Answer Source

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:

    # 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download