How to launch getattr function in python with additional parameters?

Question:

I want to call some unknown function with adding parameters using getattr function. Is it possible?

Asked By: megido

||

Answers:

Yes, but you don’t pass them to getattr(); you call the function as normal once you have a reference to it.

getattr(obj, 'func')('foo', 'bar', 42)

If you wish to invoke a dynamic method with a dynamic list of arguments / keyword arguments, you can do the following:

function_name = 'wibble'
args = ['flip', 'do']
kwargs = {'foo':'bar'}

getattr(obj, function_name)(*args, **kwargs)
Answered By: Steve Mayne

function to call

import sys

def wibble(a, b, foo='foo'):
    print(a, b, foo)
    
def wibble_without_kwargs(a, b):
    print(a, b)
    
def wibble_without_args(foo='foo'):
    print(foo)
    
def wibble_without_any_args():
    print('huhu')


# have to be in the same scope as wibble
def call_function_by_name(function_name, args=None, kwargs=None):
    if args is None:
        args = list()
    if kwargs is None:
        kwargs = dict()
    getattr(sys.modules[__name__], function_name)(*args, **kwargs)

    
call_function_by_name('wibble', args=['arg1', 'arg2'], kwargs={'foo': 'bar'})
call_function_by_name('wibble_without_kwargs', args=['arg1', 'arg2'])
call_function_by_name('wibble_without_args', kwargs={'foo': 'bar'})
call_function_by_name('wibble_without_any_args')
# output:
# arg1 arg2 bar
# arg1 arg2
# bar
# huhu
Answered By: mGran
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.