Requiring arguments to be passed as keyword arguments
Duncan Booth
duncan at rcp.co.uk
Tue Oct 5 12:18:04 EDT 1999
mhagger at blizzard.harvard.edu (Michael Haggerty) wrote in
<xj0zoxyjqwt.fsf at cyclone.harvard.edu>:
>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):
... print "x=%s variation=%s" % (x, variation)
...
>>> f(1)
x=1 variation=57
>>> f(1,2)
Traceback (innermost last):
File "<stdin>", line 1, in ?
File "<stdin>", line 1, in f
TypeError: unpack non-sequence
>>> f(1, variation=2)
x=1 variation=2
This doesn't stop malicious use of positional arguments but it will fix the
case you were asking about.
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