tags:

views:

46

answers:

3

I'm porting some code from Perl to Python, and one of the functions I am moving does the following:

sub _Run($verbose, $cmd, $other_stuff...)
{
  ...
}

sub Run
{
  _Run(1, @_);
}

sub RunSilent
{
  _Run(0, @_);
}

so to do it Python, I naively thought I could do the following:

def _Run(verbose, cmd, other_stuff...)
  ...

def Run(*args)
  return _Run(True, args);

def RunSilent
  return _Run(False, args);

but that doesn't work, because args is passed as an array/tuple. To make it work, I did the following:

def _Run(verbose, cmd, other_stuff...)
  ...

def Run(*args)
  return _Run(True, ','.join(args));

def RunSilent
  return _Run(False, ','.join(args));

but that looks kind of ugly. Is there a better way?

+5  A: 

The * can be used for passing (positional) arguments too.

def Run(*args):
  return _Run(True, *args)

Note that, with only this, you can't call the function with keyword arguments. To support them one need to include the ** as well:

def Run(*args, **kwargs):
  return _Run(True, *args, **kwargs)

Actually you could declare the function as

def run(cmd, other_stuff, silent=False):
   ...

then it could be called as

run("foo", etc)               # Run
run("foo", etc, silent=True)  # RunSilent
KennyTM
Thanks. I did end up going with this: def run(cmd, other_stuff, silent=False):Sometimes, while porting this Perl stuff, I get too literal, and don't stop and think how I would do it in Python.
Cliff
A: 
def Run(*args, **kwargs)
  return _Run(True, *args, **kwargs);
Tomasz Wysocki
+3  A: 

There's also functools.partial:

from functools import partial

Run = partial(_Run, True)
RunSilent = partial(_Run, False)

This will create the two functions you want. Requires python 2.5 or higher.

Ivo van der Wijk