faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

1 of 1 people (100%) answered Yes

Entry

Requiring arguments to be passed as keyword arguments

Jul 5th, 2000 10:02
Nathan Wallace, Hans Nowak, Snippet 245, Evan Simpson


"""
Packages: core_python
"""
"""
> >Sometimes I would like to write functions with arguments that are
> >REQUIRED to be passed as keyword arguments rather than positional
> >arguments.  For example, for the following function I might want the
> >second parameter to be passed as a keyword parameter:
> >
> >    f(1, 2) # Exception
> >    f(1, variation=2) # OK
> >
>
> This is a kludge, but you can avoid accidental positional arguments if you
> stick in a tuple argument:
> >>> def f(x, (donotuse,)=(None,), variation=57):
> Wish list #1: A non-kludge way of doing this.
> Wish list #2: A way to specify a default argument that cannot be changed
> when called.
Less of a kludge, but longer and slower:
"""
def _fkw_f(a, b, kw1, kw2=3):
  # kw1 and kw2 are forced-keyword.
  print a, b, kw1, kw2
def f(a, b=1, **kw):
  # Fixed-arg default values must live here
  return apply(_fkw_f, (a, b,), kw)
"""
>>> f('a')
...TypeError: not enough arguments; expected 3, got 2
>>> f('a', 'b', 'kw1')
...TypeError: too many arguments; expected 2, got 3
>>> f('a', 'b', kw1='kw1')
a b kw1 3
>>> f('a', 'b', kw1='kw1', kw2='kw2')
a b kw1 kw2
>>> f('a', 'b', kw1='kw1', zoob=7)
...TypeError: unexpected keyword argument: zoob
"""