What is a function parameter =[] for?

Marko Rauhamaa marko at pacujo.net
Fri Nov 20 11:41:42 EST 2015


Ian Kelly <ian.g.kelly at gmail.com>:

> On Fri, Nov 20, 2015 at 9:24 AM, Chris Angelico <rosuav at gmail.com> wrote:
>> The cases where that's not true are usually ones that are more like
>> C++ overloaded functions:
>>
>> def next(iter):
>>     return iter.__next__()
>> def next(iter, default):
>>     try: return iter.__next__()
>>     except StopIteration: return default
>
> IMO the version with the default argument should have a different
> name, as it is conceptually a different function.

I don't necessarily disagree, but consider this function:

   socket.create_connection(address[, timeout[, source_address]])

   <URL: https://docs.python.org/3/library/socket.html?highlight=conne
   ct#socket.create_connection>

It has been implemented:

   _GLOBAL_DEFAULT_TIMEOUT = object()

   def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT,
                         source_address=None):

which is somewhat inconsistent. Why not:

   def create_connection(address, timeout=None, source_address=None):

or:

   omitted = object()

   def create_connection(address, timeout=omitted,
                         source_address=omitted):

The argument for the former is that neither timeout nor source_address
can meaningfully be None. The argument for the latter is that it follows
a generic pattern that places no assumptions on the legality or
illegality of None as a value.

The chosen implementation allows:

    s.create_connection(address, source_address=None)

but not:

    s.create_connection(address, timeout=None)


Marko



More information about the Python-list mailing list