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?
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
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.
精彩评论