Python: Using defined arguments with *args

171 Views Asked by At

Rewritten to make more clear the use-case and answer better Anentropic's question.

def use_all (step_todo, wait_complete=True, *args):
    execute_step1 (step-todo)
    handle_args (*args)
    if not wait_complete: 
       do_somehing ()
       return
    execute_stepN ()

@decorate
def use_from (step_todo, *args):
    use_all (step_todo, args)

@decorate
def use_many ():
    use_all (step_todo1, wait_complete=False)
    use_all (step_todo2, args2)
    use_all (step_todo3)

The use_all is the main "executive" to process the steps (exactlypxssh for installation). It shall not be decorated with start/stop comments as may be called several times from a procedure (e.g. step_many which is reboot - reason for no wait_complete), but single step shall be.

As the use-case is specific, I may see solution to handle the *args as _single named variable containing tuple, e.g.

def use_all (step_todo, wait_complete=True, args_list=()):

Is this correct (and recommended) solution?

This is somehow linked to questions python function *args and **kwargs with other specified keyword arguments or Using default arguments before positional arguments . Is it possible not to parse kwargs and keep Python R2.7?

Thanks Jan

2

There are 2 best solutions below

5
On BEST ANSWER

You need to do this:

def use_from(step_todo, *args):
    use_all(step_todo, *args)

...otherwise you are calling use_all with a single arg containing a list of values, instead of calling it with the multiple args

also, don't put a space between your function and the parentheses, it's bad style :)

to get around the problem of wait_complete taking value of your first arg you need to pass it explicitly, eg:

def use_from(step_todo, *args):
    use_all(step_todo, True, *args)
0
On

That is not possible to do in Python 2.7, however in python 3.x you could:

def use_all (step_todo, *args, wait_complete=True):
    print('W_C: {0}'.format(wait_complete))
    print('Args: {0}'.format(args))

def use_from (step_todo, *args, **kwargs):
    use_all (step_todo, *args, **kwargs)

use_from ('Step1')
use_from ('Step3', 'aa:bb:cc')

Ouput:

>>> W_C: True
>>> Args: ()
>>> W_C: True
>>> Args: ('aa:bb:cc',)