3

What's your preferred way of processing configuration parameters?

For example:

test(this=7)

could be processed by:

def test(**kw):
  this = kw.pop('this', 1)
  that = kw.pop('that', 2)

or

def test(**kw):
  if 'this' in kw:
      this = kw['this']
  else:
      this = 1
  if 'that' in kw:
      that = kw['that']
  else:
      that = 2

Is there a better (more pythonic) way?

2
  • 1
    what's wrong with def test(this=1, that=2): ? Commented Oct 21, 2011 at 18:34
  • @JBernardo - nothing, although it can get unwieldy if there are lots of parameters Commented Oct 21, 2011 at 18:36

2 Answers 2

3

If the possible parameters and defaults are fixed, the Pythonic way is to write:

def test(this=1, that=2):
    ...

If the parameter list is dynamic, your approach with kwds.pop() has a nice advantage of letting you verify that all the arguments were used (detecting misspelled parameter names for example). It is instructive to look at a fragment from the code generated by collections.namedtuple('Point', ['x', 'y'], verbose=True). Notice the final check to make sure all arguments were consumed from kwds:

    def _replace(_self, **kwds):
        'Return a new Point object replacing specified fields with new values'
        result = _self._make(map(kwds.pop, ('x', 'y'), _self))
        if kwds:
            raise ValueError('Got unexpected field names: %r' % kwds.keys())
        return result 
Sign up to request clarification or add additional context in comments.

1 Comment

The final check is a nice touch
1

I personally like to loop through the key/value pair's like so:

def test(**kw):
    for k, v in kw.items():
        if k == 'this':
            something = v
        # etc...

2 Comments

How do you set default values?
With **kw alone you wouldn't. If I needed default values for parameters I would do test(a=1, b=2, **kwargs).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.