Suanmeiguo
Suanmeiguo

Reputation: 1405

How to skip providing default arguments in a Python method call that has a long list of named args that have defaults?

I'm calling this method from the Python boto2 library:

boto.emr.step.StreamingStep(name, mapper, reducer=None, combiner=None, action_on_failure='TERMINATE_JOB_FLOW', cache_files=None, cache_archives=None, step_args=None, input=None, output=None, jar='/home/hadoop/contrib/streaming/hadoop-streaming.jar')

I know that arguments after mapper have default values so I don't have to specify their values. But what if I want to pass a value for just one argument at the very end? For example, I want to provide values for the name, mapper, and combiner parameters, and just use the default value for reducer.

Should I do this:

boto.emr.step.StreamingStep('a name', 'mapper name', None, 'combiner name')

Or should I expressly pass all arguments before it?

If there are 100 arguments, and I just want to pass a value for the very last argument, then I have to pass many default values to it. Is there a easier way to do this?

Upvotes: 14

Views: 30558

Answers (3)

mhlester
mhlester

Reputation: 23211

There are two ways to do it. The first, most straightforward, is to pass a named argument:

boto.emr.step.StreamingStep(name='a name', mapper='mapper name', combiner='combiner name')

(Note, because name and mapper were in order, specifying the argument name wasn't required)


Additionally, you can pass a dictionary with ** argument unpacking:

kwargs = {'name': 'a name', 'mapper': 'mapper name', 'combiner': 'combiner name'}
boto.emr.step.StreamingStep(**kwargs)

Upvotes: 24

DhruvPathak
DhruvPathak

Reputation: 43235

  1. Do not use positional arguments,instead use keyword arguments.

  2. If it is mandatory to use positional arguments,use *args list, populate it with default values using a loop or something ,and set last argument, then pass it to the method.

Upvotes: 1

BrenBarn
BrenBarn

Reputation: 251355

Just pass the arguments you want by keyword: boto.emr.step.StreamingStep(name='a name', mapper='a mapper', combiner='a combiner')

Upvotes: 5

Related Questions