How to detect that a function argument is the default one

Skip Montanaro skip.montanaro at gmail.com
Wed Dec 10 10:29:34 EST 2014


On Wed, Dec 10, 2014 at 9:14 AM, ast <nomail at invalid.com> wrote:
> I have the idea to write:
>
> def __init__(center=(0,0), radius=10, mass=None)):
>
>    if  mass == None:        self.mass = radius**2
>    else:
>        self.mass = mass
>
> but maybe Python provides something clever.

This is almost the correct idiom. In general, pick defaults from
values outside your valid domain. None is often perfect for
this. Since you're comparing to a singleton value, "is" is the usual
comparison, so your code becomes:

def __init__(center=(0,0), radius=10, mass=None)):
    if mass is None:
        self.mass = radius**2
    else:
        self.mass = mass

At the programming level, Python generally tries not to be too clever,
especially for real basic stuff. From the Zen of Python:

    >>> import this
    The Zen of Python, by Tim Peters

    ...
    Explicit is better than implicit.
    ...

Guido could have been more clever here, but it wouldn't have likely
gained much (you'd still have to detect the default and set the value
appropriately), and perhaps made the code a (small) bit harder to
read.

Skip



More information about the Python-list mailing list