Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python wrap function with unknown arguments

If I have this function:

def foo(arg_one, arg_two):
    pass

I can wrap it like so:

def bar(arg_one, arg_two):
    return foo(arg_one, arg_two)

foo = bar

Is it possible to do this without knowing foo's required arguments, and if so, how?

like image 385
Leagsaidh Gordon Avatar asked Aug 25 '26 09:08

Leagsaidh Gordon


2 Answers

You can use the argument unpacking operators (or whatever they're called):

def bar(*args, **kwargs):
    return foo(*args, **kwargs)

If you don't plan on passing any keyword arguments, you can remove **kwargs.

like image 54
Blender Avatar answered Aug 26 '26 23:08

Blender


You can use *args and **kwargs:

def bar(*args, **kwargs):
    return foo(*args, **kwargs)

args is a list of positional arguments.

kwargs is a dictionary of keyword arguments.

Note that calling those variables args and kwargs is just a naming convention. * and ** do all the magic for unpacking the arguments.

Also see:

  • documentation
  • What do *args and **kwargs mean?
  • *args and **kwargs?
like image 28
alecxe Avatar answered Aug 26 '26 23:08

alecxe