24  Python: Function as a String

24.1 Function as a character/string

  • Python does not have a direct equivalent to R’s do.call or match.fun.

  • However, one can achieve a similar effect using a dictionary to map function names to their actual function objects, as shown in the previous response.

  • An alternative option is to use partial function of functools library.

24.2 Data

Code
import numpy as np

A = np.array([11, 12, np.nan, 14, 15])

24.3 Option 1: Using mapping function

Code
def fn_N(x, na_rm=False):
    xn = len(x) - np.isnan(x).sum() if na_rm else len(x)
    return xn

def fn_sum(x, na_rm=False):
    return np.nansum(x) if na_rm else np.sum(x)

def fn_mean(x, na_rm=False):
    xn = fn_N(x, na_rm=na_rm)
    xsum = fn_sum(x, na_rm=na_rm)
    xmean = xsum / xn
    return xmean

def fn_call(func_name, *args, **kwargs):
    function_map = {
        'fn_mean': fn_mean,
    }
    
    func = function_map.get(func_name)
    if func is None:
        raise ValueError("Function not found")
    
    return func(*args, **kwargs)

24.4 Example

Code
fn_call('fn_mean', A, na_rm=True)

24.5 Option 2: Using library functools

Code
import numpy as np
from functools import partial

def fn_N(x, na_rm=False):
    xn = len(x) - np.isnan(x).sum() if na_rm else len(x)
    return xn

def fn_sum(x, na_rm=False):
    return np.nansum(x) if na_rm else np.sum(x)

def fn_xmean(x, na_rm=False):
    xn = fn_N(x, na_rm=na_rm)
    xsum = fn_sum(x, na_rm=na_rm)
    xmean = xsum / xn
    return xmean

# Using functools.partial to create a function with preset arguments
def fn_call(func_name, *args, **kwargs):
    func = globals().get(func_name)
    if func is None:
        raise ValueError("Function not found")
    
    partial_func = partial(func, *args, **kwargs)
    return partial_func()

24.6 Example

Code
fn_call('fn_mean', A, na_rm=True)