[Python-ideas] 'default' keyword argument for max(), min()

Nick Coghlan ncoghlan at gmail.com
Sat Apr 18 14:17:35 CEST 2009


spir wrote:
> The issue as I see it is related to the fact that python does not
> allow optional arguments without default values -- which in most
> cases is not problematic. But here I would like an hypothetical 
> min(s, optional default) or min(s, ?default)

Actually, you can have true optional arguments in Python. They're
especially easy to do for functions written in C, but there a couple of
common tricks for writing them in pure Python as well:

1. Extract the optional keyword-only argument manually (this most
closely mimics the approach used for optional arguments in C code, and
is also the only way to get keyword-only arguments in Python 2.x)

  def f(**kwds):
    try:
      arg = kwds.pop("optional")
      have_arg = True
    except KeyError:
      have_arg = False
    if kwds:
      raise TypeError("Unexpected keyword arguments")
    return have_arg

>>> f()
False
>>> f(optional=None)
True
>>> f(fred=1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 8, in f
TypeError: Unexpected keyword arguments
>>> f(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: f() takes exactly 0 arguments (1 given)

The downside of that approach is that you have to check for unexpected
keyword arguments yourself, which leads directly to the second approach.

2. Use a custom sentinel value to indicate a missing keyword-only
argument (this only works in Python 3.x where keyword-only parameter
syntax is available)

MISSING = object()
def f(*, optional=MISSING):
    return optional is not MISSING

>>> f()
False
>>> f(optional=1)
True
>>> f(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: f() takes exactly 0 positional arguments (1 given)
>>> f(fred=1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: f() got an unexpected keyword argument 'fred'

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------



More information about the Python-ideas mailing list