How to detect that a function argument is the default one

Marko Rauhamaa marko at pacujo.net
Wed Dec 10 11:33:45 EST 2014


Skip Montanaro <skip.montanaro at gmail.com>:

> 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

In this case, None works well. However, sometimes None is a valid input
value. Then, a sentinel object is the way out:

        
    _OMITTED = object()

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


Marko



More information about the Python-list mailing list