Requiring arguments to be passed as keyword arguments

Evan Simpson evan at tokenexchange.com
Wed Oct 6 15:41:16 EDT 1999


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

As for Wish #2, how about

def f([args] ; [initialized locals]): [suite]

as in:

def f(a, b=2, **kws;
         split, join, x=mm.getx()):
  pass
  # split, join, and x are initialized locals.
  # split and join are shorthand for 'split=split' and 'join=join'
  # initializing values are evaluated the same way as default values.

Basically, this would act on local variables like

def f(a, b=2, split=split, join=join, x=mm.getx(), **kws): pass

but look like this to callers:

def f(a, b=2, **kws): pass

Duncan Booth <duncan at rcp.co.uk> wrote ...
> mhagger at blizzard.harvard.edu (Michael Haggerty) wrote...
>
> >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.
>






More information about the Python-list mailing list