I want to call some unknown function with adding parameters using getattr function. Is it possible?
Asked
Active
Viewed 2.9k times
3 Answers
82
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)
Ignacio Vazquez-Abrams
- 740,318
- 145
- 1,296
- 1,325
52
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)
Steve Mayne
- 21,307
- 4
- 47
- 48
-
Thanks for the additional kwargs approach. – dave4jr Feb 27 '18 at 20:36
-
Thanks for sharing this tip. This is very helpful. – Ganesh Apr 27 '22 at 21:42
-2
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
mGran
- 1
- 2
-
1Don't set empty lists or dicts in the function declaration since they are evaluated immediately. – Sunny Patel Aug 10 '21 at 02:50
-
@SunnyPatel: Don't agree. With the empty list and dict declaration, the call_function_by_name is more universal. You can call functions without kwargs, args or even without any arguments. I modified my answer to make this clear. – mGran Aug 13 '21 at 06:23
-
@mGran, Sunny is pointing out that doing this is specifically an anti-pattern. There are many discussions on why setting an instance of an empty list/dict/etc in a function declaration doesn't do what many people think it will do, and why it will bite you. I'd suggest taking a look at some of those discussions. e.g. https://stackoverflow.com/questions/26320899/why-is-the-empty-dictionary-a-dangerous-default-value-in-python or https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument to make sure you understand the implications of doing this. – Zeb Oct 20 '21 at 17:43
-
1