0

I have a function which is

def abc(a,b,c):
    #do something
    pass

I would like to call this with a list instead of abc(a,b,c), e.g.:

abc([1,2,3])

I cannot change the definition of abc.

Use case:

I am trying to write my own eval using the ast library

While implementing the ast.Call, I would like to be able to call my functions with multiple arguments.

However, if node is of type ast.Call, the arguments are passed in the form of a list.

E.g.:

>> exp = ast.parse('abc(1,2)', mode='eval').body
>> exp
# <_ast.Call at 0x2ab3c5bef7d0>
>> exp.args
#[<_ast.Num at 0x2ab3c5bef850>, <_ast.Num at 0x2ab3c5bef890>]

The problem is, I cannot understand how to call a function whose name is abc when the args returned to me is a list.

I would be trying to call library functions like min, max, len, str and my own functions like contains, get_item etc. What I can't understand is, how do I pass a list of arguments to a function that takes multiple arguments?

Dan Getz
  • 8,774
  • 6
  • 30
  • 64
akshitBhatia
  • 1,131
  • 5
  • 12
  • 20
  • i did not know the term unpacking. thank you. – akshitBhatia Mar 30 '16 at 20:19
  • Yeah it can sometimes be hard to find the relevant information, if you lack the terminology. There's more about this in python docs: https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists . I recommend reading that whole page :) – Ilja Everilä Mar 30 '16 at 20:23

1 Answers1

1

You can do this as follows, by unpacking the list with *

>>> def abc(a,b,c): print(a,b,c)
...
>>> abc(1,2,3)
1 2 3
>>> abc(*[1,2,3])
1 2 3
DNA
  • 42,007
  • 12
  • 107
  • 146